0% found this document useful (0 votes)
26 views

File

Uploaded by

Amogh Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

File

Uploaded by

Amogh Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 212

ICSE 10

2024-25

SAVIOUR OF
COMPUTERS

A Complete Saviour of ICSE Class 10


Computer Applications. It Includes -:
Theory Notes
Programming Notes
50 Most Important Program
Last 10 Years Solutions
TABLE OF CONTENTS

CLASS 10TH THEORY NOTES CLASS 10TH


PROGRAMMING
Comprehensive Coverage: Provides NOTES
detailed explanations of all ICSE Class
Step-by-Step Guidance:
10 Computer Science topics.
Clear instructions for every
Structured Learning: Organized in a
systematic manner for easy programming concept.
understanding and quick revision. Code Snippets: Examples
Clarity and Conciseness: Presents of code for easy
understanding and
complex concepts in a clear and
reference.
concise manner, aiding retention.
Illustrative Examples: Includes
relevant examples to reinforce
theoretical concepts.
50 MOST
IMPORTANT
PROGRAM
LAST 10 YEARS SOLUTIONS Core Program Coverage:
Includes essential
Exam-Oriented: Contains solutions to
programs crucial for ICSE
previous 10 years' ICSE Computer
Class 10 Computer
Science exam papers.
Science.
Understanding Patterns: Helps
Practical Examples:
students understand recurring
Provides practical
question patterns and exam trends.
applications of
Application of Concepts:
programming concepts in
Demonstrates application of theory in
each program.
solving exam-style questions.
Problem-Solving Practice:
Evaluation Tool: Allows self-
Offers opportunities for
assessment and practice for better
students to practice
exam preparation.
problem-solving
techniques.

code is easy 4.0


#saviouroficse
SAVIOUR OF
COMPUTERS

THEORY
NOTES
CHAPTER

CLASS AS THE BASIS


OF ALL COMPUTATION

OBJECT OBJECT

Entity which have Characteristics and Behaviour. OBJECT IS TERMED AS


For example ,
THE INSTANT OF THE
CLASS AND SO THE
PROCESS OF CREATING
A OBJECT IS KNOWN
Real World Objects INSTANTIATION .

Characteristics Behavior Syntax -:


Software Objects
Classname Objectname = name
Classname () ;

Methods
Car benz = new car () ;
Data Member
Car swift = new swift () ;

CLASS
DEFINING A CLASS AND
Blueprint of the Object ITS SYNTAX

Syntax of class :
Representation of Similar objects class classname
{
type instance - variable;
Car (Class)
type methodname1(parameter-list)
{
Swift Object 1
//body of method
Benz Object 2 }
Endeavour Object 3 type methodname2(parameter-list)
Verna Object 4 {
//body of method
}
}
CHAPTER

CLASS AS THE BASIS


OF ALL COMPUTATION

ACCESS SPECIFIER
OBJECT

Decides how parts of the classes can be accessed by other classes in other
parts of the program // defines the scope of visibility of the particular code.

Visibility Rules

DATA TYPES IN JAVA


CHAPTER

CLASS AS THE BASIS


OF ALL COMPUTATION

PRIMITIVE DATATYPES
[PRE DEFINED]

BYTE INT

1. Byte Datatype is an 8-bit signed two 1. int datatype is a 32-bit signed two's
complement Integer. complement integer.
2. Minimum value is -128 or (-2)^7. 2. Minimum value is - 2,147,483,648 or
3. Maximum value is 127 (inclusive) or (-2)³¹.
(2^7-1). 3. Maximum value is
4. Default value is 0. 2,147,483,647(inclusive) or (2³¹– 1).
5. Example, Byte a = 100 and Byte b = 4. The default value is 0.
-50. 5. Example, int a = 100000, int b =
-200000.

SHORT LONG

1. Short Short datatype is a 16-bit 1. long datatype is a 64-bit signed


signed two's complement integer. two's complement integer.
2. Minimum value is -32,768 or (-2)^15. 2. Minimum value is
3. Maximum value is 32,767 (inclusive) -9,223,372,036,854,775,808 or
or (2^5- 1). (-2)^63.
4. Default value is 0 3. Maximum value is
5. Example, short s 10000, short r = 9,223,372,036,854,775,807
-20000. (inclusive) (2^63-1)
4. This type is used when a wider range
than int is needed.
5. Default value is OL.
6. Example, long a = 100000L, long b =
-200000L.
CHAPTER

CLASS AS THE BASIS


OF ALL COMPUTATION

PRIMITIVE DATATYPES
[PRE DEFINED]

DOUBLE CHAR

1. double datatype is a double- 1. char datatype is a single 16-bit


precision 64-bit IEEE 754 floating Unicode character.
point. 2. Minimum value is \u0000' (or 0).
2. double datatype should never be 3. Maximum value is \uffff' (or 65,535
used for precise values such as inclusive).
currency 4. char datatype is used to store any
3. Default value is 0.0d. character.
4. Example, double d1 = 123.4. 5. Example, char letterA = 'A'.

BOOLEAN

1. boolean datatype represents one bit


of information.
2. There are only two possible values:
true and false.
3. This datatype is used for simple flags
that track true/false conditions.
4. Default value is false.
5. Example, boolean one = true.
CHAPTER

CLASS AS THE BASIS


OF ALL COMPUTATION

REFERENCE DATA TYPES

non-primitive Data types are called reference types because they refer to objects. The
main difference between primitive and non-primitive data types are:
Primitive types are predefined (already
defined) in Java. Non-primitive types are
created by the programmer and is not
defined by Java (except for String).

DATA (OR MEMBER DATA OR INSTANCE VARIABLES OR ATTRIBUTES):

The variables declared within the class on which some operations are to be performed
are known as data or data members or instance variables or attributes or fields.

// see that a, b are integer and x, y


Example:-int a, b float x, y
are floating data members

// here ch is a character and m is


char ch long m
long type data members

METHODS (OR FUNCTION OR BEHAVIOUR):

A method is a block of code that only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform specific actions, and they are also
known as functions.
CHAPTER

CLASS AS THE BASIS


OF ALL COMPUTATION

WHY DO WE NEED A CLASS?: PRIMITIVE DATA TYPES

Classes are required in OOPs The variables declared using short, int,
because It provides a template for long, float, double, char, byte, and
creating objects, which can bind boolean are called primitive data types
code into data. It has definitions of
methods and data. It supports the
inheritance property of Object
Oriented Programming and hence
can maintain the class hierarchy.

COMPOSITE DATA TYPES:

A composite data type is any data type that


is composed of primitive data types as its
based type. In other words, it is an aggregate
of primitive types. Composite types in Java
are the array data structure and the class
data type.

DIFFERENCE BETWEEN PRIMITIVE AND COMPOSITE DATA TYPES:

Primitive data types Composite data types

These data types are defined by the user


They are predefined/inbuilt data
and made up of primitive data type
types.
values.

Examples: int, byte, long, short, char,


Examples: Array, class, interface.
float, double, boolean.
CHAPTER

CLASS AS THE BASIS


OF ALL COMPUTATION

VARIABLE (OR DATA MEMBER OR


ATTRIBUTE):
TYPES OF VARIABLES:
The variables declared within a class
along with the data type (like int, float, 1. Static variable or class variable
2. Instance variable
char, etc.) on which some operations to
be performed are known as data Static variable: The data member or variable
members or variables or attributes of the declared once for a class is known as a static
class / class variable.
Instance variable: The data member or
variable declared within the class is known
as an instance variable.

METHOD(OR FUNCTION) WITHIN THE


CLASS:
TYPES OF METHODS:
1. Static method
The method defined within the class to
2. Instance method
execute data members of the class(instance
variables or static variables) is known as the Static Method: The method which begins with
function or method within the class the static keyword is known as the static
method. These functions use only static
variables

Instance method: The method or function which


uses both static (or class) variables and instance
variables is known as an instance variable
CHAPTER

METHODS

INTRODUCTION METHODS

Methods are a set of statements that


Java is considered as one of the most popular can perform a specific task. Methods
programming languages. It is because of its versatility. are immensely useful in Java
One of the best features of Java is that the programmer because it can provide flexibility to
can use a piece of code multiple times. To be able to the program. It saves time as the user
use this feature to its full extent, the programmer can can reuse the same method
use methods. repeatedly without writing the code
multiple times.

NEED FOR METHODS

1. Reducing complexity: Methods provide the facility to divide a complex problem


into parts which can be called as and when required. Thus, this feature helps the
programmer to deal with the complexity of the code.

2. Code reusability: Once a problem has been defined as a method, then these
methods can be called anywhere in the program repeatedly. Thus, in helps to
reduce the duplication of the program. As add() method can be defined only once
and used repeatedly just by calling it.

3. Reduces length: It indirectly reduces the length of the compiled code as a


method once defined can be called again and again.

4. Hides the complexity: Methods are just like black boxes where a user need not
to be aware of the logic/code running behind the application.

3. Reduces length: It indirectly reduces the length of the compiled code as a


method once defined can be called again and again.

4. Hides the complexity: Methods are just like black boxes where a user need not
to be aware of the logic/code running behind the application.
CHAPTER

METHODS

DEFINING A METHOD TYPES OF USER


DEFINED METHODS.
A method must be defined before it is used anywhere in
a program. Any method consists of two parts: the (i) Static Methods: The static
header(prototype) and the body. Header is the first line methods are Class methods and
of a method definition. It contains access specifiers, belong to the class. They can be
return type, function name and the parameter list. The created by using the modifier
body is the block of statements that are executed when 'static' on the method prototype.
the method s called. They can be invoked directly
using just the name of the method
and the parameters required. You
SYNTAX: can also call them through an
object reference.
<specifiers><modifier>
<return_type>method_name(parameter1,parameter2..)
<exception list> (ii) Non Static Methods: The
{ methods that do not use the
// block of statements/method body keyword static in their prototype
} are known as non static methods.
These methods can be invoked by
creating the instance of an object.
METHOD CALLING/INVOKING
That is why, they are also
A method once defined can be called repeatedly just by known as Instance method.
calling the method name, followed by the parameters
list, if defined in method prototyping.
Examples:

1. if method prototype is
public void dispMessage() then calling statement is
dispMessage(); // calling a method with no parameters.

2. if method prototype is private int cube (int x) then


calling statement is int a = cube(5); //as cube() method is
with argument, thus 5 (constant) has been sent as
parameter. This method is of integer return type, so int
a (variable) is used to store the result.
CHAPTER

METHODS

CALL BY VALUE

When a method is called by its parameter as value, it is known as call by value.


Points to Ponder:
When a method is called by value, the actual parameters are copied to the formal parameters.
Any change made to the formal parameters do not affect or change the actual parameters.
Memory is allocated separately for actual and formal parameters.
Hence, while calling by value, the actual parameters can be constants and expressions also.
It is not mandatory that only variables should be passed.

SYNTAX:

type method_name (type var1, type var2...) //method definition


method_name (value1, value2); // method call

CALL BY REFERENCE

All the data is stored in the memory which is divided into cells. Each cell has a unique address.
The term reference, stores memory location of a variable.
Points to Ponder:
When a method is called by reference, the actual parameters are not copied to the formal
parameters.
The memory is not allocated separately for actual and formal parameters.
Any change made to the formal parameters will automatically update or change the value of
the actual parameters.
While calling by reference it is mandatory that only object or array variables should be passed.
The actual parameters cannot be constants and expressions.

SYNTAX:

type method_name (class_name obj2) //method definition


obj1.method_name (obj1 ); // method call

METHOD OVERLOADING

In Java, two different methods can have the same name if the parameter types or number of
parameter passed are different. The parameter types and number of parameter are called the
signature of methods. When more than one method with the same name exist in the same
program with different signatures, this is called method overloading.
CHAPTER

CONSTRUCTOR

INTRODUCTION

So far, you have studied the methods and the way they
work in Java. Now you will be learning a different type
of method. It is known as a constructor and its most
distinguishing feature is that it is named after the class it
is in. Let us find out more about the constructor. CHARACTERISTICS

A constructor will have


CONSTRUCTORS
the same name as that of
the class.
A constructor is a special member method of a class
A constructor does not
without a return type. It is used for initialising and
have a return type not
constructing the data members of an object when it is
even void.
created. It is automatically called (invoked) when the
A constructor cannot be
object is created using new operator. It cannot be
static or final.
invoked by the user like normal methods. A constructor must be
declared public (if it has to
NEEED OF A CONSTRUCTOR be accessed outside the
class).
A constructor is used for initialising and constructing the It is automatically called
data members of an object with legal values when it is (invoked) when an object
created. Data members are mostly declared as private is created.
members, to implement data hiding and abstraction.
Due to this, data members cannot be initialised outside
the class with values. So, constructors are used for
initialising the objects implicitly as they are created.

DECLARING AND DEFINING

Being a method, it also gives the programmer the ability to define, declare and modify. Since, a
constructor has no return type (not even void), it also provides the programmer with the liberty to
define a constructor with or without a parameter. A simple constructor is created using the new
operator followed by the name of the class.
Syntax:
<access specifier> class_name (parameter list/void)
{
Data_member1 = value1 ; Data_member2 = value2;
}
CHAPTER

CONSTRUCTORS

EXAMPLE:

class Book
{ int bookno;
String name;
float price;
public Book()
//constructor is created, having same name Book as that of
{ bookno = 0;
its class name Book, with public access specifier and no
name = "ABC";
return type.
price=0.0
} }

TYPES OF CONSTRUCTORS

The main function of a constructor is to initialise the data members of an object while it is
created. Constructors can be broadly categorised into two categories based on the parameters
it takes:

Default constructor : A constructor that takes no parameters.

Parameterised constructor : A constructor that takes one or more parameters.

DEFAULT CONSTRUCTOR/NON PARAMETERISED CONSTRUCTOR

A constructor that takes no parameters is called a default constructor. It will have the name of the
class and have no return type. If you do not write a constructor in your program, the compiler will
supply a default constructor and initialise values with the default values of the primitive data
types i.e. integer variables to zero, floating point variables to 0.0 and String to null.
Syntax:
class_name()
{ Data_member1 = value1;
Data_member2 = value2;
}
CHAPTER

CONSTRUCTOR

PARAMETERISED CONSTRUCTOR

Constructor that takes one or more parameters or arguments is called as a parameterised


constructor. Such a constructor will accept values and initialise the data members with the
corresponding values. There is no limitation to number of parameters.
Syntax:
class_name (type1 val 1, type2 val 2...)// parameter list
{
Data_member1 = val 1;
Data_member2 = val 2;
}
'THIS' KEYWORD

'this' keyword is used within a constructor to refer to the current object. It is actually a
reference to the object that invokes the constructor. In fact, even if you do not use the this
keyword, the compiler normally implicitly converts it by prefixing this to the data members.

CONSTRUCTOR MEMBER METHODS


name: always similar to class name name: according to user
return type: no return type return type: void or valid
need: to initilalise member variables need: to avoid repetition and to
increase code reusability.

CONSTRUCTORS WITHIN CONSTRUCTORS USING 'THIS'

Constructors can be chained together by invoking a constructor from within another


constructor. The this keyword is used to invoke another constructor from within the class.
When constructors are chained this way, the control just moves from one constructor to the
other till the data members are initialised and the object is fully constructed.
CHAPTER

LIBRARY CLASSES

DATA TYPE

The data type refers to the identification of the type of data(or variable) which is used to
perform some operations.
COMPOSITE DATA TYPE
The data type which combines primitive data types is known as composite data type.
USER DEFINED DATA TYPE
The data type created by the user to perform some task is known as user defined data
type.
class is a composite data type.

WRAPER CLASS

The class that converts primitive or fundamental data types into its
corresponding object types and vice-versa is known as wrapper class.

primitive type wrapper class


byte Byte

short Short

int Integer

long Long

double Double

AUTOBOXING AND UNBOXING

AUTO BOXING
It converts primitive data type into its corresponding wrapper class object.

UNBOXING
It converts wrapper class into its corresponding primitive data type.
CHAPTER

LIBRARY CLASSES

DATA TYPE

Java has some functions which converts numeric data into string and vice -versa.
toString( )
parse
valueOf( )

toString( ) : used to convert numeric data into


string data and vice-versa.

parse : used to convert numeric type


string into corresponding primitive data type.

valueOf( ) : used to convert numeric string


into corresponding primitive data type object.

CHARACTER FUNCTIONS

FUNCTION WHAT IT RETURNS?


isLetter(char) it returns true if character is a letter.

isDigit(char) it returns true if character is a digit.

isLetterOrDigit(char) it returns true if character is a letter or digit.

isWhitespace(char) it returns true if character is a blank space

isSpaceChar(char) it returns true if character is a unicode space

it returns true if character is an upper case letter


isUpperCase(char)

isLowerCase(char) it returns true if character is an lower case letter

toUpperCase(char) it converts character into upper case

PRO TIP : agr kisi bhi function ke samne "is" dikhe


toh samagh jana ki voh boolean return karega.
CHAPTER

ENCAPSULATION &
INHERITANCE

INTRODUCTION

Wrapping up data and methods into a single unit is


known as encapsulation. Data encapsulation is the most
important feature of a class. The data is not accessible
to the outside world. They can be accessed only by its NOTE :
methods, which are wrapped within the class. Methods
serve as an interface between the data of the object Java implements data
and the program. This process of protecting data from encapsulation and
direct access by the program is called data hiding or abstraction through
information hiding. visibility modifiers.
The visibility modifiers
allow the user to control
ENCAPSULATION which members other
classes can have access
Encapsulation is a protective wrapper that prevents the to.
code and data from being accessed directly by other The visibility modifiers in
codes defined outside that wrapper. In Java, the basis Java are public, private,
of encapsulation is a class which is used to define the protected and
structure and the behaviour which will be shared by a default(friendly).
set of objects.

VISIBILITY MODIFIERS

In Java, the visibility modifiers (access specifiers) allows the user to control which members of a class
can be accessed by others or other classes can have access to. Java specifies different levels of
access to each of these specifiers. It is through these access specifiers that Java implements data
abstraction. The most commonly used are public and private. public-the member is accessible from
all classes inside or outside the package. private-the member is accessible only within its own class.
protected-the member is accessible by any subclasses or other classes in the same package or any
other package. This is normally used with inherited classes. default(friendly)-the member is accessible
by any subclasses or other classes in the same package. It will not be accessible outside the package
even if they are subclasses.
CHAPTER

ENCAPSULATION &
INHERITANCE

SCOPE AND VISIBILITY RULES

Scope determines the extent to which a particular block


of code or data item can be accessed. Hence, the part
of the program in which a block of code or data item
can be accessed is known as its scope. Visibility is
related to scope which means whether a variable/item
can be used from a specific place in the program or not. NOTE :
Java uses the visibility modifiers to define the scope
The part of the program in
and visibility of the program parts.
which a block of code or
data item can be
RULES OF VISIBILITY
accessed is known as its
scope
All data members are declared at the class level
A public static member of
irrespective of the modifier being accessible within
a public class will not be
the same class. Such data are called global data.
accessible to any class
All data declared within the methods are accessible
outside the package even
only within the same method. Such data are called though both the member
local data. They go out of scope as soon as the and the class are declared
method is over. public.
All data members declared within a block i.e. within
curly braces, are accessible only within the same
block. They go out of scope as soon as the block is
over.
All data declared outside a block can be accessed
within a block.
A public static member belongs to a class.
A public static member of a public class will not be
accessible to any class outside the package even
though both the member and the class are declared
public.
CHAPTER

ENCAPSULATION &
INHERITANCE

VISIBILITY MODIFIER'S SUMMARY CHART

Subclass in
in the same other Everywhere/ Outside
Modifiers Class
package packages package

private Yes No No No
Yes (with related
protected Yes Yes Yes
subclasses only)

public Yes Yes Yes Yes

default Yes Yes Yes No

DATA HIDING.

You might be wondering, how does specifying the access permissions of the class
implement encapsulation?

That's because the aim behind the concept to encapsulation was to hide the details of the
implementation procedure. The user should only know how to use the program not the
intricacies. This is why encapsulation is also known as data hiding.

ACCESSOR AND MUTATOR

A function which is used to access private data members is called an Accessor ar Getter
method.

A function which is used to change the value of a private data member is called a Mutator
or Setter method. Such methods keep the instance variables safe and secure from the
outside interference and implement encapsulation.
CHAPTER

ENCAPSULATION &
INHERITANCE

IMPORTANCE OF ACCESSOR AND MUTATOR


METHODS

The goal of object oriented programming is to make the data secure. In that interest,
accessor and mutator play a very important role. If the variables of a class are not private
then they can be accessed and modified from anywhere. This is a very dangerous
scenario as it can lead to massive data loss. To prevent such a thing, the access to data is
kept limited and setter or getter methods are used to access the data. These methods
help the user to alter the data in a controlled manner. Hence, only the user can change
the data.

ADVANTAGES OF ENCAPSULATION

Flexibility: It gives more versatility to user as the implementation details are hidden. So,
the logic can be changed easily. In other words encapsulation helps us create flexible
codes that can be easily changed and maintained. Program
Logic is hidden: When the user uses an encapsulated code, he/she is only capable of
updating and viewing the data through setter and getter methods. The working of
these methods are completely hidden from the user.
Data Hiding: Encapsulation enables the programmer to hide valuable data by making it
private.
Programmers become more powerful: The programmer decides what to show and
what not to. If a programmer decides not to allow any setter methods then the user can
only view the data without any modification

INHERITANCE

Inheritance is the process by which objects of one class acquire/inherits the properties of
objects of another class.

For example, let us consider a class Plant. Three classes: class Herb, class Shrub and class
Tree are all parts of the class Plant and have a few common properties. So the uppermost
class is called the Base class and classes that acquire its properties are called Derived
classes. Each derived class shares common characteristics with the base class and will
have the combined features of both the classes.
CHAPTER

ENCAPSULATION &
INHERITANCE

INHERITANCE

Here, class Tomato, Mustard, Sunflower are the derived classes of the class Herb.
Class Herb is the base class of the class Tomato, Mustard, Sunflower.
Inheritance provides the facility of reusability. Which means that additional
features can be added to an already existing class without modifying it. This is
possible when a new class is derived from the existing one.
The new class will have the combined features of both the classes
Each derived class should define only those features that are unique to it.

NOTE:

Inheritance is the process by which objects of one class acquire the properties of the
objects of another class.
Inheritance provides the facility of reusability.
CHAPTER

STRINGS

CHARACTER

Any alphabet , digit or a symbol is known as a character


example: A, c, 6, +,5 etc.

CHARACTER CONSTANT (OR CHARACTER LITERAL)

Single character enclosed within single inverted


commas is know as character constant example: 'A', 'c',
'6', '+', '5' etc.

STRING

Sequence of character with or without space is known


as string. example: CLARIFYopBOLTE, CKOP.

STRING CONSTANT

Sequence of characters with or without spaces


enclosed within double inverted commas is known as
string constant example: "CLARIFYopBOLTE", "CKOP".

STRING VARIABLE

The variable or identifier that stores a string constant is


known as a string variable.
ASCII CODES

'A' -'Z' : 65-90 '


Example: String nam; // here String is a data type and a'-'z' : 97-122
'nam' is a string variable. '0'-'9' : 48-57
Space character : 32
The string creates a single dimensional array of
characters and each character of the string stores in
diffrent memory indexes
CHAPTER

STRINGS

STRING INPUT

To input a string from the input device string class is used. The string class creates a string
of fixed length which can not be altered or modified.
The following functions can be used to input a string :
readLine()
nextLine()
next()

readLine()
The readLine() method of Console class in Java is used to read a single line
of text from the console.
syntax: string_variable/string_object = input_buffer_variable.readLine( );

nextLine()
This function is used to input a line of text or string from input using scanner
class.
syntax: string_variable/string_object = scanner_object.nextLine( );

next()
This is used to input a string without any space from the input using
Scanner class
syntax: string_variable/string_object = scanner_object.next( );
CHAPTER

STRINGS

STRING FUNCTIONS (OR STRING METHODS)


length(): it returns length of a string
length: it returns length of an array
charAt(): it returns the character present at the index specified from any
string
indexOf(): it returns the index number of a character specified in the
brackets from a string object
lastIndexOf(): it returns the last index number of a character specified in
the brackets from a string object
replace(ch1, ch2): it replaces or changes all the occurrences of a
character by a new character in a string
trim(): it trims/removes all the spaces present in the beginning and end
of the string except the spaces in between
substring(n): it returns the substring from a string starting from nth
index character upto the end of string
substring(n,m): it returns the substring from a string starting from nth
index character upto mth index character. excluding mth index i.e. till
mth^-1
toUpperCase(): it is used to convert a string into uppercase form
toLowerCase(): it is used to convert a string into lowercase form
concat(): it is used to join/concatenate two strings one after another
without any space
equals(S): This function returns true if the two string are equal,
otherwise returns false by taking the cases of the alphabets into
account i.e. upper case and lowercase letters are different
equalsIgnoreCase(S): This function returns true if the two string are
equal by ignoring the cases of letters, otherwise returns false
compareTo(S): it is used to compare two string lexicographically i.e.
length wise and character wise, and returns integer = 0 or > 0 or<0
compareToIgnoreCase(S): it is used to compare two string
lexicographically i.e. length wise and character wise by ignoring the
cases of the letters and returns = 0 or > 0 or<0
CHAPTER

ARRAYS

INTRODUCTION

Java array is an object which contains elements of a


similar data type. Additionally, The elements of an array ADVANTAGES
are stored in a contiguous memory location. It is a data
Code Optimization: It
structure where we store similar elements. We can store
makes the code
only a fixed set of elements in a Java array. optimized, we can retrieve
or sort the data efficiently.
REFERENCE DATA TYPES Random access: We can
get any data located at an
Suppose you face a situation where you have to prerare index position.
a report on the result of a class having 60 students. You
DISADVANTAGES
need to show names af students, roll no and marks
Size Limit: We can store
obtained. To simplify this, JAVA offers Reference data
only the fixed size of
types.
elements in the array. It
Reference data types are composed of primitive data
doesn't grow its size at
types which actually refers to the memory address of
runtime. To solve this
the data. These are Arrays, Classes and Interfaces.
problem, collection
framework is used in Java
ARRAYS which grows
automatically.
An array is defined as a named set of elements of
similar data types stored in contiguous locations. It acts
like a container to hold a fixed number of values of a
single type. For example: An integer array is a set of
integers stored under a single name. The length of the
array is established when the array is created.

TYPES OF ARRAY

ARRAYS

Single Dimensional Array Multi Dimensional Array


CHAPTER

ARRAYS

SINGLE DIMENSIONAL ARRAY

This is the simplest form of the array. They are also known as 1-D arrays.

For example: int A[10] represents the array of the integer data type that can hold 10
values. This memory location of A[10] will be A[0], A[1], A[2], . . A[9] .

MULTI DIMENSIONAL ARRAY

These are also known as 2-dimensional array. A 2-D array will be a table, or a matrix.
It would look like this:
or

SEARCHING TECHNIQUES IN ARRAYS

Sometimes you may need to search an element in an array. Then you can use different
searching techniques Searching an array involves traversing the array and searching for
a particular element. There are two main methods for searching Linear Search or
Sequential Search for unsorted arrays Binary Search for sorted arrays

BINARY SEARCH

You must be aware of the phrase 'Divide and Conquer'. Binary search uses this very
technique to find the given item in the array. Binary search technique is quite efficient but
it works on sorted arrays only, either ascending or descending. Theoretically, this
technique divides the array to form two arrays of equal size. It then looks for the element
in the first array, if found, returns the value, otherwise repeats the process on the next
array.
CHAPTER

ARRAYS

SORTING TECHNIQUES IN ARRAYS

Sorting involves arranging the array elements in ascending or descending


order if they are numeric arrays. In the case of String or character arrays, the
elements will be ordered alphabetically.

The main two sorting techniques are:


Bubble Sort
Selection Sort

BUBBLE SORT

This technique is mostly used for sorting the elements in a single dimensional array. In
bubble sort. as the elements are sequentially scanned and sorted (in
ascending/descending order), they gradually move to their proper location in the array like
bubbles. During each iteration, the pair of consecutive elements are compared and
interchanged if out of order. This sorting process continues until the last two elements of
the array are compared and swapped if out of order.It is an easy technique but it
consumes a lot of time when the number of exchanges are more. If there are 6 elements,
then five iteration are required. If there are 9 elements, then eight iterations are required.
The Bubble sort comes to an end when it examines the entire array and no more swapping
is needed.

SELECTION SORT

It is a combination of searching and sorting. Assume that we wish to sort the array in
increasing order. During each pass, the unsorted element with the smallest value is moved
to its proper position in the array (for ascending order). If an array has n elements, then the
number of passes will be n-1. In selection sort, the inner loop sends the next smallest value
and the outer loop swaps that values into proper index positions.
SAVIOUR OF
COMPUTERS

50 MOST
IMPORTANT
PROGRAMS
CHAPTER

CONDITIONAL
CONSTRUCTS

WRITE A PROGRAM TO INPUT THREE NUMBERS (POSITIVE OR


NEGATIVE). IF THEY ARE UNEQUAL THEN DISPLAY THE GREATEST
NUMBER OTHERWISE, DISPLAY THEY ARE EQUAL. THE PROGRAM
ALSO DISPLAYS WHETHER THE NUMBERS ENTERED BY THE USER
ARE 'ALL POSITIVE', 'ALL NEGATIVE' OR 'MIXED NUMBERS'.

import java.util.Scanner;
public class NumberAnalysis
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
System.out.print("Enter third number: ");
int c = in.nextInt();
int greatestNumber = a;
if ((a == b) && (b == c)) {
System.out.println("Entered numbers are equal.");
}
else {
if (b > greatestNumber) {
greatestNumber = b;
}
if (c > greatestNumber) {
greatestNumber = c;
}
System.out.println("The greatest number is " + greatestNumber);
if ((a >= 0) && (b >= 0) && (c >= 0)) {
System.out.println("Entered numbers are all positive numbers.");
}
else if((a < 0) && (b < 0) && (c < 0)) {
System.out.println("Entered numbers are all negative numbers.");
}
else {
System.out.println("Entered numbers are mixed numbers.");
}
}
}
}
CHAPTER

CONDITIONAL
CONSTRUCTS

A TRIANGLE IS SAID TO BE AN 'EQUABLE TRIANGLE', IF THE AREA


OF THE TRIANGLE IS EQUAL TO ITS PERIMETER. WRITE A PROGRAM
TO ENTER THREE SIDES OF A TRIANGLE. CHECK AND PRINT
WHETHER THE TRIANGLE IS EQUABLE OR NOT. FOR EXAMPLE, A
RIGHT ANGLED TRIANGLE WITH SIDES 5, 12 AND 13 HAS ITS AREA
AND PERIMETER BOTH EQUAL TO 30.

iimport java.util.Scanner;
public class EquableTriangle
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the 3 sides of the triangle.");
System.out.print("Enter the first side: ");
double a = in.nextDouble();
System.out.print("Enter the second side: ");
double b = in.nextDouble();
System.out.print("Enter the third side: ");
double c = in.nextDouble();
double p = a + b + c;
double s = p / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
if (area == p)
System.out.println("Entered triangle is equable.");
elseSystem.out.println("Entered triangle is not equable.");
}
}
}
CHAPTER

CONDITIONAL
CONSTRUCTS

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. EXAMPLE:
CONSIDER THE NUMBER 59. SUM OF DIGITS = 5 + 9 = 14 PRODUCT
OF DIGITS = 5 * 9 = 45 TOTAL OF THE SUM OF DIGITS AND PRODUCT
OF DIGITS = 14 + 45 = 59 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,
DISPLAY THE MESSAGE "SPECIAL 2 - DIGIT NUMBER" OTHERWISE,
DISPLAY THE MESSAGE "NOT A SPECIAL TWO-DIGIT NUMBER".

import java.util.Scanner;
public class SpecialNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a 2 digit number: ");
int orgNum = in.nextInt();
if (orgNum < 10 || orgNum > 99) {
System.out.println("Invalid input. Entered number is not a 2 digit
number");
System.exit(0);
}
int num = orgNum;
int digit1 = num % 10;
int digit2 = num / 10;
num /= 10;
int digitSum = digit1 + digit2;
int digitProduct = digit1 * digit2;
int grandSum = digitSum + digitProduct;
if (grandSum == orgNum)
System.out.println("Special 2-digit number");
elseSystem.out.println("Not a special 2-digit number");
}
}
CHAPTER

CONDITIONAL
CONSTRUCTS

WRITE A PROGRAM THAT ACCEPTS THREE NUMBERS FROM THE


USER AND DISPLAYS THEM EITHER IN "INCREASING ORDER" OR IN
"DECREASING ORDER" AS PER THE USER'S CHOICE.
CHOICE 1: ASCENDING ORDER
CHOICE 2: DESCENDING ORDER
SAMPLE INPUTS: 394, 475, 296
CHOICE 2
SAMPLE OUTPUT
FIRST NUMBER : 475
SECOND NUMBER: 394
THIRD NUMBER : 296
THE NUMBERS ARE IN DECREASING ORDER.

import java.util.Scanner;
public class BusFare
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter distance travelled: ");
int dist = in.nextInt();
int fare = 0;
if (dist <= 0)
fare = 0;
else if (dist <= 10)
fare = 80;
else if (dist <= 20)
fare = 80 + (dist - 10) * 6;
else if (dist <= 30)
fare = 80 + 60 + (dist - 20) * 5;
else if (dist > 30)
fare = 80 + 60 + 50 + (dist - 30) * 4;
System.out.println("Fare = " + fare);
}
}
CHAPTER

CONDITIONAL
CONSTRUCTS

A COURIER COMPANY CHARGES DIFFERENTLY FOR 'ORDINARY'


BOOKING AND 'EXPRESS' BOOKING BASED ON THE WEIGHT OF THE
PARCEL AS PER THE TARIFF GIVEN BELOW:
WEIGHT OF PARCEL ORDINARY BOOKING. EXPRESS BOOKING
UP TO 100 GM ₹80 ₹100
101 TO 500 GM ₹150 ₹200
501 GM TO 1000 GM ₹210 ₹250
MORE THAN 1000 GM ₹250 ₹300
WRITE A PROGRAM TO INPUT WEIGHT OF A PARCEL AND TYPE OF
BOOKING (`O' FOR ORDINARY AND 'E' FOR EXPRESS). CALCULATE
AND PRINT THE CHARGES ACCORDINGLY.

import java.util.Scanner;
public class CourierCompany
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter weight of parcel: ");
double wt = in.nextDouble();
System.out.print("Enter type of booking: ");
char type = in.next().charAt(0);
double charge = 0;
if (wt <= 0)
charge = 0;
else if (wt <= 100 && type == 'O')
charge = 80;
else if (wt <= 100 && type == 'E')
charge = 100;
else if (wt <= 500 && type == 'O')
charge = 150;
else if (wt <= 500 && type == 'E')
charge = 200;
else if (wt <= 1000 && type == 'O')
charge = 210;
else if (wt <= 1000 && type == 'E')
charge = 250;
else if (wt > 1000 && type == 'O')
charge = 250;
else if (wt > 1000 && type == 'E')
charge = 300;
System.out.println("Parcel charges = " + charge);
}
}
CHAPTER

CONDITIONAL
CONSTRUCTS

WRITE THE PROGRAMS IN JAVA TO FIND THE SUM OF THE


FOLLOWING SERIES:
(A) S = 1 + 1 + 2 + 3 + 5 + ....... TO N TERMS

import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int a = 1, b = 1;
int sum = a + b;
for (int i = 3; i <= n; i++) {
int term = a + b;
sum += term;
a = b;
b = term;
}
System.out.println("Sum=" + sum);
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

WRITE THE PROGRAMS IN JAVA TO FIND THE SUM OF THE


FOLLOWING SERIES:
(B) S = 2 - 4 + 6 - 8 + ....... TO N

import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;
for (int i = 1, j = 2; i <= n; i++, j = j + 2) {
if (i % 2 == 0) {
sum -= j;
}
else {
sum += j;
}
}
System.out.println("Sum=" + sum);
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

WRITE THE PROGRAMS IN JAVA TO FIND THE SUM OF THE


FOLLOWING SERIES:
(C) S = 1 + (1+2) + (1+2+3) + ....... + (1+2+3+ ....... + N)

import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int a = 1, b = 1;
int sum = a + b;
for (int i = 3; i <= n; i++) {
int term = a + b;
sum += term;
a = b;
b = term;
}
System.out.println("Sum=" + sum);
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

WRITE THE PROGRAM TO FIND THE SUM OF THE FOLLOWING


SERIES:
S = (A/2) + (A/5) + (A/8) + (A/11) + ....... + (A/20)

import java.util.Scanner;
public class Series
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
double sum = 0;
for (int i = 2; i <= 20; i = i + 3) {
sum += a / (double)i;
}
System.out.println("Sum=" + sum);
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

WRITE A PROGRAM TO ENTER TWO NUMBERS AND CHECK


WHETHER THEY ARE CO-PRIME OR NOT.
[TWO NUMBERS ARE SAID TO BE CO-PRIME, IF THEIR HCF IS 1
(ONE).]
SAMPLE INPUT: 14, 15
SAMPLE OUTPUT: THEY ARE CO-PRIME.

import java.util.Scanner;
public class Coprime
{
public void checkCoprime() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter b: ");
int b = in.nextInt();
int hcf = 1;
for (int i = 1; i <= a && i <= b; i++) {
if (a % i == 0 && b % i == 0)
hcf = i;
}
if (hcf == 1)
System.out.println(a + " and " + b + " are co-prime");
elseSystem.out.println(a + " and " + b + " are not co-prime");
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

WRITE A PROGRAM TO INPUT A NUMBER AND CHECK AND PRINT


WHETHER IT IS A PRONIC NUMBER OR NOT. [PRONIC NUMBER IS
THE NUMBER WHICH IS THE PRODUCT OF TWO CONSECUTIVE
INTEGERS.]
EXAMPLES:
12 = 3 * 4
20 = 4 * 5
42 = 6 * 7

import java.util.Scanner;
public class PronicNumber
{
public void pronicCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to check: ");
int num = in.nextInt();
boolean isPronic = false;
for (int i = 1; i <= num - 1; i++) {
if (i * (i + 1) == num) {
isPronic = true;
break;
}
}
if (isPronic)
System.out.println(num + " is a pronic number");
elseSystem.out.println(num + " is not a pronic number");
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

WRITE A PROGRAM TO INPUT A NUMBER AND CHECK WHETHER IT


IS A HARSHAD NUMBER OR NOT. [A NUMBER IS SAID TO BE
HARSHAD NUMBER, IF IT IS DIVISIBLE BY THE SUM OF ITS DIGITS.
THE PROGRAM DISPLAYS THE MESSAGE ACCORDINGLY.]
FOR EXAMPLE;
SAMPLE INPUT: 132
SUM OF DIGITS = 6 AND 132 IS DIVISIBLE BY 6.
OUTPUT: IT IS A HARSHAD NUMBER.
SAMPLE INPUT: 353
OUTPUT: IT IS NOT A HARSHAD NUMBER.

import java.util.*;
public class HarshadNumber
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = in.nextInt();
int x = num, rem = 0, sum = 0;
while(x > 0) {
rem = x % 10;
sum = sum + rem;
x = x / 10;
}
int r = num % sum;
if(r == 0)
System.out.println(num + " is a Harshad Number.");
elseSystem.out.println(num + " is not a Harshad Number.");
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

WRITE A PROGRAM TO INPUT A NUMBER AND CHECK WHETHER IT


IS A PRIME NUMBER OR NOT. IF IT IS NOT A PRIME NUMBER THEN
DISPLAY THE NEXT NUMBER THAT IS PRIME.
SAMPLE INPUT: 14
SAMPLE OUTPUT: 17

import java.util.Scanner;
public class PrimeCheck
{
public void primeCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number");
}
else {
for (int newNum = num + 1; newNum <= Integer.MAX_VALUE; newNum++)
{
isPrime = true;
for (int i = 2; i <= newNum / 2; i++) {
if (newNum % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("Next prime number = " + newNum);
break;
}
}
}
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

USING A SWITCH STATEMENT, WRITE A MENU DRIVEN PROGRAM


TO:
(A) GENERATE AND DISPLAY THE FIRST 10 TERMS OF THE
FIBONACCI SERIES
0, 1, 1, 2, 3, 5
THE FIRST TWO FIBONACCI NUMBERS ARE 0 AND 1, AND EACH
SUBSEQUENT NUMBER IS THE SUM OF THE PREVIOUS TWO.
(B) FIND THE SUM OF THE DIGITS OF AN INTEGER THAT IS INPUT BY
THE USER.
SAMPLE INPUT: 15390
SAMPLE OUTPUT: SUM OF THE DIGITS = 18
FOR AN INCORRECT CHOICE, AN APPROPRIATE ERROR MESSAGE
SHOULD BE DISPLAYED.

import java.util.Scanner;
public class FibonacciNDigitSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Fibonacci Series");
System.out.println("2. Sum of digits");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
/*
* i is starting from 3 below
* instead of 1 because we have
* already printed 2 terms of
* the series. The for loop will
* print the series from third
* term onwards.
*/
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;
CHAPTER

ITERATIVE
CONSTRUCTS

case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

USING A SWITCH STATEMENT, WRITE A MENU DRIVEN PROGRAM


TO:
(A) GENERATE AND DISPLAY THE FIRST 10 TERMS OF THE
FIBONACCI SERIES
0, 1, 1, 2, 3, 5
THE FIRST TWO FIBONACCI NUMBERS ARE 0 AND 1, AND EACH
SUBSEQUENT NUMBER IS THE SUM OF THE PREVIOUS TWO.
(B) FIND THE SUM OF THE DIGITS OF AN INTEGER THAT IS INPUT BY
THE USER.
SAMPLE INPUT: 15390
SAMPLE OUTPUT: SUM OF THE DIGITS = 18
FOR AN INCORRECT CHOICE, AN APPROPRIATE ERROR MESSAGE
SHOULD BE DISPLAYED.

import java.util.Scanner;
public class FibonacciNDigitSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Fibonacci Series");
System.out.println("2. Sum of digits");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
/*
* i is starting from 3 below
* instead of 1 because we have
* already printed 2 terms of
* the series. The for loop will
* print the series from third
* term onwards.
*/
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;
CHAPTER

ITERATIVE
CONSTRUCTS

case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
CHAPTER

ITERATIVE
CONSTRUCTS

USING SWITCH STATEMENT, WRITE A MENU DRIVEN PROGRAM FOR


THE FOLLOWING:
(A) TO FIND AND DISPLAY THE SUM OF THE SERIES GIVEN BELOW:
S = X^1- X^2 + X^3 - X^4+ X^5 - ....................... - X^20
(B) TO FIND AND DISPLAY THE SUM OF THE SERIES GIVEN BELOW:
S = 1/A^2 + 1/A^4+ 1/A^6+ 1/A^8+ ....................... TO N TERMS
FOR AN INCORRECT OPTION, AN APPROPRIATE ERROR MESSAGE
SHOULD BE DISPLAYED.

import java.util.Scanner;
public class SeriesSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Sum of x^1 - x^2 + .... - x^20");
System.out.println("2. Sum of 1/a^2 + 1/a^4 + .... to n terms");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
System.out.print("Enter the value of x: ");
int x = in.nextInt();
long sum1 = 0;
for (int i = 1; i <= 20; i++) {
int term = (int)Math.pow(x, i);
if (i % 2 == 0)
sum1 -= term;
else
sum1 += term;
}
System.out.println("Sum = " + sum1);
break;
CHAPTER

ITERATIVE
CONSTRUCTS

case 2:
System.out.print("Enter the number of terms: ");
int n = in.nextInt();
System.out.print("Enter the value of a: ");
int a = in.nextInt();
int c = 2;
double sum2 = 0;
for(int i = 1; i <= n; i++) {
sum2 += (1/Math.pow(a, c));
c += 2;
}
System.out.println("Sum = " + sum2);
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
CHAPTER

NESTED
LOOPS

WRITE A PROGRAM IN JAVA TO ENTER A NUMBER CONTAINING


THREE DIGITS OR MORE. ARRANGE THE DIGITS OF THE ENTERED
NUMBER IN ASCENDING ORDER AND DISPLAY THE RESULT.
SAMPLE INPUT: ENTER A NUMBER 4972
SAMPLE OUTPUT: 2, 4, 7, 9

import java.util.Scanner;
public class DigitSort
{
public void sortDigits() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number having 3 or more digits: ");
int OrgNum = in.nextInt();
for (int i = 0; i <= 9; i++) {
int num = OrgNum;
int c = 0;
while (num != 0) {
if (num % 10 == i)
c++;
num /= 10;
}
for (int j = 1; j <= c; j++) {
System.out.print(i + ", ");
}
}
System.out.println();
}
}
CHAPTER

NESTED
LOOPS

A NUMBER IS SAID TO BE MULTIPLE HARSHAD NUMBER, WHEN


DIVIDED BY THE SUM OF ITS DIGITS, PRODUCES ANOTHER
'HARSHAD NUMBER'. WRITE A PROGRAM TO INPUT A NUMBER AND
CHECK WHETHER IT IS A MULTIPLE HARSHAD NUMBER OR NOT.
(WHEN A NUMBER IS DIVISIBLE BY THE SUM OF ITS DIGIT, IT IS
CALLED 'HARSHAD NUMBER').
SAMPLE INPUT: 6804
HINT: 6804 ⇒ 6+8+0+4 = 18 ⇒ 6804/18 = 378
378 ⇒ 3+7+8= 18 ⇒ 378/18 = 21
21 ⇒ 2+1 = 3 ⇒ 21/3 = 7
SAMPLE OUTPUT: MULTIPLE HARSHAD NUMBER

import java.util.Scanner;
public class MultipleHarshad
{
public void checkMultipleHarshad() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int dividend = num;
int divisor;
int count = 0;
while (dividend > 1) {
divisor=0;
int t = dividend;
while (t > 0) {
int d = t % 10;
divisor += d;
t /= 10;
}
if (dividend % divisor == 0 && divisor != 1) {
dividend = dividend / divisor;
count++;
}
else {
break;
}
}
if (dividend == 1 && count > 1)
System.out.println(num + " is Multiple Harshad Number");
else
System.out.println(num + " is not Multiple Harshad Number");
}
}
CHAPTER

NESTED
LOOPS

A NUMBER IS SAID TO BE MULTIPLE HARSHAD NUMBER, WHEN


DIVIDED BY THE SUM OF ITS DIGITS, PRODUCES ANOTHER
'HARSHAD NUMBER'. WRITE A PROGRAM TO INPUT A NUMBER AND
CHECK WHETHER IT IS A MULTIPLE HARSHAD NUMBER OR NOT.
(WHEN A NUMBER IS DIVISIBLE BY THE SUM OF ITS DIGIT, IT IS
CALLED 'HARSHAD NUMBER').
SAMPLE INPUT: 6804
HINT: 6804 ⇒ 6+8+0+4 = 18 ⇒ 6804/18 = 378
378 ⇒ 3+7+8= 18 ⇒ 378/18 = 21
21 ⇒ 2+1 = 3 ⇒ 21/3 = 7
SAMPLE OUTPUT: MULTIPLE HARSHAD NUMBER

import java.util.Scanner;
public class MultipleHarshad
{
public void checkMultipleHarshad() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int dividend = num;
int divisor;
int count = 0;
while (dividend > 1) {
divisor=0;
int t = dividend;
while (t > 0) {
int d = t % 10;
divisor += d;
t /= 10;
}
if (dividend % divisor == 0 && divisor != 1) {
dividend = dividend / divisor;
count++;
}
else {
break;
}
}
if (dividend == 1 && count > 1)
System.out.println(num + " is Multiple Harshad Number");
else
System.out.println(num + " is not Multiple Harshad Number");
}
}
CHAPTER

NESTED
LOOPS

WRITE THE PROGRAMS TO DISPLAY THE FOLLOWING PATTERNS:


(A)
1
31
531
7531
97531

public class Pattern


{
public void displayPattern() {
for (int i = 1; i < 10; i = i + 2) {
for (int j = i; j > 0; j = j - 2) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
CHAPTER

NESTED
LOOPS

WRITE THE PROGRAMS TO DISPLAY THE FOLLOWING PATTERNS:


(B)
12345
6789
10 11 12
13 14
15

public class Pattern


{
public void displayPattern() {
int a = 1;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
}
}
CHAPTER

NESTED
LOOPS

WRITE THE PROGRAMS TO DISPLAY THE FOLLOWING PATTERNS:


(C)

15 14 13 12 11
10 9 8 7
654
32
1

public class Pattern


{
public void displayPattern() {
int a = 15;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(a-- + "\t");
}
System.out.println();
}
}
}
CHAPTER

NESTED
LOOPS

WRITE THE PROGRAMS TO DISPLAY THE FOLLOWING PATTERNS:

(D)
1
10
101
1010
10101

public class Pattern


{
public void displayPattern() {
int a = 1, b = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print(b + " ");
elseSystem.out.print(a + " ");
}
System.out.println();
}
}
}
CHAPTER

NESTED
LOOPS

WRITE THE PROGRAMS TO DISPLAY THE FOLLOWING PATTERNS:


(G)

*
* #
* #*
* #*#
* #*#*

public class Pattern


{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print("# ");
else
System.out.print("* ");
}
System.out.println();
}
}
}
CHAPTER

NESTED
LOOPS

USING THE SWITCH STATEMENT, WRITE A MENU DRIVEN PROGRAM


FOR THE FOLLOWING:
(A) TO PRINT THE FLOYD'S TRIANGLE:

1
23
456
7 8 9 10
11 12 13 14 15

(B) TO DISPLAY THE FOLLOWING PATTERN:


I
IC
ICS
ICSE
FOR AN INCORRECT OPTION, AN APPROPRIATE ERROR MESSAGE
SHOULD BE DISPLAYED.

import java.util.Scanner;
public class Pattern
{
public void choosePattern() {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Floyd's triangle");
System.out.println("Type 2 for an ICSE pattern");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
break;
CHAPTER

NESTED
LOOPS

case 2:
String s = "ICSE";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(s.charAt(j) + " ");
}
System.out.println();
}
break;
default:
System.out.println("Incorrect Choice");
}
}
}
CHAPTER

CHARACTER
MANIPULATION

WRITE A PROGRAM IN JAVA TO ACCEPT AN INTEGER NUMBER N


SUCH THAT 0<N<27. DISPLAY THE CORRESPONDING LETTER OF THE
ALPHABET (I.E. THE LETTER AT POSITION N).
[HINT: IF N =1 THEN DISPLAY A]

import java.util.Scanner;
public class Integer2Letter
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integer: ");
int n = in.nextInt();
if (n > 0 && n < 27) {
char ch = (char)(n + 64);
System.out.println("Corresponding letter = " + ch);
}
else {
System.out.println("Please enter a number in 1 to 26 range");
}
}
}
CHAPTER

CHARACTER
MANIPULATION

WRITE A PROGRAM TO INPUT A LETTER. FIND ITS ASCII CODE.


REVERSE THE ASCII CODE AND DISPLAY THE EQUIVALENT
CHARACTER.
SAMPLE INPUT: Y
SAMPLE OUTPUT: ASCII CODE = 89
REVERSE THE CODE = 98
EQUIVALENT CHARACTER: B

import java.util.Scanner;
public class ASCIIReverse
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter: ");
char l = in.next().charAt(0);
int a = (int)l;
System.out.println("ASCII Code = " + a);
int r = 0;
while (a > 0) {
int digit = a % 10;
r = r * 10 + digit;
a /= 10;
}
System.out.println("Reversed Code = " + r);
System.out.println("Equivalent character = " + (char)r);
}
}
CHAPTER

CHARACTER
MANIPULATION

WRITE A MENU DRIVEN PROGRAM TO DISPLAY


(I) FIRST FIVE UPPER CASE LETTERS
(II) LAST FIVE LOWER CASE LETTERS AS PER THE USER'S CHOICE.
ENTER '1' TO DISPLAY UPPER CASE LETTERS AND ENTER '2' TO
DISPLAY LOWER CASE LETTERS.

import java.util.Scanner;
public class MenuUpLowCase
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter '1' to display upper case letters");
System.out.println("Enter '2' to display lower case letters");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch (ch) {
case 1:
for (int i = 65; i <= 69; i++)
System.out.println((char)i);
break;
case 2:
for (int i = 118; i <= 122; i++)
System.out.println((char)i);
break;
default:
break;
}
}
}
CHAPTER

CHARACTER
MANIPULATION

WRITE A PROGRAM IN JAVA TO DISPLAY THE FOLLOWING


PATTERNS:
(I)
A
AB
ABC
ABCD
ABCDE

public class Pattern


{
public static void main(String args[]) {
for (int i = 65; i < 70; i++) {
for (int j = 65; j <= i; j++) {
if (i % 2 == 0)
System.out.print((char)(j+32));
elseSystem.out.print((char)j);
}
System.out.println();
}
}
}
CHAPTER

CHARACTER
MANIPULATION

WRITE A PROGRAM IN JAVA TO DISPLAY THE FOLLOWING


PATTERNS:
(II)
ZYXWU
ZYXW
ZYX
ZY
Z

public class Pattern


{
public static void main(String args[]) {
for (int i = 86; i <= 90; i++) {
for (int j = 90; j >= i; j--) {
System.out.print((char)j);
}
System.out.println();
}
}
}
CHAPTER

ARRAYS

WRITE A PROGRAM IN JAVA TO STORE 20 NUMBERS (EVEN AND


ODD NUMBERS) IN A SINGLE DIMENSIONAL ARRAY (SDA).
CALCULATE AND DISPLAY THE SUM OF ALL EVEN NUMBERS AND
ALL ODD NUMBERS SEPARATELY.

import java.util.Scanner;
public class SDAOddEvenSum
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[ ] = new int[20];
System.out.println("Enter 20 numbers");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int oddSum = 0, evenSum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
evenSum += arr[i];
elseoddSum += arr[i];
}
System.out.println("Sum of Odd numbers = " + oddSum);
System.out.println("Sum of Even numbers = " + evenSum);
}
}
CHAPTER

ARRAYS

WRITE A PROGRAM IN JAVA TO STORE 20 TEMPERATURES IN °F IN A


SINGLE DIMENSIONAL ARRAY (SDA) AND DISPLAY ALL THE
TEMPERATURES AFTER CONVERTING THEM INTO °C.
HINT: (C/5) = (F - 32) / 9

import java.util.Scanner;
public class SDAF2C
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double arr[] = new double[20];
System.out.println("Enter 20 temperatures in degree Fahrenheit");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextDouble();
}
System.out.println("Temperatures in degree Celsius");
for (int i = 0; i < arr.length; i++) {
double tc = 5 * ((arr[i] - 32) / 9);
System.out.println(tc);
}
}
}
CHAPTER

ARRAYS

WRITE A PROGRAM IN JAVA USING ARRAYS:


(A) TO STORE THE ROLL NO., NAME AND MARKS IN SIX SUBJECTS
FOR 100 STUDENTS.
(B) CALCULATE THE PERCENTAGE OF MARKS OBTAINED BY EACH
CANDIDATE. THE MAXIMUM MARKS IN EACH SUBJECT ARE 100.
(C) CALCULATE THE GRADE AS PER THE GIVEN CRITERIA:
PERCENTAGE MARKSGRADE
FROM 80 TO 100 A
FROM 60 TO 79. B
FROM 40 TO 59 C
LESS THAN 40. D

import java.util.Scanner;
public class SDAGrades
{
public static void main(String args[]) {
final int TOTAL_STUDENTS = 100;
Scanner in = new Scanner(System.in);
int rollNo[ ]= new int[TOTAL_STUDENTS];
String name[ ]= new String[TOTAL_STUDENTS];
int s1[ ]= new int[TOTAL_STUDENTS];
int s2[ ]= new int[TOTAL_STUDENTS];
int s3[ ]= new int[TOTAL_STUDENTS];
int s4[ ]= new int[TOTAL_STUDENTS];
int s5[ ]= new int[TOTAL_STUDENTS];
int s6[ ]= new int[TOTAL_STUDENTS];
double p[ ] = new double[TOTAL_STUDENTS];
char g[ ] = new char[TOTAL_STUDENTS];
for (int i = 0; i < TOTAL_STUDENTS; i++)
{
System.out.println("Enter student " + (i+1) + " details:");
System.out.print("Roll No: ");
rollNo[i] = in.nextInt();
in.nextLine();
System.out.print("Name: ");
name[i] = in.nextLine();
System.out.print("Subject 1 Marks: ");
s1[i] = in.nextInt();
System.out.print("Subject 2 Marks: ");
s2[i] = in.nextInt();
System.out.print("Subject 3 Marks: ");
s3[i] = in.nextInt();
System.out.print("Subject 4 Marks: ");
s4[i] = in.nextInt();
System.out.print("Subject 5 Marks: ");
s5[i] = in.nextInt();
System.out.print("Subject 6 Marks: ");
s6[i] = in.nextInt();
CHAPTER

ARRAYS

WRITE A PROGRAM IN JAVA USING ARRAYS:


(A) TO STORE THE ROLL NO., NAME AND MARKS IN SIX SUBJECTS
FOR 100 STUDENTS.
(B) CALCULATE THE PERCENTAGE OF MARKS OBTAINED BY EACH
CANDIDATE. THE MAXIMUM MARKS IN EACH SUBJECT ARE 100.
(C) CALCULATE THE GRADE AS PER THE GIVEN CRITERIA:
PERCENTAGE MARKSGRADE
FROM 80 TO 100 A
FROM 60 TO 79. B
FROM 40 TO 59 C
LESS THAN 40. D

import java.util.Scanner;
public class SDAGrades
{
public static void main(String args[]) {
final int TOTAL_STUDENTS = 100;
Scanner in = new Scanner(System.in);
int rollNo[ ]= new int[TOTAL_STUDENTS];
String name[ ]= new String[TOTAL_STUDENTS];
int s1[ ]= new int[TOTAL_STUDENTS];
int s2[ ]= new int[TOTAL_STUDENTS];
int s3[ ]= new int[TOTAL_STUDENTS];
int s4[ ]= new int[TOTAL_STUDENTS];
int s5[ ]= new int[TOTAL_STUDENTS];
int s6[ ]= new int[TOTAL_STUDENTS];
double p[ ] = new double[TOTAL_STUDENTS];
char g[ ] = new char[TOTAL_STUDENTS];
for (int i = 0; i < TOTAL_STUDENTS; i++)
{
System.out.println("Enter student " + (i+1) + " details:");
System.out.print("Roll No: ");
rollNo[i] = in.nextInt();
in.nextLine();
System.out.print("Name: ");
name[i] = in.nextLine();
System.out.print("Subject 1 Marks: ");
s1[i] = in.nextInt();
System.out.print("Subject 2 Marks: ");
s2[i] = in.nextInt();
System.out.print("Subject 3 Marks: ");
s3[i] = in.nextInt();
System.out.print("Subject 4 Marks: ");
s4[i] = in.nextInt();
System.out.print("Subject 5 Marks: ");
s5[i] = in.nextInt();
System.out.print("Subject 6 Marks: ");
s6[i] = in.nextInt();
CHAPTER

ARRAYS

p[i] = (((s1[i] + s2[i] + s3[i] + s4[i]


+ s5[i] + s6[i]) / 600.0) * 100);
if (p[i] < 40)
g[i] = 'D';
else if (p[i] < 60)
g[i] = 'C';
else if (p[i] < 80)
g[i] = 'B';
elseg[i] = 'A';
}
System.out.println();
for (int i = 0; i < TOTAL_STUDENTS; i++) {
System.out.println(rollNo[i] + "\t"
+ name[i] + "\t"
+ p[i] + "\t"
+ g[i]);
}
}
}
CHAPTER

ARRAYS

WRITE A PROGRAM TO ACCEPT A LIST OF 20 INTEGERS. SORT THE


FIRST 10 NUMBERS IN ASCENDING ORDER AND NEXT THE 10
NUMBERS IN DESCENDING ORDER BY USING 'BUBBLE SORT'
TECHNIQUE. FINALLY, PRINT THE COMPLETE LIST OF INTEGERS.

import java.util.Scanner;
public class SDABubbleSort
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[20];
System.out.println("Enter 20 numbers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
//Sort first half in ascending orderfor (int i = 0; i < arr.length / 2 - 1; i++) {
for (int j = 0; j < arr.length / 2 - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = t;
}
}
}
//Sort second half in descending orderfor (int i = 0; i < arr.length / 2 - 1;
i++) {
for (int j = arr.length / 2; j < arr.length - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int t = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = t;
}
}
}
//Print the final sorted arraySystem.out.println("\nSorted Array:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
CHAPTER

ARRAYS

WRITE A PROGRAM IN JAVA TO ACCEPT 20 NUMBERS IN A SINGLE


DIMENSIONAL ARRAY ARR[20]. TRANSFER AND STORE ALL THE
EVEN NUMBERS IN AN ARRAY EVEN[ ] AND ALL THE ODD NUMBERS
IN ANOTHER ARRAY ODD[ ]. FINALLY, PRINT THE ELEMENTS OF
BOTH THE ARRAYS.

import java.util.Scanner;
public class SDAEvenOdd
{
public static void main(String args[]) {
final int NUM_COUNT = 20;
Scanner in = new Scanner(System.in);
int i = 0;
int arr[] = new int[NUM_COUNT];
int even[] = new int[NUM_COUNT];
int odd[] = new int[NUM_COUNT];
System.out.println("Enter 20 numbers:");
for (i = 0; i < NUM_COUNT; i++) {
arr[i] = in.nextInt();
}
int eIdx = 0, oIdx = 0;
for (i = 0; i < NUM_COUNT; i++) {
if (arr[i] % 2 == 0)
even[eIdx++] = arr[i];
elseodd[oIdx++] = arr[i];
}
System.out.println("Even Numbers:");
for (i = 0; i < eIdx; i++) {
System.out.print(even[i] + " ");
}
System.out.println("\nOdd Numbers:");
for (i = 0; i < oIdx; i++) {
System.out.print(odd[i] + " ");
}
}
}
CHAPTER

ARRAYS

A DOUBLE DIMENSIONAL ARRAY IS DEFINED AS N[4][4] TO STORE


NUMBERS. WRITE A PROGRAM TO FIND THE SUM OF ALL EVEN
NUMBERS AND PRODUCT OF ALL ODD NUMBERS OF THE ELEMENTS
STORED IN DOUBLE DIMENSIONAL ARRAY (DDA).

import java.util.Scanner;
public class DDAEvenOdd
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N[][] = new int[4][4];
long evenSum = 0, oddProd = 1;
System.out.println("Enter the elements of 4x4 DDA: ");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
N[i][j] = in.nextInt();
if (N[i][j] % 2 == 0)
evenSum += N[i][j];
else
OddProd *= N[i][j];
}
}
System.out.println("Sum of all even numbers = " + evenSum);
System.out.println("Product of all odd numbers = " + oddProd);
}
}
CHAPTER

STRINGS

WRITE A PROGRAM TO INPUT A SENTENCE. FIND AND DISPLAY THE


FOLLOWING:
(I) NUMBER OF WORDS PRESENT IN THE SENTENCE
(II) NUMBER OF LETTERS PRESENT IN THE SENTENCE
ASSUME THAT THE SENTENCE HAS NEITHER INCLUDE ANY DIGIT
NOR A SPECIAL CHARACTER.

import java.util.Scanner;
public class WordsNLetters
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
int wCount = 0, lCount = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ')
wCount++;
elselCount++;
}
System.out.println("No. of words = " + wCount);
System.out.println("No. of letters = " + lCount);
}
}
CHAPTER

STRINGS

WRITE A PROGRAM IN JAVA TO ACCEPT A WORD/A STRING AND


DISPLAY THE NEW STRING AFTER REMOVING ALL THE VOWELS
PRESENT IN IT.
SAMPLE INPUT: COMPUTER APPLICATIONS
SAMPLE OUTPUT: CMPTR PPLCTNS

import java.util.Scanner;
public class VowelRemoval
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
int len = str.length();
String newStr = "";
for (int i = 0; i < len; i++) {
char ch = Character.toUpperCase(str.charAt(i));
if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
continue;
}
newStr = newStr + ch;
}
System.out.println("String with vowels removed");
System.out.println(newStr);
}
}
CHAPTER

STRINGS

WRITE A PROGRAM IN JAVA TO ACCEPT A NAME(CONTAINING


THREE WORDS) AND DISPLAY ONLY THE INITIALS (I.E., FIRST LETTER
OF EACH WORD).
SAMPLE INPUT: LAL KRISHNA ADVANI
SAMPLE OUTPUT: L K A

import java.util.Scanner;
public class NameInitials
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3 or more words:");
String str = in.nextLine();
int len = str.length();
System.out.print(str.charAt(0) + " ");
for (int i = 1; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
char ch2 = str.charAt(i + 1);
System.out.print(ch2 + " ");
}
}
}
}
CHAPTER

STRINGS

WRITE A PROGRAM IN JAVA TO ACCEPT A NAME CONTAINING


THREE WORDS AND DISPLAY THE SURNAME FIRST, FOLLOWED BY
THE FIRST AND MIDDLE NAMES.
SAMPLE INPUT: MOHANDAS KARAMCHAND GANDHI
SAMPLE OUTPUT: GANDHI MOHANDAS KARAMCHAND

import java.util.Scanner;
public class SurnameFirst
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a name of 3 words:");
String name = in.nextLine();
Int lastSpaceIdx = name.lastIndexOf(' ');
String surname = name.substring(lastSpaceIdx + 1);
String initialName = name.substring(0, lastSpaceIdx);
System.out.println(surname + " " + initialName);
}
}
CHAPTER

STRINGS

WRITE A PROGRAM IN JAVA TO ENTER A STRING/SENTENCE AND


DISPLAY THE LONGEST WORD AND THE LENGTH OF THE LONGEST
WORD PRESENT IN THE STRING.
SAMPLE INPUT: “TATA FOOTBALL ACADEMY WILL PLAY AGAINST
MOHAN BAGAN”
SAMPLE OUTPUT: THE LONGEST WORD: FOOTBALL: THE LENGTH OF
THE WORD: 8

import java.util.Scanner;
public class LongestWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
str += " "; //Add space at end of stringString word = "", lWord = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
if (word.length() > lWord.length())
lWord = word;
word = "";
}
else {
word += ch;
}
}
System.out.println("The longest word: " + lWord +
": The length of the word: " + lWord.length());
}
}
CHAPTER

STRINGS

WRITE A PROGRAM IN JAVA TO ACCEPT A WORD AND DISPLAY THE


ASCII CODE OF EACH CHARACTER OF THE WORD.
SAMPLE INPUT: BLUEJ
SAMPLE OUTPUT:
ASCII OF B = 66
ASCII OF L = 76
ASCII OF U = 85
ASCII OF E = 69
ASCII OF J = 74
import java.util.Scanner;
public class LongestWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word or sentence:");
String str = in.nextLine();
str += " "; //Add space at end of stringString word = "", lWord = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ') {
if (word.length() > lWord.length())
lWord = word;
word = "";
}
else {
word += ch;
}
}
System.out.println("The longest word: " + lWord +
": The length of the word: " + lWord.length());
}
}
CHAPTER

STRINGS

WRITE A PROGRAM IN JAVA TO ACCEPT A STRING IN UPPER CASE


AND REPLACE ALL THE VOWELS PRESENT IN THE STRING WITH
ASTERISK (*) SIGN.
SAMPLE INPUT: "TATA STEEL IS IN JAMSHEDPUR"
SAMPLE OUTPUT: T*T* ST**L *S *N J*MSH*DP*R

import java.util.Scanner;
public class VowelReplace
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string in uppercase:");
String str = in.nextLine();
String newStr = "";
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == 'A' ||
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
newStr = newStr + '*';
}
else {
newStr = newStr + ch;
}
}
System.out.println(newStr);
}
}
CHAPTER

STRINGS

WRITE A PROGRAM IN JAVA TO ENTER A SENTENCE. FRAME A


WORD BY JOINING ALL THE FIRST CHARACTERS OF EACH WORD OF
THE SENTENCE. DISPLAY THE WORD.
SAMPLE INPUT: VITAL INFORMATION RESOURCE UNDER SEIZE
SAMPLE OUTPUT: VIRUS

import java.util.Scanner;
public class FrameWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
String word = "" + str.charAt(0);
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == ' ')
word += str.charAt(i + 1);
}
System.out.println(word);
}
}
SAVIOUR OF
COMPUTERS

LAST 10 YEARS
SOLUTIONS
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

SECTION A

Question 1

(a) What is meant by precedence of operators?

Answer

Precedence of operators refers to the order in which the operators are applied to the operands in an
expression.

(b) What is a literal?

Answer

Literals are data items that are fixed data values. Java provides different types of literals like:

Integer Literals
Floating-Point Literals
Boolean Literals
Character Literals
String Literals
null Literal

(c) State the Java concept that is implemented through:

a superclass and a subclass.


the act of representing essential features without including background details.

Answer

Inheritance
Abstraction

(d) Give a difference between a constructor and a method.

Answer

Constructor has the same name as class name whereas function should have a different name than
class name.

(e) What are the types of casting shown by the following examples?

double x = 15.2;
int y = (int) x;

int x = 12;
long y = x;

Answer

Explicit Type Casting


Implicit Type Casting
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

SECTION A

Question 2

(a) Name any two wrapper classes.

Answer

Two wrapper classes are:


1. Integer
2. Character

(b) What is the difference between a break statement and a continue statement when they
occur in a loop?

Answer

When the break statement gets executed, it terminates its loop completely and control reaches to
the statement immediately following the loop. The continue statement terminates only the current
iteration of the loop by skipping rest of the statements in the body of the loop.

(c) Write statements to show how finding the length of a character array char[] differs from
finding the length of a String object str.

Answer

Java code snippet to find length of character array:

char ch[] = {'x', 'y', 'z'};


int len = ch.length

Java code snippet to find length of String object str:

String str = "Test";


int len = str.length();

(d) Name the Java keyword that:


1. indicates that a method has no return type.
2. stores the address of the currently-calling object.

Answer

1. void
2. this

(e) What is an exception?

Answer

An exception is an abnormal condition that arises in a code sequence at run time. Exceptions indicate
to a calling method that an abnormal condition has occurred.
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

Question 3

(a) Write a Java statement to create an object mp4 of class Digital.

Answer

Digital MP4 = new Digital();

(b) State the values stored in the variables str1 and str2:

String s1 = "good";
String s2 = "world matters";
String str1 = s2.substring(5).replace('t', 'n');
String str2 = s1.concat(str1);

Answer

Value stored in str1 is " manners" and str2 is "good manners". (Note that str1 begins with a
space.)

Explanation

s2.substring(5) gives a substring from index 5 till the end of the string which is " matters".
The replace method replaces all 't' in " matters" with 'n' giving " manners". s1.concat(str1)
joins together "good" and " manners" so "good manners" is stored in str2.

(c) What does a class encapsulate?

Answer

(d) Rewrite the following program segment using the if..else statement:

comm = (sale > 15000)? sale * 5 / 100 : 0;

Answer

if(sale > 15000)


comm = sale * 5 / 100;
elsecomm = 0;

(e) How many times will the following loop execute? What value will be returned?
int x = 2, y = 50;
do{
++x;
y -= x++;
}while(x <= 10);
return y;

Answer

The loop will run 5 times and the value returned is 15.
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

(f) What is the data type that the following library functions return?

1. isWhitespace(char ch)
2. Math.random()

Answer

1. boolean
2. double

(g) Write a Java expression for:

ut + 1/2 ft^2

Answer

u * t + 1 / 2.0 * f * t * t

(h) If int n[] = {1, 2, 3, 5, 7, 9, 13, 16}, what are the values of x and y?
x = Math.pow(n[4], n[2]);
y = Math.sqrt(n[5] + n[7]);

Answer

x = Math.pow(n[4], n[2]);
⇒ x = Math.pow(7, 3);
⇒ x = 343.0;
y = Math.sqrt(n[5] + n[7]);
⇒ y = Math.sqrt(9 + 16);
⇒ y = Math.sqrt(25);
⇒ y = 5.0;

(i) What is the final value of ctr when the iteration process given below, executes?
int ctr = 0;
for(int i = 1; i <= 5; i++)
for(int j = 1; j <= 5; j += 2)
++ctr;

Answer

The final value of ctr is 15.

The outer loop executes 5 times. For each iteration of outer loop, the inner loop executes 3
times. So the statement ++ctr; is executed a total of 5 x 3 = 15 times.

(j) Name the method of Scanner class that:

1. is used to input an integer data from the standard input stream.


2. is used to input a String data from the standard input stream.

Answer

1. nextInt()
2. nextLine()
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

SECTION B

Question 4
Define a class named FruitJuice with the following description:

Data Members. Purpose

int product_code. stores the product code number

String flavour. stores the flavour of the juice (e.g., orange, apple, etc.)

String pack_type. stores the type of packaging (e.g., tera-pack, PET bottle, etc.)

int pack_size. stores package size (e.g., 200 mL, 400 mL, etc.)

int product_price. stores the price of the product

Member Methods Purpose


FruitJuice(). constructor to initialize integer data members to 0 and string data members to ""

void input(). to input and store the product code, flavour, pack type, pack size and product price

void discount(). to reduce the product price by 10

void display(). to display the product code, flavour, pack type, pack size and product price
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class FruitJuice


{
private int product_code;
private String flavour;
private String pack_type;
private int pack_size;
private int product_price;

public FruitJuice() {
product_code = 0;
flavour = "";
pack_type = "";
pack_size = 0;
product_price = 0;
}

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter Flavour: ");
flavour = in.nextLine();
System.out.print("Enter Pack Type: ");
pack_type = in.nextLine();
System.out.print("Enter Product Code: ");
product_code = in.nextInt();
System.out.print("Enter Pack Size: ");
pack_size = in.nextInt();
System.out.print("Enter Product Price: ");
product_price = in.nextInt();
}

public void discount() {


product_price -= 10;
}

public void display() {


System.out.println("Product Code: " + product_code);
System.out.println("Flavour: " + flavour);
System.out.println("Pack Type: " + pack_type);
System.out.println("Pack Size: " + pack_size);
System.out.println("Product Price: " + product_price);
}

public static void main(String args[]) {


FruitJuice obj = new FruitJuice();
obj.input();
obj.discount();
obj.display();
}
}
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

Question 5
The International Standard Book Number (ISBN) is a unique numeric book identifier
which is printed on every book. The ISBN is based upon a 10-digit code.

The ISBN is legal if:


1 × digit1 + 2 × digit2 + 3 × digit3 + 4 × digit4 + 5 × digit5 + 6 × digit6 + 7 × digit7 + 8 × digit8
+ 9 × digit9 + 10 × digit10 is divisible by 11.

Example:
For an ISBN 1401601499
Sum = 1 × 1 + 2 × 4 + 3 × 0 + 4 × 1 + 5 × 6 + 6 × 0 + 7 × 1 + 8 × 4 + 9 × 9 + 10 × 9 = 253 which is
divisible by 11.

Write a program to:


1. Input the ISBN code as a 10-digit integer.
2. If the ISBN is not a 10-digit integer, output the message "Illegal ISBN" and terminate
the program.
3. If the number is divisible by 11, output the message "Legal ISBN". If the sum is not
divisible by 11, output the message "Illegal ISBN".

Answer

import java.util.Scanner;

public class ISBNCheck


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the ISBN: ");
long isbn = in.nextLong();

int sum = 0, count = 0, m = 10;


while (isbn != 0) {
int d = (int)(isbn % 10);
count++;
sum += d * m;
m--;
isbn /= 10;
}

if (count != 10) {
System.out.println("Illegal ISBN");
}
else if (sum % 11 == 0) {
System.out.println("Legal ISBN");
}
else {
System.out.println("Illegal ISBN");
}
}
}
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

Question 6

Write a program that encodes a word into Piglatin. To translate word into Piglatin
word, convert the word into uppercase and then place the first vowel of the
original word as the start of the new word along with the remaining alphabets.
The alphabets present before the vowel being shifted towards the end followed by
"AY".

Sample Input 1: London


Output: ONDONLAY

Sample Input 2: Olympics


Output: OLYMPICSA

Answer

import java.util.Scanner;

public class PigLatin


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

Scanner in = new Scanner(System.in);


System.out.print("Enter word: ");
String word = in.next();
int len = word.length();

word=word.toUpperCase();
String piglatin="";
int flag=0;

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


{
char x = word.charAt(i);
if(x=='A' || x=='E' || x=='I' || x=='O' || x=='U')
{
piglatin=word.substring(i) + word.substring(0,i) + "AY";
flag=1;
break;
}
}

if(flag == 0)
{
piglatin = word + "AY";
}
System.out.println(word + " in Piglatin format is " + piglatin);
}
}
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

Question 7
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 BubbleSortDsc


{
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 Sortfor (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] + " ");
}
}
}
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

Question 8
Design a class to overload a function series( ) as follows:
1. double series(double n) with one double argument and returns
the sum of the series sum = (1/1) + (1/2) + (1/3) + .......... + (1/n)
2. double series(double a, double n) with two double arguments
and returns the sum of the series. sum = (1/a^2) + (4/a^3)+
(7/a^8)+ (10/a^11) + .......... to n terms

Answer

public class Series


{
double series(double n) {
double sum = 0;
for (int i = 1; i <= n; i++) {
double term = 1.0 / i;
sum += term;
}
return sum;
}

double series(double a, double n) {


double sum = 0;
int x = 1;
for (int i = 1; i <= n; i++) {
int e = x + 1;
double term = x / Math.pow(a, e);
sum += term;
x += 3;
}
return sum;
}

public static void main(String args[]) {


KboatSeries obj = new KboatSeries();
System.out.println("First series sum = " + obj.series(5));
System.out.println("Second series sum = " + obj.series(3, 8));
}
}
SAVIOUR OF COMPUTERS

2013 COMPUTER
APPLICATION PAPER

Question 9
Using the switch statement, write a menu driven program:
1. To check and display whether a number input by the user is a composite
number or not. A number is said to be composite, if it has one or more than one
factors excluding 1 and the number itself. Example: 4, 6, 8, 9...
2. To find the smallest digit of an integer that is input: Sample input: 6524 Sample
output: Smallest digit is 2
For an incorrect choice, an appropriate error message should be displayed.

Answer
import java.util.Scanner;

public class Number


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Composite Number");
System.out.println("Type 2 for Smallest Digit");
System.out.print("Enter your choice: ");
int ch = in.nextInt();

switch (ch) {
case 1:
System.out.print("Enter Number: ");
int n = in.nextInt();
int c = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0)
c++;
}

if (c > 2)
System.out.println("Composite Number");
elseSystem.out.println("Not a Composite Number");
break;

case 2:
System.out.print("Enter Number: ");
int num = in.nextInt();
int s = 10;
while (num != 0) {
int d = num % 10;
if (d < s)
s = d;
num /= 10;
}
System.out.println("Smallest digit is " + s);
break;

default:
System.out.println("Wrong choice");
}
}
}
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

SECTION A

Question 1

(a) Which of the following are valid comments ?


1. /*comment*/
2. /*comment
3. //comment
4. */comment*/

Answer

The valid comments are:


Option 1 — /*comment*/
Option 3 — //comment

(b) What is meant by a package ? Name any two java Application Programming
Interface packages.

Answer

A package is a named collection of Java classes that are grouped on the basis of their
functionality. Two java Application Programming Interface packages are:
1. java.util
2. java.io

(c) Name the primitive data type in Java that is:


1. a 64-bit integer and is used when you need a range of values wider than those
provided by int.
2. a single 16-bit Unicode character whose default value is '\u0000'.

Answer

1. long
2. char

(d) State one difference between the floating point literals float and double.

Answer

Float literals double literals


float literals have a double literals have a
size of 32 bits so they size of 64 bits so they
can store a fractional can store a fractional
number with around number with 15-16
6-7 total digits of total digits of
precision. precision.
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

(e) Find the errors in the given program segment and re-write the statements correctly to assign
values to an integer array.
int a = new int (5);
for (int i=0; i<=5; i++) a[i]=i;

Answer

Corrected Code:
int a[] = new int[5];
for (int i = 0; i < 5; i++)
a[i] = i;

Question 2

(a) Operators with higher precedence are evaluated before operators with relatively lower
precedence. Arrange the operators given below in order of higher precedence to lower
precedence:
1. &&
2. %
3. >=
4. ++

Answer

++
%
>=
&&

(b) Identify the statements listed below as assignment, increment, method invocation or object
creation statements.
1. System.out.println("Java");
2. costPrice = 457.50;
3. Car hybrid = new Car();
4. petrolPrice++;

Answer

1. Method Invocation
2. Assignment
3. Object Creation
4. Increment

(c) Give two differences between the switch statement and the if-else statement

switch if-else

switch can only test if if-else can test for any


the expression is boolean expression like
equal to any of its less than, greater than,
case constants equal to, not equal to,
It is a multiple etc.
branching flow of It is a bi-directional flow
control statement of control statement
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

(d) What is an infinite loop? Write an infinite loop statement.

Answer

A loop which continues iterating indefinitely and never stops is termed as infinite
loop. Below is an example of infinite loop:
for (;;)
System.out.println("Infinite Loop");

(e) What is constructor? When is it invoked?

Answer

A constructor is a member method that is written with the same name as the class
name and is used to initialize the data members or instance variables. A constructor
does not have a return type. It is invoked at the time of creating any object of the
class.

Question 3

(a) List the variables from those given below that are composite data types:
1. static int x;
2. arr[i]=10;
3. obj.display();
4. boolean b;
5. private char chr;
6. String str;

Answer

The composite data types are:


arr[i]=10;
obj.display();
String str;

(b) State the output of the following program segment:


String str1 = "great"; String str2 = "minds";
System.out.println(str1.substring(0,2).concat(str2.substring(1)));
System.out.println(("WH" + (str1.substring(2).toUpperCase())));

Answer
The output of the above code is:
grinds
WHEAT

Explanation:
1. str1.substring(0,2) returns "gr". str2.substring(1) returns "inds". Due to concat both
are joined together to give the output as "grinds".
2. str1.substring(2) returns "eat". It is converted to uppercase and joined to "WH" to
give the output as "WHEAT".
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

(c) What are the final values stored in variable x and y below?

double a = -6.35;
double b = 14.74;
double x = Math.abs(Math.ceil(a));
double y = Math.rint(Math.max(a,b));

Answer

The final value stored in variable x is 6.0 and y is 15.0.

Explanation:
1. Math.ceil(a) gives -6.0 and Math.abs(-6.0) is 6.0.
2. Math.max(a,b) gives 14.74 and Math.rint(14.74) gives 15.0.

(d) Rewrite the following program segment using if-else statements instead of the
ternary operator:
String grade = (marks>=90)?"A": (marks>=80)? "B": "C";

Answer

String grade;
if (marks >= 90)
grade = "A";
else if (marks >= 80)
grade = "B";
elsegrade = "C";

(e) Give the output of the following method:


public static void main (String [] args){
int a = 5;
a++;
System.out.println(a);
a -= (a--) - (--a);
System.out.println(a);}
Answer
Output
6
4
Explanation
1. a++ increments value of a by 1 so a becomes 6.
2. a -= (a--) - (--a)
⇒ a = a - ((a--) - (--a))
⇒ a = 6 - (6 - 4)
⇒a=6-2
⇒a=4
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

(f) What is the data type returned by the library functions :


1. compareTo()
2. equals()

Answer

1. int
2. boolean

(g) State the value of characteristic and mantissa when the following code
is executed:

String s = "4.3756";
int n = s.indexOf('.');
int characteristic=Integer.parseInt(s.substring(0,n));
int mantissa=Integer.valueOf(s.substring(n+1));

Answer

The value of characteristic is 4 and mantissa is 3756.


Index of . in String s is 1 so variable n is initialized to 1. s.substring(0,n) gives 4.
Integer.parseInt() converts string "4" into integer 4 and this 4 is assigned to
the variable characteristic.
s.substring(n+1) gives 3756 i.e. the string starting at index 2 till the end of s.
Integer.valueOf() converts string "3756" into integer 3756 and this value is
assigned to the variable mantissa.

(h) Study the method and answer the given questions.


public void sampleMethod()

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


{ for (int j = 0; j<2; j++)
{int number = (int)(Math.random() * 10);
System.out.println(number); }}

1. How many times does the loop execute?


2. What is the range of possible values stored in the variable number?

Answer

1. The loops execute 6 times.


2. The range is from 0 to 9.
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

(i) Consider the following class:

public class myClass {


public static int x=3, y=4;
public int a=2, b=3;}

1. Name the variables for which each object of the class will have its
own distinct copy.
2. Name the variables that are common to all objects of the class.

Answer

1. a, b
2. x, y

(j) What will be the output when the following code segments are
executed?

(i)
String s = "1001";
int x = Integer.valueOf(s);
double y = Double.valueOf(s);
System.out.println("x="+x);
System.out.println("y="+y);

(ii)
System.out.println("The king said \"Begin at the beginning!\" t

Answer

(i) The output of the code is:


x=1001
y=1001.0
(ii) The output of the code is:
The king said "Begin at the beginning!" to me.
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

SECTION B
Question 4
Define a class named movieMagic with the following description:

Data Members. Purpose


int year To store the year of release of a movie
String title To store the title of the movie
float rating To store the popularity rating of the movie
(. minimum rating=0.0 and maximum rating=5.0

Member Methods. Purpose


movieMagic(). Default constructor to initialize numeric data members to 0 and String
data member to "".

void accept(). To input and store year, title and rating

void display(). To display the title of the movie and a message based on the rating as
per the table given below

Ratings table

Rating. Message to be displayed

0.0 to 2.0 Flop


2.1 to 3.4. Semi-Hit
3.5 to 4.4. Hit
4.5 to 5.0. Super-Hit

Write a main method to create an object of the class and call the above member methods.

Answer

import java.util.Scanner;

public class movieMagic


{
private int year;
private String title;
private float rating;

public movieMagic() {
year = 0;
title = "";
rating = 0.0f;
}
public void accept() {
Scanner in = new Scanner(System.in);
System.out.print("Enter Title of Movie: ");
title = in.nextLine();
System.out.print("Enter Year of Movie: ");
year = in.nextInt();
System.out.print("Enter Rating of Movie: ");
rating = in.nextFloat();
}
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

public void display() {


String message = "Invalid Rating";
if (rating <= 2.0f)
message = "Flop";
else if (rating <= 3.4f)
message = "Semi-Hit";
else if (rating <= 4.4f)
message = "Hit";
else if (rating <= 5.0f)
message = "Super-Hit";

System.out.println(title);
System.out.println(message);
}

public static void main(String args[]) {


movieMagic obj = new movieMagic();
obj.accept();
obj.display();
}
}

Question 5

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.

Example: Consider the number 59.


Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59

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".
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class SpecialNumber


{
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");
elseSystem.out.println("Not a special 2-digit number");

}
}

Question 6

Write a program to assign a full path and file name as given below. Using
library functions, extract and output the file path, file name and file
extension separately as shown.

Input
C:\Users\admin\Pictures\flower.jpg

Output
Path: C:\Users\admin\Pictures\
File name: flower
Extension: jpg
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class FilepathSplit


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

Scanner in = new Scanner(System.in);


System.out.print("Enter full path: ");
String filepath = in.next();

char pathSep = '\\';


char dotSep = '.';

int pathSepIdx = filepath.lastIndexOf(pathSep);


System.out.println("Path:\t\t" + filepath.substring(0, pathSepIdx));

int dotIdx = filepath.lastIndexOf(dotSep);


System.out.println("File Name:\t" + filepath.substring(pathSepIdx + 1,
dotIdx));

System.out.println("Extension:\t" + filepath.substring(dotIdx + 1));


}
}

Question 7
Design a class to overload a function area( ) as follows:
1. double area (double a, double b, double c) with three double
arguments, returns the area of a scalene triangle using the
formula: area = √(s(s-a)(s-b)(s-c)) where s = (a+b+c) / 2
2. double area (int a, int b, int height) with three integer arguments,
returns the area of a trapezium using the formula: area =
(1/2)height(a + b)
3. double area (double diagonal1, double diagonal2) with two double
arguments, returns the area of a rhombus using the formula: area
= 1/2(diagonal1 x diagonal2)
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class KboatOverload


{
double area(double a, double b, double c) {
double s = (a + b + c) / 2;
double x = s * (s-a) * (s-b) * (s-c);
double result = Math.sqrt(x);
return result;
}

double area (int a, int b, int height) {


double result = (1.0 / 2.0) * height * (a + b);
return result;
}

double area (double diagonal1, double diagonal2) {


double result = 1.0 / 2.0 * diagonal1 * diagonal2;
return result;
}
}

Question 8
Using the switch statement, write a menu driven program to
calculate the maturity amount of a Bank Deposit.
The user is given the following options:
1. Term Deposit
2. Recurring Deposit

For option 1, accept principal (P), rate of interest(r) and time period in
years(n). Calculate and output the maturity amount(A) receivable
using the formula:
A = P[1 + r / 100]^n

For option 2, accept Monthly Installment (P), rate of interest (r) and
time period in months (n). Calculate and output the maturity amount
(A) receivable using the formula:
A = P x n + P x (n(n+1) / 2) x r / 100 x 1 / 12

For an incorrect option, an appropriate error message should be


displayed.
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class BankDeposit


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Term Deposit");
System.out.println("Type 2 for Recurring Deposit");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
double p = 0.0, r = 0.0, a = 0.0;
int n = 0;

switch (ch) {
case 1:
System.out.print("Enter Principal: ");
p = in.nextDouble();
System.out.print("Enter Interest Rate: ");
r = in.nextDouble();
System.out.print("Enter time in years: ");
n = in.nextInt();
a = p * Math.pow(1 + r / 100, n);
System.out.println("Maturity amount = " + a);
break;

case 2:
System.out.print("Enter Monthly Installment: ");
p = in.nextDouble();
System.out.print("Enter Interest Rate: ");
r = in.nextDouble();
System.out.print("Enter time in months: ");
n = in.nextInt();
a = p * n + p * ((n * (n + 1)) / 2) * (r / 100) * (1 / 12.0);
System.out.println("Maturity amount = " + a);
break;

default:
System.out.println("Invalid choice");
}
}
}
SAVIOUR OF COMPUTERS

2014 COMPUTER
APPLICATION PAPER

Question 9
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]. 1982
n[1]. 1987
n[2]. 1993
n[3]. 1996
n[4]. 1999
n[5]. 2003
n[6]. 2006
n[7]. 2007
n[8]. 2009
n[9]. 2010

Answer

import java.util.Scanner;

public class GraduationYear


{
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");
elseSystem.out.println("Record exists");
}
}
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

SECTION A

(a) What are the default values of the primitive data type int and
float?

Answer
Default value of int is 0 and float is 0.0f.

(b) Name any two OOP’s principles.

Answer

1. Encapsulation
2. Inheritance

(c) What are identifiers ?

Answer

Identifiers are symbolic names given to different parts of a


program such as variables, methods, classes, objects, etc.

(d) Identify the literals listed below:


(i) 0.5 (ii) 'A' (iii) false (iv) "a"

Answer
1. Real Literal
2. Character Literal
3. Boolean Literal
4. String Literal

(e) Name the wrapper classes of char type and boolean type.

Answer

Wrapper class of char type is Character and boolean type is


Boolean.
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

(a) Evaluate the value of n if value of p = 5, q = 19


int n = (q – p) > (p – q) ? (q – p) : (p – q);

Answer
int n = (q – p) > (p – q) ? (q – p) : (p – q)
⇒ int n = (19 - 5) > (5 - 19) ? (19 - 5) : (5 - 19)
⇒ int n = 14 > -14 ? 14 : -14
⇒ int n = 14 [∵ 14 > -14 is true so ? : returns 14]
Final value of n is 14

(b) Arrange the following primitive data types in an ascending order of


their size:
(i) char (ii) byte (iii) double (iv) int

Answer
byte, char, int, double

(c) What is the value stored in variable res given below:


double res = Math.pow ("345".indexOf('5'), 3);

Answer
Value of res is 8.0
Index of '5' in "345" is 2. Math.pow(2, 3) means 23 which is equal to 8

(d) Name the two types of constructors

Answer
Parameterized constructors and Non-Parameterized constructors.

(e) What are the values of a and b after the following function is
executed, if the values passed are 30 and 50:
void paws(int a, int b)
{
a=a+b;
b=a–b;
a=a–b;
System.out.println(a+ "," +b);
}
Answer

Value of a is 50 and b is 30.


Output of the code is:
50,30
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

(e) (i) Name the mathematical function which is used to find sine of an angle
given in radians.
(ii) Name a string function which removes the blank spaces provided in the
prefix and suffix of a string.
Answer
(i) Math.sin() (ii) trim()

(f) (i) What will this code print ?


int arr[]=new int[5];
System.out.println(arr);
1. 0
2. value stored in arr[0]
3. 0000
4. garbage value
Answer

This code will print garbage value

(ii) Name the keyword which is used- to resolve the conflict between
method parameter and instance variables/fields.
Answer
this keyword

(g) State the package that contains the class:


1. BufferedReader
2. Scanner
Answer

1. java.io
2. java.util

(h) Write the output of the following program code:


char ch ;
int x=97;
do
{
ch=(char)x;
System.out.print(ch + " " );
if(x%10 == 0)
break;
++x;
} while(x<=100);
Answer
The output of the above code is:
abcd
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

(a) State the data type and value of y after the following is executed:
char x='7';
y=Character.isLetter(x);
Answer
Data type of y is boolean and value is false. Character.isLetter() method
checks if its argument is a letter or not and as 7 is a number not a letter
hence it returns false.

(b) What is the function of catch block in exception handling ? Where


does it appear in a program ?
Answer
Catch block contains statements that we want to execute in case an
exception is thrown in the try block. Catch block appears immediately
after the try block in a program.

(c) State the output when the following program segment is executed:
String a ="Smartphone", b="Graphic Art";
String h=a.substring(2, 5);
String k=b.substring(8).toUpperCase();
System.out.println(h);
System.out.println(k.equalsIgnoreCase(h));
Answer
The output of the above code is:
art
true

Explanation

a.substring(2, 5) extracts the characters of string a starting from index 2 till


index 4. So h contains the string "art". b.substring(8) extracts characters of
b from index 8 till the end so it returns "Art". toUpperCase() converts it into
uppercase. Thus string "ART" gets assigned to k. Values of h and k are "art"
and "ART", respectively. As both h and k differ in case only hence
equalsIgnoreCase returns true.

(d) The access specifier that gives the most accessibility is ________ and
the least accessibility is ________.
Answer

The access specifier that gives the most accessibility is public and the least
accessibility is private.
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

(i) Write the Java expressions for:


a^2 + b^2/2ab
Answer
(a * a + b * b) / (2 * a * b)

(j) If int y = 10 then find int z = (++y * (y++ + 5));


Answer

z = (++y * (y++ + 5))


⇒ z = (11 * (11 + 5))
⇒ z = (11 * 16)
⇒ z = 176

SECTION B

Question 4

Define a class called ParkingLot with the following description:


Instance variables/data members:
int vno — To store the vehicle number.
int hours — To store the number of hours the vehicle is parked in
the parking lot.
double bill — To store the bill amount.

Member Methods:
void input() — To input and store the vno and hours.
void calculate() — To compute the parking charge at the rate of ₹3
for the first hour or part thereof, and ₹1.50 for each additional hour
or part thereof.
void display() — To display the detail.

Write a main() method to create an object of the class and call the
above methods.
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class ParkingLot


{
private int vno;
private int hours;
private double bill;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter vehicle number: ");
vno = in.nextInt();
System.out.print("Enter hours: ");
hours = in.nextInt();
}

public void calculate() {


if (hours <= 1)
bill = 3;
elsebill = 3 + (hours - 1) * 1.5;
}

public void display() {


System.out.println("Vehicle number: " + vno);
System.out.println("Hours: " + hours);
System.out.println("Bill: " + bill);
}

public static void main(String args[]) {


ParkingLot obj = new ParkingLot();
obj.input();
obj.calculate();
obj.display();
}
}
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

Question 5

Write two separate programs to generate the following patterns


using iteration (loop) statements:
(a)

*
*#
*#*
*#*#
*#*#*
(b)

5 4321
5 432
5 43
5 4
5

Answer

public class Pattern


{
public static void main(String args[]) {
for (int i = 1; i <=5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print("# ");
elseSystem.out.print("* ");
}
System.out.println();
}
}
}
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

(B)
Answer
public class Pattern
{
public static void main(String args[]) {
for (int i = 1; i <=5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

Question 6
Write a program to input and store roll numbers,
names and marks in 3 subjects of n number of students
in five single dimensional arrays and display the
remark based on average marks as given below:

Average Marks. Remarks


85 — 100. Excellent
75 — 84. Distinction
60 — 74. First Class
40 — 59. Pass
Less than 40. Poor
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class AvgMarks


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

Scanner in = new Scanner(System.in);


System.out.print("Enter number of students: ");
int n = in.nextInt();

int rollNo[] = new int[n];


String name[] = new String[n];
int s1[] = new int[n];
int s2[] = new int[n];
int s3[] = new int[n];
double avg[] = new double[n];

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


System.out.println("Enter student " + (i+1) + " details:");
System.out.print("Roll No: ");
rollNo[i] = in.nextInt();
in.nextLine();
System.out.print("Name: ");
name[i] = in.nextLine();
System.out.print("Subject 1 Marks: ");
s1[i] = in.nextInt();
System.out.print("Subject 2 Marks: ");
s2[i] = in.nextInt();
System.out.print("Subject 3 Marks: ");
s3[i] = in.nextInt();
avg[i] = (s1[i] + s2[i] + s3[i]) / 3.0;
}

System.out.println("Roll No\tName\tRemark");
for (int i = 0; i < n; i++) {
String remark;
if (avg[i] < 40)
remark = "Poor";
else if (avg[i] < 60)
remark = "Pass";
else if (avg[i] < 75)
remark = "First Class";
else if (avg[i] < 85)
remark = "Distinction";
elseremark = "Excellent";
System.out.println(rollNo[i] + "\t"
+ name[i] + "\t"
+ remark);
}
}
}
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

Question 7

Design a class to overload a function Joystring( ) as follows:


void Joystring(String s, char ch1, char ch2) with one string
argument and two character arguments that replaces the
character argument ch1 with the character argument ch2 in the
given String s and prints the new string.
Example:
Input value of s = "TECHNALAGY"
ch1 = 'A'
ch2 = 'O'
Output: "TECHNOLOGY"

void Joystring(String s) with one string argument that prints


the position of the first space and the last space of the given
String s.
Example:
Input value of s = "Cloud computing means Internet based
computing"
Output:
First index: 5
Last Index: 36

void Joystring(String s1, String s2) with two string arguments


that combines the two strings with a space between them and
prints the resultant string.
Example:
Input value of s1 = "COMMON WEALTH"
Input value of s2 = "GAMES"
Output: COMMON WEALTH GAMES
(Use library functions)
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

Answer
public class StringOverload
{
public void joystring(String s, char ch1, char ch2) {
String newStr = s.replace(ch1, ch2);
System.out.println(newStr);
}

public void joystring(String s) {


int f = s.indexOf(' ');
int l = s.lastIndexOf(' ');
System.out.println("First index: " + f);
System.out.println("Last index: " + l);
}

public void joystring(String s1, String s2) {


String newStr = s1.concat(" ").concat(s2);
System.out.println(newStr);
}

public static void main(String args[]) {


KboatStringOverload obj = new KboatStringOverload();
obj.joystring("TECHNALAGY", 'A', 'O');
obj.joystring("Cloud computing means Internet based computing");
obj.joystring("COMMON WEALTH", "GAMES");
}
}

Question 8

Write a program to input twenty names in an array.


Arrange these names in descending order of letters,
using the bubble sort technique.
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class ArrangeNames


{
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 Sortfor (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]);
}
}
}

Question 9
Using switch statement, write a menu driven program to:
(i) To find and display all the factors of a number input by the user (
including 1 and the excluding the number itself).
Example:
Sample Input : n = 15
Sample Output : 1, 3, 5

(ii) To find and display the factorial of a number input by the user (the
factorial of a non-negative integer n, denoted by n!, is the product of all
integers less than or equal to n.)
Example:
Sample Input : n = 5
Sample Output : 5! = 1*2*3*4*5 = 120
For an incorrect choice, an appropriate error message should be displayed.
SAVIOUR OF COMPUTERS

2015 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class Menu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Factors of number");
System.out.println("2. Factorial of number");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
int num;

switch (choice) {
case 1:
System.out.print("Enter number: ");
num = in.nextInt();
for (int i = 1; i < num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
break;

case 2:
System.out.print("Enter number: ");
num = in.nextInt();
int f = 1;
for (int i = 1; i <= num; i++)
f *= i;
System.out.println("Factorial = " + f);
break;

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

2016 COMPUTER
APPLICATION PAPER

SECTION A

Question 1

(a) Define Encapsulation.


Answer

Encapsulation is a mechanism that binds together code and the


data it manipulates. It keeps them both safe from the outside world,
preventing any unauthorised access or misuse. Only member
methods, which are wrapped inside the class, can access the data
and other methods.

(b) What are keywords ? Give an example.


Answer

Keywords are reserved words that have a special meaning to the


Java compiler. Example: class, public, int, etc.

(c) Name any two library packages.


Answer

Two library packages are:


1. java.io
2. java.util

(d) Name the type of error ( syntax, runtime or logical error) in


each case given below:
1. Math.sqrt (36 – 45)
2. int a;b;c;
Answer

1. Runtime Error
2. Syntax Error

(e) If int x[] = { 4, 3, 7, 8, 9, 10}; what are the values of p and q ?


1. p = x.length
2. q = x[2] + x[5] * x[1]

Answer
1.6
2.q = x[2] + x[5] * x[1]
q = 7 + 10 * 3
q = 7 + 30
q = 37
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

(a) State the difference between == operator and equals() method.

Answer

equals() ==
It is a method It is a relational operator
It is used to check if the It is used to check if two
contents of two strings are variables refer to the same
same or not Example: String s1 object in memory
= new String("hello");String s2 Example:String s1 = new
= new String("hello");boolean
String("hello");String s2 =
res
s1.equals(s2);System.out.printl new
n(res); String("hello");boolean res
The output of this code = s1 ==
snippet is true as contents of s2;System.out.println(res);
s1 and s2 are the same. The output of this code
snippet is false as s1 and s2
point to different String
objects.

(b) What are the types of casting shown by the following examples:
1. char c = (char) 120;
2. int x = ‘t’;

Answer

1. Explicit Cast.
2. Implicit Cast.

(c) Differentiate between formal parameter and actual parameter.

Answer

Formal parameter Actual parameter

Formal Actual parameters


parameters appear in function
appear in function call statement.
definition. They represent the
They represent values passed to
the values the called function.
received by the
called function.
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

(d) Write a function prototype of the following:


A function PosChar which takes a string argument and a
character argument and returns an integer value.
Answer

int PosChar(String s, char ch)

(e) Name any two types of access specifiers.


Answer

1. public
2. private

Question 3
(a) Give the output of the following string functions:
1. "MISSISSIPPI".indexOf('S') + "MISSISSIPPI".lastIndexOf('I')
2. "CABLE".compareTo("CADET")
Answer

1. 2 + 10 = 12
2. ASCII Code of B - ASCII Code of D
⇒ 66 - 68
⇒ -2

(b) Give the output of the following Math functions:


1. Math.ceil(4.2)
2. Math.abs(-4)
Answer

1. 5.0
2. 4

(c) What is a parameterized constructor ?


Answer

A Parameterised constructor receives parameters at the time of


creating an object and initializes the object with the received values.
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

(d) Write down java expression for:


Answer

T = Math.sqrt(a*a + b*b + c*c)

(e) Rewrite the following using ternary operator:


if (x%2 == 0)
System.out.print("EVEN");
elseSystem.out.print("ODD");
Answer

System.out.print(x%2 == 0 ? "EVEN" : "ODD");

(f) Convert the following while loop to the corresponding for


loop:
int m = 5, n = 10;
while (n>=1)
{
System.out.println(m*n);
n--;
}
Answer

int m = 5;
for (int n = 10; n >= 1; n--) {
System.out.println(m*n);
}

(g) Write one difference between primitive data types and


composite data types.
Answer

Primitive Data Types are built-in data types defined by Java


language specification whereas Composite Data Types are defined
by the programmer.
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

(h) Analyze the given program segment and answer the following
questions:

1. Write the output of the program segment.


2. How many times does the body of the loop gets executed ?
for(int m = 5; m <= 20; m += 5)
{ if(m % 3 == 0)
break;
elseif(m % 5 == 0)
System.out.println(m);
continue;
}
Answer

Output
5
10
Loop executes 3 times

(i) Give the output of the following expression:


a+= a++ + ++a + --a + a-- ; when a = 7
Answer

a+= a++ + ++a + --a + a--


⇒ a = a + (a++ + ++a + --a + a--)
⇒ a = 7 + (7 + 9 + 8 + 8)
⇒ a = 7 + 32
⇒ a = 39

(j) Write the return type of the following library functions:


1. isLetterOrDigit(char)
2. replace(char, char)
Answer

1. boolean
2. String
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

(h) Analyze the given program segment and answer the following
questions:

1. Write the output of the program segment.


2. How many times does the body of the loop gets executed ?
for(int m = 5; m <= 20; m += 5)
{ if(m % 3 == 0)
break;
elseif(m % 5 == 0)
System.out.println(m);
continue;
}
Answer

Output
5
10
Loop executes 3 times

(i) Give the output of the following expression:


a+= a++ + ++a + --a + a-- ; when a = 7
Answer

a+= a++ + ++a + --a + a--


⇒ a = a + (a++ + ++a + --a + a--)
⇒ a = 7 + (7 + 9 + 8 + 8)
⇒ a = 7 + 32
⇒ a = 39

(j) Write the return type of the following library functions:


1. isLetterOrDigit(char)
2. replace(char, char)
Answer

1. boolean
2. String
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

SECTION B

Question 4
Define a class named BookFair with the following description:
Instance variables/Data members:
String Bname — stores the name of the book
double price — stores the price of the book

Member methods:

(i) BookFair() — Default constructor to initialize data members


(ii) void Input() — To input and store the name and the price of the
book.
(iii) void calculate() — To calculate the price after discount.
Discount is calculated based on the following criteria.

Price. Discount
Less than or equal to ₹1000. 2% of price
More than ₹1000 and less than or equal to ₹3000. 10% of price
More than ₹3000. 15% of price

(iv) void display() — To display the name and price of the book
after discount.

Write a main method to create an object of the class and call the
above member methods.
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

import java.util.Scanner;

public class BookFair


{
private String bname;
private double price;

public BookFair() {
bname = "";
price = 0.0;
}

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter name of the book: ");
bname = in.nextLine();
System.out.print("Enter price of the book: ");
price = in.nextDouble();
}

public void calculate() {


double disc;
if (price <= 1000)
disc = price * 0.02;
else if (price <= 3000)
disc = price * 0.1;
elsedisc = price * 0.15;

price -= disc;
}

public void display() {


System.out.println("Book Name: " + bname);
System.out.println("Price after discount: " + price);
}

public static void main(String args[]) {


BookFair obj = new BookFair();
obj.input();
obj.calculate();
obj.display();
}
}
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

Question 5
Using the switch statement, write a menu driven program for the
following:

(i) To print the Floyd’s triangle [Given below]


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

(b) To display the following pattern:


I
IC
ICS
ICSE
For an incorrect option, an appropriate error message should be
displayed.
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

import java.util.Scanner;

public class Pattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Floyd's triangle");
System.out.println("Type 2 for an ICSE pattern");

System.out.print("Enter your choice: ");


int ch = in.nextInt();

switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
break;

case 2:
String s = "ICSE";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(s.charAt(j) + " ");
}
System.out.println();
}
break;

default:
System.out.println("Incorrect Choice");
}
}
}
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

Question 6
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.
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

Answer
import java.util.Scanner;

public class SpecialPalindrome


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

}
}
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

question7

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)s=1+(1×2)+(1×2×3)+... ...
... +(1×2×3×4... ... ... ×20)

Answer
public class Overload
{
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;
elsesum += 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);
}
}
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

Question 8

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)s=1+(1×2)+(1×2×3)+... ... ... +
(1×2×3×4... ... ... ×20)

Answer
import java.util.Scanner;

public class NivenNumber


{
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");
}
}
SAVIOUR OF COMPUTERS

2016 COMPUTER
APPLICATION PAPER

Question 9
Write a program to initialize the seven Wonders of the World along with their
locations in two different arrays. Search for a name of the country input by the
user. If found, display the name of the country along with its Wonder, otherwise
display "Sorry not found!".
Seven Wonders:
CHICHEN ITZA, CHRIST THE REDEEMER, TAJ MAHAL, GREAT WALL OF CHINA,
MACHU PICCHU, PETRA, COLOSSEUM
Locations:
MEXICO, BRAZIL, INDIA, CHINA, PERU, JORDAN, ITALY
Examples:
Country name: INDIA
Output: TAJ MAHAL
Country name: USA
Output: Sorry Not found!

Answer

import java.util.Scanner;

public class 7Wonders


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

String wonders[] = {"CHICHEN ITZA", "CHRIST THE REDEEMER", "TAJMAHAL",


"GREAT WALL OF CHINA", "MACHU PICCHU", "PETRA", "COLOSSEUM"};

String locations[] = {"MEXICO", "BRAZIL", "INDIA", "CHINA", "PERU", "JORDAN",


"ITALY"};

Scanner in = new Scanner(System.in);


System.out.print("Enter country: ");
String c = in.nextLine();
int i;

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


if (locations[i].equals(c)) {
System.out.println(locations[i] + " - " + wonders[i]);
break;
}
}

if (i == locations.length)
System.out.println("Sorry Not Found!");
}
}
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

SECTION A

Question 1
(a) What is inheritance?
Answer

Inheritance is the mechanism by which a class acquires the properties and


methods of another class.

(b) Name the operators listed below:


1. <
2. ++
3. &&
4. ? :
Answer

1. Less than operator. (It is a relational operator)


2. Increment operator. (It is an arithmetic operator)
3. Logical AND operator. (It is a logical operator)
4. Ternary operator. (It is a conditional operator)

(c) State the number of bytes occupied by char and int data types.
Answer

char occupies 2 bytes and int occupies 4 bytes.

(d) Write one difference between / and % operator.


Answer
/ operator computes the quotient whereas % operator computes the
remainder.

(e) String x[] = {"SAMSUNG", "NOKIA", "SONY", "MICROMAX",


"BLACKBERRY"};
Give the output of the following statements:
1. System.out.println(x[1]);
2. System.out.println(x[3].length());
Answer

1. The output of System.out.println(x[1]); is NOKIA. x[1] gives the second


element of the array x which is "NOKIA"
2. The output of System.out.println(x[3].length()); is 8. x[3].length() gives the
number of characters in the fourth element of the array x which is
MICROMAX.
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Question 2
(a) Name the following:
1. A keyword used to call a package in the program.
2. Any one reference data type.
Answer

1. import
2. Array

(b) What are the two ways of invoking functions?


Answer

Call by value and call by reference.

(c) State the data type and value of res after the following is executed:
char ch='t';
res= Character.toUpperCase(ch);
Answer

Data type of res is char and its value is T.

(d) Give the output of the following program segment and also mention the
number of times the loop is executed:

int a,b;
for (a = 6, b = 4; a <= 24; a = a + 6)
{
if (a%b == 0)
break;
}
System.out.println(a);
Answer

Output of the above code is 12 and loop executes 2 times.

(e) Write the output:


char ch = 'F';
int m = ch;
m=m+5;
System.out.println(m + " " + ch);
Answer

Output of the above code is:


75 F
Explanation
The statement int m = ch; assigns the ASCII value of F (which is 70) to variable m.
Adding 5 to m makes it 75. In the println statement, the current value of m which is
75 is printed followed by space and then value of ch which is F.
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Question 3
(a) Write a Java expression for the following:
ax^5+ bx^3 + c
Answer
a * Math.pow(x, 5) + b * Math.pow(x, 3) + c

(b) What is the value of x1 if x=5?


x1= ++x – x++ + --x
Answer
x1 = ++x – x++ + --x
⇒ x1 = 6 - 6 + 6
⇒ x1 = 0 + 6
⇒ x1 = 6

(c) Why is an object called an instance of a class?


Answer
A class can create objects of itself with different characteristics and common
behaviour. So, we can say that an Object represents a specific state of the class. For
these reasons, an Object is called an Instance of a Class.

(d) Convert following do-while loop into for loop.


int i = 1;
int d = 5;
do {
d=d*2;
System.out.println(d);
i++ ; } while ( i<=5);
Answer
int i = 1;
int d = 5;
for (i = 1; i <= 5; i++) {
d=d*2;
System.out.println(d);
}

(e) Differentiate between constructor and function.


Answer

Constructor Function

Constructor is a block Function is a group of


of code that initializes statements that can be
a newly created called at any point in the
object. program using its name
Constructor has the to perform a specific task.
same name as class Function should have a
name. different name than class
Constructor has no name.
return type not even Function requires a valid
void. return type.
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

(f) Write the output for the following:


String s="Today is Test";
System.out.println(s.indexOf('T'));
System.out.println(s.substring(0,7) + " " +"Holiday");
Answer
Output of the above code is:
0
Today i Holiday

Explanation
As the first T is present at index 0 in string s so s.indexOf('T') returns 0.
s.substring(0,7) extracts the characters from index 0 to index 6 of string s. So its
result is Today i. After that println statement prints Today i followed by a space
and Holiday

(g) What are the values stored in variables r1 and r2:


1. double r1 = Math.abs(Math.min(-2.83, -5.83));
2. double r2 = Math.sqrt(Math.floor(16.3));
Answer
1. r1 has 5.83
2. r2 has 4.0

Explanation
1. Math.min(-2.83, -5.83) returns -5.83 as -5.83 is less than -2.83. (Note that these
are negative numbers). Math.abs(-5.83) returns 5.83.
2. Math.floor(16.3) returns 16.0. Math.sqrt(16.0) gives square root of 16.0 which is
4.0.

(h) Give the output of the following code:


String A ="26", B="100";
String D=A+B+"200";
int x= Integer.parseInt(A);
int y = Integer.parseInt(B);
int d = x+y;
System.out.println("Result 1 = " + D);
System.out.println("Result 2 = " + d);
Answer
Output of the above code is:
Result 1 = 26100200
Result 2 = 126

Explanation
1. As A and B are strings so String D=A+B+"200"; joins A, B and "200" storing the
string "26100200" in D.
2. Integer.parseInt() converts strings A and B into their respective numeric values.
Thus, x becomes 26 and y becomes 100.
3. As Java is case-sensitive so D and d are treated as two different variables.
4. Sum of x and y is assigned to d. Thus, d gets a value of 126.
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

(i) Analyze the given program segment and answer the


following questions:
for(int i=3;i<=4;i++ ) {
for(int j=2;j<i;j++ ) {
System.out.print("" ); }
System.out.println("WIN" ); }
1. How many times does the inner loop execute?
2. Write the output of the program segment.
Answer

1. Inner loop executes 3 times. (For 1st iteration of outer loop,


inner loop executes once. For 2nditeration of outer loop,
inner loop executes two times.)
2. Output:
WIN
WIN

(j) What is the difference between the Scanner class functions


next() and nextLine()?
Answer

next() nextLine

It reads the input till


It reads the input
the end of line so it
only till space so it
can read a full
can read only a
sentence including
single word.
spaces.
It places the cursor in
It places the cursor in
the same line after
the next line after
reading the input.
reading the input.
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

SECTION B

Question 4 Define a class ElectricBill with the following


specifications:
class : ElectricBill

Instance variables / data member:


String n — to store the name of the customer
int units — to store the number of units consumed
double bill — to store the amount to be paid

Member methods:
void accept( ) — to accept the name of the customer and
number of units consumed
void calculate( ) — to calculate the bill as per the following
tariff:

Number of units. Rate per unit


First 100 units. Rs.2.00
Next 200 units. Rs.3.00
Above 300 units. Rs.5.00

A surcharge of 2.5% charged if the number of units consumed is


above 300 units.
void print( ) — To print the details as follows:
Name of the customer: ………………………
Number of units consumed: ………………………
Bill amount: ………………………

Write a main method to create an object of the class and call


the above member methods.
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class ElectricBill


{
private String n;
private int units;
private double bill;

public void accept() {


Scanner in = new Scanner(System.in);
System.out.print("Enter customer name: ");
n = in.nextLine();
System.out.print("Enter units consumed: ");
units = in.nextInt();
}

public void calculate() {


if (units <= 100)
bill = units * 2;
else if (units <= 300)
bill = 200 + (units - 100) * 3;
else {
double amt = 200 + 600 + (units - 300) * 5;
double surcharge = (amt * 2.5) / 100.0;
bill = amt + surcharge;
}
}

public void print() {


System.out.println("Name of the customer\t\t: " + n);
System.out.println("Number of units consumed\t: " + units);
System.out.println("Bill amount\t\t\t: " + bill);
}

public static void main(String args[]) {


ElectricBill obj = new ElectricBill();
obj.accept();
obj.calculate();
obj.print();
}
}
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Question 5
Write a program to accept a number and check and display
whether it is a spy number or not. (A number is spy if the sum of its
digits equals the product of its digits.)
Example: consider the number 1124.
Sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1 x 1 x 2 x 4 = 8
Answer

import java.util.Scanner;

public class SpyNumber


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

Scanner in = new Scanner(System.in);

System.out.print("Enter Number: ");


int num = in.nextInt();

int digit, sum = 0;


int orgNum = num;
int prod = 1;

while (num > 0) {


digit = num % 10;

sum += digit;
prod *= digit;
num /= 10;
}

if (sum == prod)
System.out.println(orgNum + " is Spy Number");
elseSystem.out.println(orgNum + " is not Spy Number");

}
}
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Question 6
Using switch statement, write a menu driven program for the
following:
1. To find and display the sum of the series given below:
S = x^1- x^2 + x^3 - x^4 + x^5 .......... - x^20 (where x = 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;
elsesum += 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;
}
}
}
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Question 7
Write a program to input integer elements into an array of size
20 and perform the following operations:
1. Display largest number from the array.
2. Display smallest number from the array.
3. Display sum of all the elements of the array

Answer
import java.util.Scanner;

public class KboatSDAMinMaxSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[20];
System.out.println("Enter 20 numbers:");
for (int i = 0; i < 20; i++) {
arr[i] = in.nextInt();
}
int min = arr[0], max = arr[0], sum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];

if (arr[i] > max)


max = arr[i];

sum += arr[i];
}

System.out.println("Largest Number = " + max);


System.out.println("Smallest Number = " + min);
System.out.println("Sum = " + sum);
}
}
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Question8
Design a class to overload a function check( ) as follows:
void check (String str , char ch ) — to find and print the frequency of a
character in a string.Example:
Input:
str = "success"
ch = 's'
Output:
number of s present is = 3

void check(String s1) — to display only vowels from string s1, after converting
it to lower case.Example:
Input:
s1 ="computer"
Output : o u e

Answer

public class Overload


{
void check (String str , char ch ) {
int count = 0;
int len = str.length();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Frequency of " + ch + " = " + count);
}

void check(String s1) {


String s2 = s1.toLowerCase();
int len = s2.length();
System.out.println("Vowels:");
for (int i = 0; i < len; i++) {
char ch = s2.charAt(i);
if (ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u')
System.out.print(ch + " ");
}
}
}
SAVIOUR OF COMPUTERS

2017 COMPUTER
APPLICATION PAPER

Question 9
Write a program to input forty words in an array. Arrange these words in
descending order of alphabets, using selection sort technique. Print the sorted
array.

Answer

import java.util.Scanner;

public class SelectionSort


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

System.out.println("Enter 40 Names: ");


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

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


int idx = i;
for (int j = i + 1; j < n; j++) {
if (a[j].compareToIgnoreCase(a[idx]) < 0) {
idx = j;
}
}
String t = a[idx];
a[idx] = a[i];
a[i] = t;
}

System.out.println("Sorted Names");
for (int i = 0; i < n; i++) {
System.out.println(a[i]);
}
}
}
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

SECTION A

Question 1

(a) Define abstraction.


Answer

Abstraction refers to the act of representing essential features without including


the background details or explanation.

(b) Differentiate between searching and sorting.


Answer

Searching Sorting

Searching means to Sorting means to


search for a term or arrange the elements of
the array in ascending
value in an array. or descending order.
Linear search and Bubble sort and
Binary search are Selection sort are
examples of search examples of sorting
techniques. techniques.

(c) Write a difference between the functions isUpperCase( ) and toUpperCase(


).
Answer

isUpperCase( ) toUpperCase( )

isUpperCase( ) toUpperCase( )
function checks if a function converts
given character is in a given character
uppercase or not. to uppercase.
Its return type is Its return type is
boolean. char.
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

(d) How are private members of a class different from public members?
Answer

private members of a class can only be accessed by other member methods of the
same class whereas public members of a class can be accessed by methods of
other classes as well.

(e) Classify the following as primitive or non-primitive datatypes:


1. char
2. arrays
3. int
4. classes
Answer

1. Primitive
2. Non-Primitive
3. Primitive
4. Non-Primitive

Question 2
(a) (i) int res = 'A';
What is the value of res?
Answer

Value of res is 65 which is the ASCII code of A. As res is an int variable and we are
trying to assign it the character A so through implicit type conversion the ASCII
code of A is assigned to res.

(ii) Name the package that contains wrapper classes.


Answer

java.lang

(b) State the difference between while and do while loop.


Answer

while do-while
It is an entry- it is an exit-
controlled loop. controlled loop.
It is helpful in It is suitable when
situations where we need to display
numbers of a menu to the user.
iterations are not
known.
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

(c) System.out.print("BEST ");


System.out.println("OF LUCK");
Choose the correct option for the output of the above statements
1. BEST OF LUCK
2. BEST
3. OF LUCK
Answer

Option 1 — BEST OF LUCK is the correct option.


System.out.print does not print a newline at the end of its output so the println
statement begins printing on the same line. So the output is BEST OF LUCK
printed on a single line.

(d) Write the prototype of a function check which takes an integer as an


argument and returns a character.
Answer

char check(int a)

(e) Write the return data type of the following function.


1. endsWith()
2. log()
Answer

1. boolean
2. double

Question 3

(a) Write a Java expression for the following:

Answer
Math.sqrt(3 * x + x * x) / (a + b)

(b) What is the value of y after evaluating the expression given below?
y+= ++y + y-- + --y; when int y=8
Answer

y+= ++y + y-- + --y


⇒ y = y + (++y + y-- + --y)
⇒ y = 8 + (9 + 9 + 7)
⇒ y = 8 + 25
⇒ y = 33
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

(c) Give the output of the following:


1. Math.floor (-4.7)
2. Math.ceil(3.4) + Math.pow(2, 3)
Answer

1. -5.0
2. 12.0

(d) Write two characteristics of a constructor.


Answer

Two characteristics of a constructor are:


1. A constructor has the same name as its class.
2. A constructor does not have a return type.

(e) Write the output for the following:


System.out.println("Incredible"+"\n"+"world");
Answer

Output of the above code is:


Incredible
world

\n is the escape sequence for newline so Incredible and world are printed on two
different lines.

(f) Convert the following if else if construct into switch case


if( var==1)
System.out.println("good");
else if(var==2)
System.out.println("better");
else if(var==3)
System.out.println("best");
elseSystem.out.println("invalid");
Answer

switch (var) {
case 1:
System.out.println("good");
break;

case 2:
System.out.println("better");
break;

case 3:
System.out.println("best");
break;

default:
System.out.println("invalid");
}
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

(g) Give the output of the following string functions:


1. "ACHIEVEMENT".replace('E', 'A')
2. "DEDICATE".compareTo("DEVOTE")
Answer

1. ACHIAVAMANT
2. -18
Explanation
1. "ACHIEVEMENT".replace('E', 'A') will replace all the E's in
ACHIEVEMENT with A's.
2. The first letters that are different in DEDICATE and DEVOTE are D
and V respectively. So the output will be: ASCII code of D - ASCII
code of V
⇒ 68 - 86
⇒ -18

(h) Consider the following String array and give the output
String arr[]= {"DELHI", "CHENNAI", "MUMBAI", "LUCKNOW",
"JAIPUR"};
System.out.println(arr[0].length() > arr[3].length());
System.out.print(arr[4].substring(0,3));
Answer

Output of the above code is:


false
JAI
Explanation
1. arr[0] is DELHI and arr[3] is LUCKNOW. Length of DELHI is 5 and
LUCKNOW is 7. As 5 > 7 is false so the output is false.
2. arr[4] is JAIPUR. arr[4].substring(0,3) extracts the characters from
index 0 till index 2 of JAIPUR so JAI is the output.

(i) Rewrite the following using ternary operator:


if (bill > 10000 )
discount = bill * 10.0/100;
elsediscount = bill * 5.0/100;
Answer

discount = bill > 10000 ? bill * 10.0/100 : bill * 5.0/100;


SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

(j) Give the output of the following program segment and also
mention how many times the loop is executed:
int i;
for ( i = 5 ; i > 10; i ++ )
System.out.println( i );
System.out.println( i * 4 );
Answer

Output of the above code is:


20
Loop executes 0 times.
Explanation

In the loop, i is initialized to 5 but the condition of the loop is i > 10. As 5
is less than 10 so the condition of the loop is false and it is not executed.
There are no curly braces after the loop which means that the
statement System.out.println( i ); is inside the loop and the statement
System.out.println( i * 4 ); is outside the loop. Loop is not executed so
System.out.println( i ); is not executed but System.out.println( i * 4 );
being outside the loop is executed and prints the output as 20 (i * 4 ⇒ 5
* 4 ⇒ 20).
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

SECTION B

Question 4
Design a class RailwayTicket with following description:
Instance variables/data members:

String name — To store the name of the customer


String coach — To store the type of coach customer wants to travel
long mobno — To store customer’s mobile number
int amt — To store basic amount of ticket
int totalamt — To store the amount to be paid after updating the original
amount

Member methods:
void accept() — To take input for name, coach, mobile number and
amount.
void update() — To update the amount as per the coach selected (extra
amount to be added in the amount as follows)

Type of Coaches. Amount


First_AC. 700
Second_AC. 500
Third_AC. 250
sleeper. None

void display() — To display all details of a customer such as name, coach,


total amount and mobile number.
Write a main method to create an object of the class and call the above
member methods.
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

Answer

import java.util.Scanner;

public class RailwayTicket


{
private String name;
private String coach;
private long mobno;
private int amt;
private int totalamt;

private void accept() {


Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter coach: ");
coach = in.nextLine();
System.out.print("Enter mobile no: ");
mobno = in.nextLong();
System.out.print("Enter amount: ");
amt = in.nextInt();
}

private void update() {


if(coach.equalsIgnoreCase("First_AC"))
totalamt = amt + 700;
else if(coach.equalsIgnoreCase("Second_AC"))
totalamt = amt + 500;
else if(coach.equalsIgnoreCase("Third_AC"))
totalamt = amt + 250;
else if(coach.equalsIgnoreCase("Sleeper"))
totalamt = amt;
}

private void display() {


System.out.println("Name: " + name);
System.out.println("Coach: " + coach);
System.out.println("Total Amount: " + totalamt);
System.out.println("Mobile number: " + mobno);
}

public static void main(String args[]) {


RailwayTicket obj = new RailwayTicket();
obj.accept();
obj.update();
obj.display();
}
}
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

Question 5

Write a program to input a number and check and print whether it


is a Pronic number or not. (Pronic number is the number which is
the product of two consecutive integers)
Examples:
12 = 3 x 4
20 = 4 x 5
42 = 6 x 7
Answer

import java.util.Scanner;

public class PronicNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to check: ");
int num = in.nextInt();

boolean isPronic = false;

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


if (i * (i + 1) == num) {
isPronic = true;
break;
}
}

if (isPronic)
System.out.println(num + " is a pronic number");
elseSystem.out.println(num + " is not a pronic number");
}
}
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

Question 6
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.
Sample input: we are in cyber world
Sample output: We Are In Cyber World
Answer

import java.util.Scanner;

public class String


{
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);
}
}
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

Question 7
Design a class to overload a function volume() as follows:
double volume (double R) – with radius (R) as an argument,
returns the volume of sphere using the formula.
V = 4/3 x 22/7 x R^3
double volume (double H, double R) – with height(H) and
radius(R) as the arguments, returns the volume of a cylinder
using the formula. V = 22/7 x R^2 x H
double volume (double L, double B, double H) – with length(L),
breadth(B) and Height(H) as the arguments, returns the volume
of a cuboid using the formula. V = L x B x H
Answer

public class Volume


{
double volume(double r) {
return (4 / 3.0) * (22 / 7.0) * r * r * r;
}

double volume(double h, double r) {


return (22 / 7.0) * r * r * h;
}

double volume(double l, double b, double h) {


return l * b * h;
}

public static void main(String args[]) {


KboatVolume obj = new KboatVolume();
System.out.println("Sphere Volume = " +
obj.volume(6));
System.out.println("Cylinder Volume = " +
obj.volume(5, 3.5));
System.out.println("Cuboid Volume = " +
obj.volume(7.5, 3.5, 2));
}
}
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

Question 8
Write a menu driven program to display the pattern as per
user’s choice.
Pattern 1
ABCDE
ABCD
ABC
AB
A
Pattern 2
B
LL
UUU
EEEE
For an incorrect option, an appropriate error message should
be displayed.
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

import java.util.Scanner;

public class MenuPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 1 for pattern 1");
System.out.println("Enter 2 for Pattern 2");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
switch (choice) {
case 1:
for (int i = 69; i >= 65; i--) {
for (int j = 65; j <= i; j++) {
System.out.print((char)j);
}
System.out.println();
}
break;

case 2:
String word = "BLUE";
int len = word.length();
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}
break;

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

}
}
}
SAVIOUR OF COMPUTERS

2018 COMPUTER
APPLICATION PAPER

Question 9
Write a program to accept name and total marks of N number of
students in two single subscript array name[] and totalmarks[].
Calculate and print:
1. The average of the total marks obtained by N number of
students.
2. [average = (sum of total marks of all the students)/N]
3. Deviation of each student’s total marks with the average.
4. [deviation = total marks of a student – average]
Answer

import java.util.Scanner;

public class SDAMarks


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = in.nextInt();

String name[] = new String[n];


int totalmarks[] = new int[n];
int grandTotal = 0;

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


in.nextLine();
System.out.print("Enter name of student " + (i+1) + ": ");
name[i] = in.nextLine();
System.out.print("Enter total marks of student " + (i+1) + ": ");
totalmarks[i] = in.nextInt();
grandTotal += totalmarks[i];
}

double avg = grandTotal / (double)n;


System.out.println("Average = " + avg);

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


System.out.println("Deviation for " + name[i] + " = "
+ (totalmarks[i] - avg));
}
}
}
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

SECTION A

Question 1
(a) Name any two basic principles of Object-oriented Programming.
Answer
1. Encapsulation
2. Inheritance

(b) Write a difference between unary and binary operator.


Answer
unary operators operate on a single operand whereas binary operators
operate on two operands.

(c) Name the keyword which:


1. indicates that a method has no return type.
2. makes the variable as a class variable
Answer
1. void
2. static

(d) Write the memory capacity (storage size) of short and float data
type in bytes.
Answer
1. short — 2 bytes
2. float — 4 bytes

(e) Identify and name the following tokens:


1. public
2. 'a'
3. ==
4. { }
Answer
1. Keyword
2. Literal
3. Operator
4. Separator
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

Question 2
(a) Differentiate between if else if and switch-case statements
Answer

if else if switch-case

if else if can test for any switch-case can only


Boolean expression like test if the expression is
less than, greater than, equal to any of its case
equal to, not equal to,
etc. constants.
if else if can use switch-case statement
different expression tests the same
involving unrelated expression against a
variables in its different set of constant values.
condition expressions.

(b) Give the output of the following code:


String P = "20", Q ="19";
int a = Integer.parseInt(P);
int b = Integer.valueOf(Q);
System.out.println(a+""+b);
Answer

Output of the above code is:


2019
Explanation
Both Integer.parseInt() and Integer.valueOf() methods convert a string
into integer. Integer.parseInt() returns an int value that gets assigned
to a. Integer.valueOf() returns an Integer object (i.e. the wrapper class
of int). Due to auto-boxing, Integer object is converted to int and gets
assigned to b. So a becomes 20 and b becomes 19. 2019 is printed as
the output.

(c) What are the various types of errors in Java?


Answer

There are 3 types of errors in Java:


1. Syntax Error
2. Runtime Error
3. Logical Error
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

(d) State the data type and value of res after the following is
executed:
char ch = '9';
res= Character.isDigit(ch);
Answer

Data type of res is boolean as return type of method Character.isDigit()


is boolean. Its value is true as '9' is a digit.

(e) What is the difference between the linear search and the binary
search technique?
Answer

Linear search Binary search


Linear search works on Binary search works on
sorted and unsorted only sorted arrays.
arrays. In Binary search, array
In Linear search, each
element of the array is is successively divided
checked against the into 2 halves and the
target value until the target element is
element is found or end searched either in the
of the array is reached. first half or in the
Linear Search is slower. second half.
Binary Search is faster.

Question 3
(a) Write a Java expression for the following:
|x^2+ 2xy|
Answer

Math.abs(x * x + 2 * x * y)

(b) Write the return data type of the following functions:


1. startsWith()
2. random()
Answer

1. boolean
2. double
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

(c) If the value of basic=1500, what will be the value of tax after the
following statement is executed?
tax = basic > 1200 ? 200 :100;
Answer

Value of tax will be 200. As basic is 1500, the condition of ternary


operator — basic > 1200 is true. 200 is returned as the result of ternary
operator and it gets assigned to tax.

(d) Give the output of following code and mention how many times
the loop will execute?
int i;
for( i=5; i>=1; i--)
{
if(i%2 == 1)
continue;
System.out.print(i+" ");
}
Answer

Output of the above code is:


42
Loop executes 5 times.

(e) State a difference between call by value and call by reference.


Answer
In call by value, actual parameters are copied to formal parameters.
Any changes to formal parameters are not reflected onto the actual
parameters. In call by reference, formal parameters refer to actual
parameters. The changes to formal parameters are reflected onto the
actual parameters.

(f) Give the output of the following:


Math.sqrt(Math.max(9,16))
Answer
The output is 4.0.
First Math.max(9,16) is evaluated. It returns 16, the greater of its
arguments. Math.sqrt(Math.max(9,16)) becomes Math.sqrt(16). It returns
the square root of 16 which is 4.0.
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

(g) Write the output for the following:


String s1 = "phoenix"; String s2 ="island";
System.out.println(s1.substring(0).concat(s2.substring(2)));
System.out.println(s2.toUpperCase());
Answer

The output of above code is:


phoenixland
ISLAND
Explanation
s1.substring(0) results in phoenix. s2.substring(2) results in land.
concat method joins both of them resulting in phoenixland.
s2.toUpperCase() converts island to uppercase.

(h) Evaluate the following expression if the value of x=2, y=3


and z=1.
v=x + --z + y++ + y
Answer

v = x + --z + y++ + y
⇒v=2+0+3+4
⇒v=9
(i) String x[] = {"Artificial intelligence", "IOT", "Machine
learning", "Big data"};
Give the output of the following statements:
1. System.out.println(x[3]);
2. System.out.println(x.length);
Answer

1. Big data
2. 4

(j) What is meant by a package? Give an example.


Answer

A package is a named collection of Java classes that are grouped


on the basis of their functionality. For example, java.util.
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

SECTION B

Question 4
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

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%

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.
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

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;
elsedisPercent = 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();
}
}
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

Question 5
Using the switch-case statement, write a menu driven program to do the
following:
(a) To generate and print Letters from A to Z and their Unicode
Letters. Unicode
A. 65
B. 66
.
.
.
Z 90
(b) Display the following pattern using iteration (looping) statement:
1
12
123
1234
12345

Answer

import java.util.Scanner;

public class CK
{
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;
}
}
}
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

Question 6
Write a program to input 15 integer elements in an array and
sort them in ascending order using the bubble sort technique.
Answer

import java.util.Scanner;

public class BubbleSort


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = 15;
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 Sortfor (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] + " ");
}
}
}
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

Question 7
Design a class to overload a function series( ) as follows:
(a) void series (int x, int n) – To display the sum of the series
given below:
x^1+ x^2+ x^3 + .......... x^n terms
(b) void series (int p) – To display the following series:
0, 7, 26, 63 .......... p terms
(c) void series () – To display the sum of the series given below:
1/2 + 1/3 + 1/4 + .......... 1/10
Answer

public class OverloadSeries


{
void series(int x, int n) {
long sum = 0;
for (int i = 1; i <= n; i++) {
sum += Math.pow(x, i);
}
System.out.println("Sum = " + sum);
}

void series(int p) {
for (int i = 1; i <= p; i++) {
int term = (int)(Math.pow(i, 3) - 1);
System.out.print(term + " ");
}
System.out.println();
}

void series() {
double sum = 0.0;
for (int i = 2; i <= 10; i++) {
sum += 1.0 / i;
}
System.out.println("Sum = " + sum);
}
}
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

Question 8
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'.
Example:
Sample Input: ADVANCEMENT AND APPLICATION OF INFORMATION
TECHNOLOGY ARE EVER CHANGING.
Sample Output: Total number of words starting with letter 'A' = 4
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 strint 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);
}
}

Question 9
A tech number has even number of digits. If the number is split in
two equal halves, then the square of sum of these halves is equal to
the number itself. Write a program to generate and print all four
digits tech numbers.
Example:
Consider the number 3025
Square of sum of the halves of 3025 = (30 + 25)^2
(55)^2
= 3025 is a tech number.
SAVIOUR OF COMPUTERS

2019 COMPUTER
APPLICATION PAPER

Answer

public class TechNumbers


{
public static void main(String args[]) {
for (int i = 1000; i <= 9999; i++) {
int secondHalf = i % 100;
int firstHalf = i / 100;
int sum = firstHalf + secondHalf;
if (i == sum * sum)
System.out.println(i);
}
}
}
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

SECTION A

Question 1
(i) Return data type of isLetter(char) is ............... .
1. Boolean
2. boolean
3. bool
4. char
Answer

boolean

(II) Method that converts a character to uppercase is ............... .


1. toUpper()
2. ToUpperCase()
3. toUppercase()
4. toUpperCase(char)
Answer

toUpperCase(char

(iii) Give output of the following String methods:


"SUCESS".indexOf('S') + "SUCCESS".lastIndexOf('S')
1. 0
2. 5
3. 6
4. -5
Answer

(iv) Corresponding wrapper class of float data type is ............... .


1. FLOAT
2. float
3. Float
4. Floating
Answer

Float

(V) .............. class is used to convert a primitive data type to its


corresponding object.
1. String
2. Wrapper
3. System
4. Math
Answer

Wrapper
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

SECTION A

Question 1
(i) Return data type of isLetter(char) is ............... .
1. Boolean
2. boolean
3. bool
4. char
Answer

boolean

(II) Method that converts a character to uppercase is ............... .


1. toUpper()
2. ToUpperCase()
3. toUppercase()
4. toUpperCase(char)
Answer

toUpperCase(char

(iii) Give output of the following String methods:


"SUCESS".indexOf('S') + "SUCCESS".lastIndexOf('S')
1. 0
2. 5
3. 6
4. -5
Answer

(iv) Corresponding wrapper class of float data type is ............... .


1. FLOAT
2. float
3. Float
4. Floating
Answer

Float

(V) .............. class is used to convert a primitive data type to its


corresponding object.
1. String
2. Wrapper
3. System
4. Math
Answer

Wrapper
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

(VI) Give the output of the following code:


System.out.println("Good".concat("Day"));
1. GoodDay
2. Good Day
3. Goodday
4. goodDay
Answer
GoodDay

(VII) A single dimensional array contains N elements. What will be


the last subscript?
1. N
2. N - 1
3. N - 2
4. N + 1
Answer
N-1

(VIII) The access modifier that gives least accessibility is:


1. private
2. public
3. protected
4. package
Answer
private

(IX) Give the output of the following code :


String A = "56.0", B = "94.0";
double C = Double.parseDouble(A);
double D = Double.parseDouble(B);
System.out.println((C+D));
1. 100
2. 150.0
3. 100.0
4. 150
Answer
150.0

(X) What will be the output of the following code?


System.out.println("Lucknow".substring(0,4));
1. Lucknow
2. Luckn
3. Luck
4. luck
Answer
Luck
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

SECTION B

Question 2
Define a class to perform binary search on a list of integers
given below, to search for an element input by the user, if it is
found display the element along with its position, otherwise
display the message "Search element not found".
2, 5, 7, 10, 15, 20, 29, 30, 46, 50

import java.util.Scanner;

public class BinarySearch


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

Scanner in = new Scanner(System.in);


int arr[] = {2, 5, 7, 10, 15, 20, 29, 30, 46, 50};

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


int n = in.nextInt();

int l = 0, h = arr.length - 1, index = -1;


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

if (index == -1) {
System.out.println("Search element not found");
}
else {
System.out.println(n + " found at position " + index);
}
}
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

Question 3
Define a class to declare a character array of size ten. Accept the
characters into the array and display the characters with highest and
lowest ASCII (American Standard Code for Information Interchange)
value. EXAMPLE :
INPUT:
'R', 'z', 'q', 'A', 'N', 'p', 'm', 'U', 'Q', 'F'
OUTPUT :
Character with highest ASCII value = z
Character with lowest ASCII value = A

import java.util.Scanner;

public class ASCIIVal


{

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
char ch[] = new char[10];
int len = ch.length;

System.out.println("Enter 10 characters:");
for (int i = 0; i < len; i++)
{
ch[i] = in.nextLine().charAt(0);
}

char h = ch[0];
char l = ch[0];

for (int i = 1; i < len; i++)


{
if (ch[i] > h)
{
h = ch[i];
}

if (ch[i] < l)
{
l = ch[i];
}
}

System.out.println("Character with highest ASCII value: " + h);


System.out.println("Character with lowest ASCII value: " + l);
}

}
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

Question 4
Define a class to declare an array of size twenty of double
datatype, accept the elements into the array and perform
the following :
Calculate and print the product of all the elements.
Print the square of each element of the array.

import java.util.Scanner;

public class SDADouble


{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double arr[] = new double[20];
int l = arr.length;
double p = 1.0;

System.out.println("Enter 20 numbers:");
for (int i = 0; i < l; i++)
{
arr[i] = in.nextDouble();
}

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


{
p *= arr[i];
}
System.out.println("Product = " + p);

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


for (int i = 0; i < l; i++)
{
double sq = Math.pow(arr[i], 2);
System.out.println(sq + " ");
}
}
}
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

Question 5
Define a class to accept a string, and print the characters with the
uppercase and lowercase reversed, but all the other characters
should remain the same as before.
EXAMPLE:
INPUT : WelCoMe_2022
OUTPUT : wELcOmE_2022

import java.util.Scanner;

public class ChangeCase


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a string:");
String str = in.nextLine();
int len = str.length();
String rev = "";

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


{
char ch = str.charAt(i);
if (Character.isLetter(ch))
{
if(Character.isUpperCase(ch))
{
rev += Character.toLowerCase(ch);
}
else
{
rev += Character.toUpperCase(ch);
}
}
else
{
rev += ch;
}
}

System.out.println(rev);

}
}
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

Question 6
Define a class to declare an array to accept and store ten words.
Display only those words which begin with the letter 'A' or 'a' and
also end with the letter 'A' or 'a'.
EXAMPLE :
Input : Hari, Anita, Akash, Amrita, Alina, Devi Rishab, John, Farha,
AMITHA
Output: Anita
Amrita
Alina
AMITHA

import java.util.Scanner;

public class KboatWords


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String names[] = new String[10];
int l = names.length;
System.out.println("Enter 10 names : ");

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


{
names[i] = in.nextLine();
}

System.out.println("Names that begin and end with letter A are:");

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


{
String str = names[i];
int len = str.length();
char begin = Character.toUpperCase(str.charAt(0));
char end = Character.toUpperCase(str.charAt(len - 1));
if (begin == 'A' && end == 'A') {
System.out.println(str);
}
}
}
}
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

Question 7
Define a class to accept two strings of same length and form a
new word in such a way that, the first character of the first
word is followed by the first character of the second word and
so on.
Example :
Input string 1 – BALL
Input string 2 – WORD
OUTPUT : BWAOLRLD

import java.util.Scanner;

public class KboatStringMerge


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter String 1: ");
String s1 = in.nextLine();
System.out.println("Enter String 2: ");
String s2 = in.nextLine();
String str = "";
int len = s1.length();

if(s2.length() == len)
{
for (int i = 0; i < len; i++)
{
char ch1 = s1.charAt(i);
char ch2 = s2.charAt(i);
str = str + ch1 + ch2;
}
System.out.println(str);
}
else
{
System.out.println("Strings should be of same length");
}
}
}
SAVIOUR OF COMPUTERS

2022 COMPUTER
APPLICATION PAPER

Question 7
Define a class to accept two strings of same length and form a
new word in such a way that, the first character of the first
word is followed by the first character of the second word and
so on.
Example :
Input string 1 – BALL
Input string 2 – WORD
OUTPUT : BWAOLRLD

import java.util.Scanner;

public class KboatStringMerge


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter String 1: ");
String s1 = in.nextLine();
System.out.println("Enter String 2: ");
String s2 = in.nextLine();
String str = "";
int len = s1.length();

if(s2.length() == len)
{
for (int i = 0; i < len; i++)
{
char ch1 = s1.charAt(i);
char ch2 = s2.charAt(i);
str = str + ch1 + ch2;
}
System.out.println(str);
}
else
{
System.out.println("Strings should be of same length");
}
}
}
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

SECTION A

Question 1
(I) A mechanism where one class acquires the properties of another
class:
1. Polymorphism
2. Inheritance
3. Encapsulation
4. Abstraction
Answer
Inheritance

(ii) Identify the type of operator &&:


1. ternary
2. unary
3. logical
4. relational
Answer
logical

(iii) The Scanner class method used to accept words with space:
1. next()
2. nextLine()
3. Next()
4. nextString()
Answer
nextLine()

(Iv) The keyword used to call package in the program:


1. extends
2. export
3. import
4. package
Answer
import

(V) What value will Math.sqrt(Math.ceil(15.3)) return?


1. 16.0
2. 16
3. 4.0
4. 5.0
Answer
4.0
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

(Vi) The absence of which statement leads to fall through situation in


switch case statement?
1. continue
2. break
3. return
4. System.exit(0)
Answer
break

(vii) State the type of loop in the given program segment:


for (int i = 5; i != 0; i -= 2)
System.out.println(i);
1. finite
2. infinite
3. null
4. fixed
Answer
infinite

(Viii) Write a method prototype name check() which takes an integer


argument and returns a char:
1. char check()
2. void check (int x)
3. check (int x)
4. char check (int x)
Answer
char check (int x)

(Ix) The number of values that a method can return is:


1. 1
2. 2
3. 3
4. 4
Answer
1

(X) Predict the output of the following code snippet:


String P = "20", Q ="22";
int a = Integer.parseInt(P);
int b = Integer.valueOf(Q);
System.out.println(a + " " + b);
1. 20
2. 20 22
3. 2220
4. 22
Answer
20 22
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

(XI) The String class method to join two strings is:


1. concat(String)
2. <string>.joint(string)
3. concat(char)
4. Concat()
Answer
concat(String)

(XII) The output of the function "COMPOSITION".substring(3, 6):


1. POSI
2. POS
3. MPO
4. MPOS
Answer
POS

(XIII) int x = (int)32.8; is an example of ............... typecasting.


1. implicit
2. automatic
3. explicit
4. coercion
Answer
explicit

(XIV) The code obtained after compilation is known as:


1. source code
2. object code
3. machine code
4. java byte code
Answer
java byte code

(XV) Missing a semicolon in a statement is what type of error?


1. Logical
2. Syntax
3. Runtime
4. No error
Answer
Syntax
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

(XVI) Consider the following program segment and select the output
of the same when n = 10 :
switch(n)
{
case 10 : System.out.println(n*2);
case 4 : System.out.println(n*4); break;
default : System.out.println(n);
}
1. 20
40
2.10
4
3.20,40
4. 10, 10
Answer
20
40

(XVII) A method which does not modify the value of variables is


termed as:
1. Impure method
2. Pure method
3. Primitive method
4. User defined method
Answer
Pure method

(XVIII) When an object of a Wrapper class is converted to its


corresponding primitive data type, it is called as ............... .
1. Boxing
2. Explicit type conversion
3. Unboxing
4. Implicit type conversion
Answer
Unboxing

(XIX)The number of bits occupied by the value ‘a’ are:


1. 1 bit
2. 2 bits
3. 4 bits
4. 16 bits
Answer
16 bits
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

(XX) Method which is a part of a class rather than an instance of the class is termed as:
1. Static method
2. Non static method
3. Wrapper class
4. String method
Answer
Static method

Question 2

(I) Write the Java expression for (a + b)^X


Answer
Math.pow(a + b, x)

(II) Evaluate the expression when the value of x = 4:


x *= --x + x++ + x
Answer
The given expression is evaluated as follows:
x *= --x + x++ + x (x = 4)
x *= 3 + x++ + x (x = 3)
x *= 3 + 3 + x (x = 4)
x *= 3 + 3 + 4 (x = 4)
x *= 10 (x = 4)
x = x * 10 (x = 4)
x = 4 * 10
x = 40

(III) Convert the following do…while loop to for loop:


int x = 10;
do
{
x––;
System.out.print(x);
}while (x>=1);
Answer
for(int x = 9; x >= 0; x--)
{
System.out.print(x);
}
Convert the following do…while loop to for loop:
int x = 10;
do
{
x––;
System.out.print(x);
}while (x>=1);
Answer
for(int x = 9; x >= 0; x--)
{
System.out.print(x);
}
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

(IV) Give the output of the following Character class methods:


(a) Character.toUpperCase ('a')
(b) Character.isLetterOrDigit('#')
Answer
(a) Character.toUpperCase ('a')
Output
A

(b) Character.isLetterOrDigit('#')
Output
false

(V) Rewrite the following code using the if-else statement:


int m = 400;
double ch = (m>300) ? (m / 10.0) * 2 : (m / 20.0) - 2;
Answer
int m = 400;
double ch = 0.0;
if(m > 300)
ch = (m / 10.0) * 2;
elsech = (m / 20.0) - 2;

(VI) Give the output of the following program segment:


int n = 4279; int d;
while(n > 0)
{ d = n % 10;
System.out.println(d);
n = n / 100;
}
Answer
Output
9
2

(VII) Give the output of the following String class methods:


(a) "COMMENCEMENT".lastIndexOf('M')
(b) "devote".compareTo("DEVOTE")
Answer
(a) "COMMENCEMENT".lastIndexOf('M')
Output
8

(VIII) Consider the given array and answer the questions given below:
int x[ ] = {4, 7, 9, 66, 72, 0, 16};
(a) What is the length of the array?
(b) What is the value in x[4]?
Answer
(a) 7
(b) 72
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

(IX) Name the following:


(a) What is an instance of the class called?
(b) The method which has same name as that of the class name.
Answer
(a) Object.
(b) Constructor.

(X) Write the value of n after execution:


char ch ='d';
int n = ch + 5;
Answer
The value of n is 105.

SECTION B

Question 3
Design a class with the following specifications:
Class name: Student
Member variables:
name — name of student
age — age of student
mks — marks obtained
stream — stream allocated

(Declare the variables using appropriate data types)

Member methods:
void accept() — Accept name, age and marks using methods of Scanner
class.
void allocation() — Allocate the stream as per following criteria:

mks. Stream
>= 300. Science and Computer
>= 200 and < 300. Commerce and Computer
>= 75 and < 200. Arts and Animation
< 75. Try Again

void print() – Display student name, age, mks and stream allocated.
Call all the above methods in main method using an object.
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

import java.util.Scanner;

public class Student


{
private String name;
private int age;
private double mks;
private String stream;

public void accept()


{
Scanner in = new Scanner(System.in);
System.out.print("Enter student name: ");
name = in.nextLine();
System.out.print("Enter age: ");
age = in.nextInt();
System.out.print("Enter marks: ");
mks = in.nextDouble();
}

public void allocation()


{
if (mks < 75)
stream = "Try again";
else if (mks < 200)
stream = "Arts and Animation";
else if (mks < 300)
stream = "Commerce and Computer";
elsestream = "Science and Computer";
}

public void print()


{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Marks: " + mks);
System.out.println("Stream allocated: " + stream);
}

public static void main(String args[]) {


Student obj = new Student();
obj.accept();
obj.allocation();
obj.print();
}
}
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

Question 4
Define a class to accept 10 characters from a user. Using bubble
sort technique arrange them in ascending order. Display the
sorted array and original array.
Answer

import java.util.Scanner;

public class CharBubbleSort


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
char ch[] = new char[10];
System.out.println("Enter 10 characters:");
for (int i = 0; i < ch.length; i++) {
ch[i] = in.nextLine().charAt(0);
}

System.out.println("Original Array");
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i] + " ");
}

//Bubble Sortfor (int i = 0; i < ch.length - 1; i++) {


for (int j = 0; j < ch.length - 1 - i; j++) {
if (ch[j] > (ch[j + 1])) {
char t = ch[j];
ch[j] = ch[j + 1];
ch[j + 1] = t;
}
}
}

System.out.println("\nSorted Array");
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i] + " ");
}
}
}
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

Question 5
Define a class to overload the function print as follows:
void print() - to print the following format
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
void print(int n) - To check whether the number is a lead number.
A lead number is the one whose sum of even digits are equal to
sum of odd digits.
e.g. 3669
odd digits sum = 3 + 9 = 12
even digits sum = 6 + 6 = 12
3669 is a lead number.
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

import java.util.Scanner;

public class MethodOverload


{
public void print()
{
for(int i = 1; i <= 5; i++)
{
for(int j = 1; j <= 4; j++)
{
System.out.print(i + " ");
}
System.out.println();
}
}

public void print(int n)


{
int d = 0;
int evenSum = 0;
int oddSum = 0;
while( n != 0)
{
d = n % 10;
if (d % 2 == 0)
evenSum += d;
elseoddSum += d;
n = n / 10;
}

if(evenSum == oddSum)
System.out.println("Lead number");
elseSystem.out.println("Not a lead number");
}

public static void main(String args[])


{
KboatMethodOverload obj = new KboatMethodOverload();
Scanner in = new Scanner(System.in);

System.out.println("Pattern: ");
obj.print();

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


int num = in.nextInt();
obj.print(num);
}
}
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

Question 6
Define a class to accept a String and print the number of digits,
alphabets and special characters in the string.
Example:
S = "KAPILDEV@83"
Output:
Number of digits – 2
Number of Alphabets – 8
Number of Special characters – 1
import java.util.Scanner;
Answer

public class tCount


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

int len = str.length();

int ac = 0;
int sc = 0;
int dc = 0;
char ch;

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


ch = str.charAt(i);
if (Character.isLetter(ch))
ac++;
else if (Character.isDigit(ch))
dc++;
else if (!Character.isWhitespace(ch))
sc++;
}

System.out.println("No. of Digits = " + dc);


System.out.println("No. of Alphabets = " + ac);
System.out.println("No. of Special Characters = " + sc);

}
}
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

Question 7
Define a class to accept values into an array of double data type of size 20.
Accept a double value from user and search in the array using linear search
method. If value is found display message "Found" with its position where it
is present in the array. Otherwise display message "not found".
Answer

import java.util.Scanner;

public class LinearSearch


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

double arr[] = new double[20];


int l = arr.length;
int i = 0;

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


for (i = 0; i < l; i++)
{
arr[i] = in.nextDouble();
}

System.out.print("Enter the number to search: ");


double n = in.nextDouble();

for (i = 0; i < l; i++)


{
if (arr[i] == n)
{
break;
}
}

if (i == l)
{
System.out.println("Not found");
}
else
{
System.out.println(n + " found at index " + i);
}
}
}
SAVIOUR OF COMPUTERS

2023 COMPUTER
APPLICATION PAPER

Question 8
Define a class to accept values in integer array of size 10. Find sum
of one digit number and sum of two digit numbers entered.
Display them separately.
Example:
Input: a[ ] = {2, 12, 4, 9, 18, 25, 3, 32, 20, 1}
Output:
Sum of one digit numbers : 2 + 4 + 9 + 3 + 1 = 19
Sum of two digit numbers : 12 + 18 + 25 + 32 + 20 = 107
Answer

import java.util.Scanner;

public class DigitSum


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int oneSum = 0, twoSum = 0, d = 0;
int arr[] = new int[10];
System.out.println("Enter 10 numbers");
int l = arr.length;

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


{
arr[i] = in.nextInt();
}

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


{
if(arr[i] >= 0 && arr[i] < 10 )
oneSum += arr[i];
else if(arr[i] >= 10 && arr[i] < 100 )
twoSum += arr[i];
}

System.out.println("Sum of 1 digit numbers = "+ oneSum);


System.out.println("Sum of 2 digit numbers = "+ twoSum);

}
}
SAVIOUR OF
COMPUTERS

PROGRAMMING
NOTES
CHAPTER

CLASS 9TH
REVISION

OBJECT CREATING A CLASS DATA TYPES


The means to recognize or identify
By creating a class we create a memory location in an entity/entities and their operations
Computer's memory. are known as data types.
For eg: To store different types of
class CIE values/data we use different data
types.
CIE Integer Data: There are 4 data
CIE types for storing integer data,
they are arranged in ascending
Class order of their range: byte - short -
int - long
Real Data: There are 2 data types
for storing real data, they are
arranged in ascending order of
their range: float - double
Computer's memory
Character Data: We use char
VARIABLES data type to store characters i.e.
data enclosed in single inverted
Now, inside a class, we need memory allocations for commas(' ').
variables to store data. String Data: We use String data
Syntax to create a variable: type to store characters i.e. data
data_type variable_name=constant/value enclosed in double inverted
For eg: commas(" ").
String var="cons"; Boolean Data: We use boolean
data type to store boolean data
var cons i.e. true and false.

Variable
[String]
CHAPTER

CLASS 9TH
REVISION

HOW TO PRINT ?
OBJECT
IMPLICIT TYPE
System.out.print() : This statement prints the sentence CONVERSION
and keeps the controller in the same line.
System.out.println() : This statement prints the
sentence and brings the controller in the next line. byte char short int long float double

Syntax : It's just like the reactivity series of


System.out.print("I'm Pranay Mishra: "); chemistry, here the lower data types
System.out.println("Founder of Clarify Knowledge"); are more powerful, they will change
System.out.print("Welcome to Code Is Easy"); the above ones into their data type.

Output : char + int = int


I'm Pranay Mishra: Founder of Clarify Knowledge int + long =long
Welcome to Code Is Easy. int + double = double

ESCAPE SEQUENCE CHARACTER EXPLICIT TYPE


CONVERSION
Now, inside a class, we need memory allocations for It is forced coversion of data types
variables to store data. and is also known as Type Casting.
Syntax to create a variable:
data_type variable_name=constant/value For eg:
For eg: int a,float b,char c;
String var="cons"; d= (char)(a+b*c);
\n - New Line char ch='A';
\t - One tab space System.out.print((int)ch);
\' - Prints single inverted commas(') in output = 65
\" - Prints double inverted commas(") in output
\\ - Prints backslash (\) in output
Enter key is also known as Carriage-return key.
One tab space means 5 spaces(cursor shifts 5
spaces).

TYPE CONVERSION

If we want to use a data in real data type variable that is


in integer type then we need to change its data type
and this process is known as type conversion.
CHAPTER

CLASS 9TH
REVISION

INPUT USING INITIALIZATION


OBJECT

The process of assigning data or actual values to a declared variable is known as initialization.

This process is basically not taking input from the user but assigning the values in the variables
during writing the code.

INPUT USING SCANNER

The class that allows to input or read primitive data types(int,short,float,etc.) and strings is known
as Scanner Class.

Syntax :- Scanner variable_name = new Scanner(System.in)


-> Scanner sc = new Scanner(System.in);
-> Scanner ob = new Scanner(System.in);
-> Here ob and sc are the variable names.

INCREMENT(++) AND DECREMENT(--) OPERATORS

The increment operator increases the value by 1 and the decrement operator decreases the value by 1.
Prefix Notation
The presence of an increment or decrement operator before the operand or variable is known as prefix
notation. For eg: ++A or --A
It first changes the value then uses it. (change-then-use rule)
Postfix Notation
The presence of an increment or decrement operator after the operand or variable is known as postfix
notation. For eg: A++ or A--
It first uses the original value then changes it. (use-then-change rule)

LET’S MAKE A CALCULATOR

Step 1: Step 2:
CREATE A CLASS CREATE A SCANNER OBJECT
CHAPTER

CLASS 9TH
REVISION

Step 3:
CREATE A SCANNER OBJECT

Step 4:
ASK FOR USER'S CHOICE

Step 5:
ASK FOR NUMBERS

Step 6:
CREATE CONDITIONS FOR PROPER WORKING

Step 7:
JUST PRINT THE RESULT NOW
CHAPTER

CLASS 9TH
REVISION

MATHS CLASS TABLE

Functions Purpose Syntax Examples

Returns absolute value of a


Math.abs(-73)
abs() numeric data by ignoring the Math.abs(argument)
-> 73
sign

Returns the square root of a Math.sqrt(81)


sqrt() Math.sqrt(argument)
positive number -> 9.0

Used to find the power of a Math.pow(5,3)


pow() Math.pow(arg,power)
numeric data -> 125.0

It rounds of the number to Math.round(1.5) -> 2


round() Math.round(arg)
closest integer value Math.round(3.2) -> 3

Returns truncated value of an


Math.rint(30.35) ->
argument by rounding it off to
rint() Math.rint(argument) 30.0
greater number if iit is 0.5 or
Math.rint(5.5) -> 6.0
more.

floor() Returns the lower number Math.floor(argument) Math.floor(1.8) -> 1.0

ceil() Returns the upper value Math.ceil(argument) Math.ceil(1.2) -> 2.0

Returns the largest from two Math.max(36,40.5)


max() Math.max(arg1,arg2)
arguments ->40.5

Returns the smallest from two Math.min(10,17)


min() Math.min(arg1,arg2)
arguments ->10

Math.cbrt(125) ->
Returns the cube root of the 5.0
cbrt() Math.cbrt(argument)
number Math.cbrt(-8) ->
-2.0

Math.random()
Generates a random number
random() Math.random() ->
between 0.0 to 1..0
0.7134361215296077
CHAPTER

CLASS 9TH
REVISION

IF ELSE

SIMPLE IF STATEMENT

The process of assigning data or actual values to a declared variable is known as initialization.
This process is basically not taking input from the user but assigning the values in the variables
during writing the code.

IF ELSE STATEMENT

Syntax:-
if(condition-1)
{
if(condition-2)
{
Statement-2;
}
else()
{
Statement-3;
}
}
else()
{
Statement-3;
}
CHAPTER

CLASS 9TH
REVISION

NESTED IF ELSE

NESTED IF STATEMENT
True
Syntax:- Condition-1 Statement-1
if(condition-1)
{
False
Statement-1
if(condition-2) False
Exit Condition-2
{
Statement-2;
True
}
}
Statement-2

NESTED IF-ELSE() STATEMENT

Syntax:-
if(condition or relational statements)
{
if-code;
}
else(conditional or relational statements)
{
else-code;
}
CHAPTER

CLASS 9TH
REVISION

LOOPS

For Loop :
The loop that executes one or more statements upto a finite limit is known as for ( ) loop.
SYNTAX :
for ( Initial-Value ; Test Condition ; Update-statement )
{
Statement-blocks;
}

While Loop :
The loop that executes one or more statements till the condition is TRUE
and terminates the iteration when the condition is FALSE .

SYNTAX :
while ( expression or condition or relational expression)
{
Statements-block
}

Do - While Loop :
The loop that executes one or more statements till the condition is TRUE and terminates the
iteration when the condition is FALSE, is known as do-while( ) loop.

SYNTAX :
do
{
Statement-block
}
while( condition or relational expression);
CHAPTER

CLASS 9TH
REVISION

LOOPS

For Loop :
The loop that executes one or more statements upto a finite limit is known as for ( ) loop.
SYNTAX :
for ( Initial-Value ; Test Condition ; Update-statement )
{
Statement-blocks;
}

While Loop :
The loop that executes one or more statements till the condition is TRUE
and terminates the iteration when the condition is FALSE .

SYNTAX :
while ( expression or condition or relational expression)
{
Statements-block
}

Do - While Loop :
The loop that executes one or more statements till the condition is TRUE and terminates the
iteration when the condition is FALSE, is known as do-while( ) loop.

SYNTAX :
do
{
Statement-block
}
while( condition or relational expression);
CHAPTER

FUNCTION
AND CONSTRUCTOR

FUNCTIONS

A method is a named piece of code within a program and executes when it is called from another
section of code. In JAVA, the methods can exists only inside class.

class abc
{
void main ()
{
}
}

There are three reasons why we should use methods :


(i) They provide us a way to invoke the same operation from many places in a program, avoiding
code repetition. (Reusing the code)
(ii) They hide implementation details from the component using methods. (Abstraction)
(iii) They help us manage complex and bigger programs into smaller manageable and
understandable sub-parts . (Modularity)

Note - : While naming a method, just make sure that it should be a legal identifier and should be
meaningful.

Method prototype and signature


The first line of the method definition is the prototype of the method .
A method prototype describes the method interface to the compiler by giving details such as
the numer and type of agruments and types of return values.

METHOD TYPES
ACCESSING A
METHOD/FUNCTION
JAVA METHODS
A method is called or invoked by
providing the method name,
followed by parameters being
STATIC NON STATIC sent enclosed in paranthesis.
They are created The are created by
float area (float a, float b)
by keyword static absence of area (x,y);
in their prototype. keyword static in
their prototype.
CHAPTER

FUNCTION
AND CONSTRUCTOR

FUNCTIONS

Invoking static and non static methods

Static Non Static

They are called class They are called instance


methods and are invoked methods and are invoked
using class name. using objects.
<ClassName>. <ObjectName>.<non-
<staticMethodName>() staticMethodName>()

SCOPE OF VARIABLE

Instance Any method in class definition can assess these variables.


Parameter only the method where parameters appear can access these.
Local Only the bloc where the variable is declared, can access these.

CONSTRUCTOR

A constructor is a special member method of a class without a return type. It is used for
initialising and constructing the data members of an object when it is created. It is
automatically called (invoked) when the object is created using new operator. It cannot be
invoked by the user like normal methods.

Characteristics
A constructor will have the same name as that of the class.
A constructor does not have a return type not even void.
A constructor cannot be static or final.
A constructor must be declared public (if it has to be accessed outside the class).
It is automatically called (invoked) when an object is created.
CHAPTER

FUNCTION
AND CONSTRUCTOR

NEED OF A CONSTRUCTOR

A constructor is used for initialising and constructing the data members of an object with legal
values when it is created. Data members are mostly declared as private members, to
implement data hiding and abstraction. Due to this, data members cannot be initialised
outside the class with values. So, constructors are used for initialising the objects implicitly as
they are created.

Declaring and defining -:


Being a method, it also gives the programmer the ability to define, declare and modify. Since, a
constructor has no return type (not even void), it also provides the programmer with the liberty to
define a constructor with or without a parameter.
A simple constructor is created using the new operator followed by the name of the class.
Syntax:
<access specifier> class_name (parameter list/void)
{
Data_member1 = value1 ;
Data_member2 = value2;
}

Example :
class Book
{ int bookno;
String name;
float price;
public Book() //constructor is created, having same name Book as
{ bookno = 0; that of its class name Book, with public access specifier
name = "ABC"; and no return type.

TYPES OF CONSTRUCTORS
The main function of a constructor is to initialise the data members of an object while it is created.
Constructors can be broadly categorised into two categories based on the parameters it takes:

Default constructor : A constructor that takes no parameters.


Parameterised constructor : A constructor that takes one or more parameters.
CHAPTER

FUNCTION
AND CONSTRUCTOR

MORE ABOUT CONSTRUCTOR

Default Constructor/Non Parameterised Constructor


A constructor that takes no parameters is called a default constructor. It will have the name of the
class and have no return type. If you do not write a constructor in your program, the compiler will
supply a default constructor and initialise values with the default values of the primitive data types i.e.
integer variables to zero, floating point variables to 0.0 and String to null.
Syntax:
class_name()
{
Data_member1 = value1;
Data_member2 = value2;
}

Parameterised Constructor
Constructor that takes one or more parameters or arguments is called as a parameterised
constructor. Such a constructor will accept values and initialise the data members with the
corresponding values. There is no limitation to number of parameters.

Syntax:
class_name (type1 val 1, type2 val 2...)// parameter list
{
Data_member1 = val 1;
Data_member2 = val 2;
}

Declaring and defining -:


Being a method, it also gives the programmer the ability to define, declare and modify. Since, a
constructor has no return type (not even void), it also provides the programmer with the liberty to
define a constructor with or without a parameter.
A simple constructor is created using the new operator followed by the name of the class.
Syntax:
<access specifier> class_name (parameter list/void)
{
Data_member1 = value1 ;
Data_member2 = value2;
}
CHAPTER

FUNCTION
AND CONSTRUCTOR

MORE ABOUT CONSTRUCTOR

'This' keyword
'This' keyword is used within a constructor to refer to the current object. It is actually a reference to
the object that invokes the constructor. In fact, even if you do not use the this keyword, the compiler
normally implicitly converts it by prefixing this to the data members.

CONSTRUCTOR MEMBER METHODS

name: always similar to class name: according to user


name return type: void or valid
return type: no return type need: to avoid repetition and to
need: to initilalise member increase code reusability.
variables

Constructors within Constructors using 'this''


Constructors can be chained together by invoking a constructor from within another constructor. The
this keyword is used to invoke another constructor from within the class. When constructors are
chained this way, the control just moves from one constructor to the other till the data members are
initialised and the object is fully constructed.
CHAPTER

DOUBLE
DIMENSIONAL ARRAY

[ ]
SINGLE
OBJECTDIMENSION AL ARRAY:
00 0 1 201 02
It has a single subscript subscript
int ar[]=new int[3]; of array 10 3 4 511 12

DOUBLE
OBJECT DIMENSION AL ARRAY: 20
6 7 821 22

It has double subscript


int ar[][]=new int[3][3];

Row column

[ ] [ ]
00

10

20
0 1 2
01

3 4 5
11

6 7 8
21
02

12

22
00

10

20
0 1 2
01

3 4 5
11

6 7 8
21
02

12

22

logic To enter elements/digits in the matrix


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
Outer loop {
ar[i][j]=in.nextInt();
} inner loop
}
CHAPTER

DOUBLE
DIMENSIONAL ARRAY

logic To print the matrix


for(int i=0;i<3;i++)
{
it prints the row for(int j=0;j<3;j++)
and as the loop {
terminates,
System.out.print(ar[i][j] + “ “);
it starts }
printing the next
row in the next System.out.println();
line }
and the process repeats until the outer loop is terminated

[ ] [ ]
LEFT DIAGONAL RIGHT DIAGNOAL

00 0 1 2
01 02 00 0 1 2
01 02

10 3 4 5
11 12 10 3 4 5
11 12

20
6 7 8
21 22 20
6 7 8
21 22

when i==j when i+j==2


left diagonal elements are found right diagonal elements are found

logic To print the diagonals

You might also like