0% found this document useful (0 votes)
18 views52 pages

CTA Notes

The document outlines the differences between procedure-oriented and object-oriented programming languages, emphasizing the advantages of object-oriented principles such as abstraction, inheritance, polymorphism, and encapsulation. It also provides an overview of Java as an object-oriented language, detailing its features, types of programs, and fundamental concepts such as classes, objects, and data types. Additionally, it covers operators, type conversion, and the character set used in Java.

Uploaded by

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

CTA Notes

The document outlines the differences between procedure-oriented and object-oriented programming languages, emphasizing the advantages of object-oriented principles such as abstraction, inheritance, polymorphism, and encapsulation. It also provides an overview of Java as an object-oriented language, detailing its features, types of programs, and fundamental concepts such as classes, objects, and data types. Additionally, it covers operators, type conversion, and the character set used in Java.

Uploaded by

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

Theory

Revision of IX Syllabus [italicised sections are not too important]


Difference between Procedure-oriented and Object-oriented
languages.
Procedure-oriented Object-oriented

The code written in these languages is The entire program is arranged in such
organized sequentially in a series of a manner that it is composed of
steps, which are grouped together in independently partitioned segments of
functions or procedures. memory, called objects.

The emphasis is laid down on the The emphasis is laid down on the data
functions or procedures rather than values rather than functions.
the data values.

The data items are globally accessible The data items associated with a given
by all the functions in the code, from object is only accessible within the
all locations. scope of the object – this ensures data
security.

Their sequential nature and its lack of Their modularity, data security,
data authenticity and security makes message-passing ability, etc. makes
them unsuitable for solving real-world them highly beneficial for solving
problems. complex real-world problems.

Debugging is difficult as there is no Debugging is easier as the objects


categorisation of data items and no wrap the related data items and
clear association of data with functions into a single unit.
procedures.

Principles of OOP.
- Abstraction / Data Hiding: The act of representing the essential features of a
system without knowing the detailed background information, such that the
representation is reasonable for and related to the current problem of its user,
is called Abstraction. Real life examples:
• Someone using a digital camera used to capture a photograph only needs to
know the usage of the shutter, lens, and other related settings, but not the
internal mechanics of its implementation.
• A driver driving a car only needs to know the usage of the steering wheel,
accelerator, breaks, clutch and other related functions, but not the
implementation of these functions or the physical principles on which these
are based on.
- Inheritance: The mechanism of deriving a new class from another class by
linking and sharing some common properties of the old class with the new
class, in a way that promotes the reusability of existing code and efficiency of
memory and time, is called Inheritance.
• The class from which the properties are derived is called the base class,
parent class or the super class. The new class which is created after inheriting
from the base class is called the sub-class or derived class. • Real life
examples:
o Even if the off-springs of a family line may seem completely different
every generation, or even among the same generation, all of them
‘inherit’ the common characteristics of the species. For example, the
cubs of a tiger may have different appearances, but all of them share
the common characters of a tiger.
o All attributes of tigers, lions, leopards, etc. may seem completely
different but one thing which brings them together is their
nutritional preference – all are carnivores. Thus, they ‘inherit’ the
characteristics of carnivores.
- Polymorphism (‘many forms’): The mechanism of using a single function for
performing multiple operations depending on the inputs is called
Polymorphism.
• In software, polymorphism is implemented via function overloading – the
technique of using a single function with different sets of arguments. • Real life
examples:
o The term ‘cell’ can mean many things depending upon the context. In
electronics, it refers to a source of electric current. In biology, it
refers to the structural and functional unit of the body. In general, it
may also refer to a compartment in a prison, examination cell or an
administrative cell.
o The word ‘duck’ can refer to the aquatic bird with broad feet and
webbed feet, as well as a term used for a batsman in a cricket innings
who got Out with 0 runs scored.
- Encapsulation: The mechanism of wrapping the data inputs and functions into
a single, independent, isolated unit is called Encapsulation.
• Encapsulation is a powerful principle that enforces data authenticity and
security in a program. It ensures that the data associated with one object is
not accessible directly outside the scope of the object – this in contrast to
procedure-oriented languages.
• The functions associated with objects provide a serialized interface to
communicate or share data between data items of different objects and
between the driver code and the objects.
• Message Passing: The mechanism by which an object sends data to another
object or asks the other object to invoke a function to perform some
operation outside the scope of the caller is called Message Passing. The
functions defined in an object provide an interface to perform message
passing.

Features of Java.
- It is an object-oriented programming language.
- It is both a compiled as well as an interpreted language.
- It can access data locally as well as from the network.
- It is case-sensitive, i.e., it treats uppercase and lowercase alphabets as distinct
entities.
- It is a simple, robust and secure language.
Java as both a compiled and interpreted language.
Normally, a high-level language employs either a compiler or an interpreter to
convert the human-readable code to machine-readable binary code. Java is special in
that it uses both of these translators and in different ways.
- The Java compiler is a software that translates a program written in Java (the
source code) into an intermediatory binary form called bytecode. The
advantage of this is that the bytecode is platform-independent, i.e., it can be
executed on any machine, irrespective of the CPU architecture, etc., provided
that the machine has the JVM installed.
- The Java interpreter is the final translator that takes the bytecode as an input,
converts it into a form that the specific machine’s CPU can process and
execute, and finally dictates the CPU to execute the resulting object code.
Since the interpreter acts as a separate layer on top of the machine to execute
the platform-independent bytecode, it is also called the Java Virtual Machine
(JVM).

Types of Java programs.


- Standalone applications: Programs developed by the users independently that
are executed ‘standalone’ in a client or a server having the JVM installed are
called standalone applications. These applications have access to all the
resources available to it in the system.
- Applets: An applet is an internet-based program written in Java that can be
embedded in an HTML webpage and be executed from within a web browser.
When a supported browser is used to view a webpage having applets
embedded, the code of the applet is transferred to the viewer’s system to be
run by the browser. Compared to standalone applications, applets have
limited access to resources.

Elementary concepts of objects, classes, states and behaviours.


- Class: The blueprint, template or prototype of an object, from which all the
objects created derive their properties and behaviours, is called a class. - Object:
The fundamental entities of an OOP language that represent a real-life object,
mapping its characteristics or states to data members and behaviours to member
functions, are called objects.
- Data members: The characteristics and states of a real-world object are
represented in an OOP language as properties closely associated to the
software object; these are called the data members of the object.
- Member functions / Methods: The behaviours exhibited by real-world objects
are represented in an OOP language as functions or methods which are tied
closely to a given object, to perform one or more operations; these are called
member functions or methods of the object.
Character set.
The set of all valid characters that a language can recognise and allow a user to use in
writing programs is called a character set. Java uses the Unicode character set, in
which every character is represented in a 2-byte (16-bit) sequence, in the form of
hexadecimal numbers ranging from 0x0000 up to 0xFFFF.
The first 128 characters are identical to the original ASCII character set, which has
128 characters, represented from 0 to 127. The different characters in the ASCII set
are:
- 48-57 represent the numeric digits 0-9.
- 65-90 represent the uppercase alphabets A-Z.
- 97-122 represent the lowercase alphabets a-z.
- 32 represents the whitespace ‘ ’.

Escape sequences. The characters used to control and customise the cursor’s
movement on the console while displaying the values in it are called escape
sequences. The common ones include:
- \t – Horizontal tab (usually equivalent to 8 spaces).
- \\ – A literal backslash.
- \’ – Single quote (used in a character literal which is delimited by ‘).
- \” – Double quote (used in a string literal which is delimited by “). -
\r – Carriage return.
- \n – New line feed.

Tokens. Each valid individual component of a statement such that it carries some
special meaning and takes part in execution of the program is called a token. They are
of the following kinds:
- Literals:
• Integers like 13, 69, -42;
• Real numbers like 0.01;
• Characters like ‘a’, ‘4’, ‘@’;
• Strings like “Hello, world!”
• Booleans like true and false.
• The null literal.
- Identifiers / Variables used to represent a specific reserved location in the
memory, such as int m = 42; // 42 is an integer literal
assigned to a memory location named as `m`.
- Assignment operator `=`.
- Punctuators like `?`, `.` and `;`.
- Separators like `,`, `()`, `[]`, `{}`, etc.
- Operators like arithmetical operators (+, -, *, /, etc.), relational operators
(<, >, ==, !=, etc.) and logical operators (&&, ||, !, etc.).
- Keywords like class, public, throws, switch, etc.
Data types. These refer to the kinds of data that can be stored in the memory for
the purposes of the program. Java is a strictly-typed language, meaning it requires the
developer to clearly specify the type of data a variable must store. They are broadly
divided into two types:
- Primitive data types are those which are available for use by default and which
are independent of other types. These include:
• Numeric types:
Data type Keyword Size Range

Byte byte 8 bits -27to


(1 byte) +(27 – 1)

Short short 16 bits -215 to


(2 bytes) +(215 – 1)

Integer int 32 bits -231 to


(4 bytes) +(231 – 1)

Long integer long 64 bits -263 to


(8 bytes) +(263 – 1)

Single float 32 bits -3.4E38 to


precision (4 bytes) +3.4E38
decimal

Double double 64 bits -1.7E308 to


precision (8 bytes) +1.7E308
decimal

• Non-numeric types:
Data type Keyword Size

Single character literal char 16 bits (2 bytes)

A collection of String Varies according to


multiple characters the size of the String.

- Non-primitive / Composite data types are those which are derived from
multiple types of primitive data, such as classes, interfaces, arrays, etc.

Type conversion. It refers to the conversion of data from one type to another as
a result of a mixed expression.
- Implicit type conversion or Coercion is a process in which the data type of the
result gets automatically converted into the highest data type available in the
expression without any user intervention. It involves no data loss.
byte

char

short

int

long

float

double

- Explicit type conversion or type casting is a process in which the data type gets
converted, forcibly if needed, into any other type depending on the user’s
choice. This may involve some data loss if the conversion is from a higher data
type to a lower data type. E.g.: int aExpB = (int) Math.pow(a, b);
Here, the result of Math.pow(a, b), which is of type double, is casted into
int. This may strip off the decimal digits and hence data is lost.

Operators. A token which performs an arithmetic operation, logically compares


two Boolean expressions or relates two logical expressions is called an operator. The
inputs given to the operators are called operands.
- Arithmetical operators:
• Binary operators (take two inputs):
Operator Mathematical Example
equivalent

+ Addition 3.2 + 4.3 // 7.5

- Subtraction 3.2 - 4.3 // -1.1


* Multiplication 3.2 * 4.3 //
13.76

/ Division 3.2 / 4.3 //


~0.74

% Modulus, i.e. 3.2 % 4.3 // 3.2


remainder left after
integer division

• Unary operators (take a single input):


Operator Function Example

+ Points to the value of float a = 3.2;


the variable +a; // 3.2

- Flips the sign of the int a = 4;


value -a; // -4

++ (postfix) Adds 1 (increments) to int a = 3;


the value AFTER the int b = a++;
expression is // a is 4, b is 3
evaluated.

++ (prefix) Adds 1 (increments) to int a = 3;


the value BEFORE the int b = ++a;
expression is // a is 4, b is 4
evaluated.

-- (postfix) Subtracts 1 int a = 3;


(decrements) to the int b = a--;
value AFTER the // a is 2, b is 3
expression is
evaluated.

-- (prefix) Subtracts 1 int a = 3;


(decrements) to the int b = --a;
value BEFORE the // a is 2, b is 2
expression is
evaluated.

- Relational operators:
Operator Mathematical Example
equivalent

< Less than 3.2 < 4.3 // true

> Greater than 3.2 > 4.3 //


false

<= Less than or equal to 3.2 <= 4.3 //


true

>= Greater than or equal to 3.3 >= 3.3 //


true

== Equal to 4 == 4.00 // true

!= Not equal to 3 != 3 // false

- Logical operators:
Name Symbol Truth table

Logical AND && A B A && B


false
false false false
false true false
true
true false

true true

Logical OR || A B A || B
false
false false true
false true true
true
true false

true true

Logical NOT ! A !A

false true

true false

- Conditional / Ternary operator (?): These operators work on three given


operands. If the given test condition is truthy, the first expression is evaluated,
otherwise, the second.
General form: (<logical/relational expression>) ?
<expression 1> : <expression 2>

Precedence of operators.
Larger number means higher precedence.
Precedence Operator Name Associativity

15 () Parentheses Left to Right


[] Array subscript
· Member selection (e.g.
System.out.println)

14 ++ Unary post-increment Left to Right


-- Unary post-decrement
13 ++ Unary pre-increment Right to left
-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
() Unary type cast

12 * Multiplication Left to right


/ Division
% Modulus

11 + Addition Left to right


- Subtraction

10 << Bitwise left shift Left to right


>> Bitwise right shift with
>>> sign extension
Bitwise right shift with
zero extension

9 < Relational less than Left to right


<= Relational less than or
> equal Relational greater
>= than
instanceof Relational greater than or
equal Type comparison

8 == Relational is equal to Left to right


!= Relational is not equal to

7 & Bitwise AND Left to right

6 ^ Bitwise exclusive OR Left to right

5 | Bitwise inclusive OR Left to right

4 && Logical AND Left to right

3 || Logical OR Left to right

2 ? : Ternary conditional Right to left

1 = Assignment Right to left


+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Inputs in Java.
- Using function arguments:
public void volume (double l, double b, double h) {
System.out.println(“Volume: “ + (l * b * h));
}
- Using Scanner:
import java.util.Scanner;
public class Example {
public static void main (String[] args) {
Scanner key = new Scanner(System.in);
// Inputting integers
int i = key.nextInt();
// Inputting real numbers
float f = key.nextFloat();
double d = key.nextDouble();
// Inputting a word
String w = key.next();
// Inputting a string
String s = key.nextLine();
// Inputting a character
char c = key.next().charAt(0);
}
}
Errors.
- Syntax errors occur when the grammatical rules of a statement in the specific
programming language are not properly adhered to. This does not allow the
code to execute. Example:
int a = 0, b = 3 c = 4;
float p = a * b/c;
This code would not run because there is a comma missing in the first line. -
Logical errors occur when the logic of an algorithm is not properly coded,
producing undesirable results. Example:
int b = 3, h = 4;
double area = 1/2 * b * h;
System.out.println(area);
While this code would execute, the area printed would always be 0 regardless
of the base and the height. This is because 1/2 by default corresponds to
integer division, i.e., division that produces a remainder. 1 divided by 2 is 0
with remainder 2, and 0 multiplied with any number is 0. The error can be
corrected as: double area = 1/2.0 * b * h;
- Runtime errors occur when the compiler encounters an invalid operation
performed by the user during the execution of the program. Example: int a =
3, b = 0;
int c = a / b;
This code throws a java.lang.ArithmeticException because we have
attempted to divide by zero.

Math methods.
between a and b.

Math.max(a, b) Returns the greater


between a and b.

Math.sqrt(a) Returns the square


Method Descr [only positive inpu
allowed].
Math.min(a, b) Retur
Math.cbrt(a) Retur than or equal to a.

Math.pow(a, b) Retur Math.floor(a) Returns an integer


or equal to a.
Math.abs(a) Retur
Math.rint(a) Returns the neares
value to a [Disti
Math.round(a) Retur from round: In ca
up to rint
a.

Math.ceil(a) Retur

rounds the input to the


nearest even integer while
round always rounds it
up].

Math.random() Returns a random number double


between 0 and 1.

Math.log(a) Returns the value of loge(a) double

Math.exp(a); Returns the value of ea. double

Math.[sin(a) / Returns the value of sin(a) double


cos(a) / tan(a)] / cos(a) / tan(a) [the
angle is expressed in
radians].

Conditional statements.
- If statement:
int a = 5;
if (a >= 5)
System.out.println(“yay!”);
// This prints “yay!” because the condition `a >= 5` holds true
for a = 5. If a were 4, “yay!” would not be printed. - If-else
statement:
int a = 5;
if (a > 5)
System.out.println(“yay!”);
else
System.out.println(“nay :(“);
// This prints “nay :(“ because the condition `a > 5` is false
for a = 5.
- If-else-if chains:
int a = 5;
if (a > 5)
System.out.println(“yay!”);
else if (a == 5)
System.out.println(“ok :|”);
else
System.out.println(“nay :(“);
// This prints “ok :|” because only the condition `a==5` is
true for a = 5.
- Nested-if statements:
int a = 8;
if (a >= 5) {
if (a > 10)
System.out.println(“WOO-HOO!”);
else if (a > 5)
System.out.println(“yay!”);
else
System.out.println(“ok :|”);
}
else
System.out.println(“nay :(“);
// This prints “yay!” because the condition `a >= 5` and the
subsequent (a > 5) is true for a = 8.
- Switch-case statements:
int a = 6;
switch (a) {
case 0:
System.out.println(“die :(“);
break;
case 1:
case 2:
case 3: // applies when a = 1, a = 2 or a = 3
System.out.println(“nay :(“);
break;
case 4:
case 5:
case 6:
case 7:
System.out.println(“yay!”);
case 8:
case 9:
case 10:
System.out.println(“WOO-HOO!”);
break;
default: // applies when a isn’t = 0 to 10.
System.out.println(“shrug”);
break;
}
// This prints “yay!”.

Loops.
- For loops are entry-controlled loops, i.e., the condition is checked in the
beginning of every iteration, and are used when the number of iterations are
fixed and known. Example:
for (int i = 1; i <= 5; i++)
System.out.println(“+1! i=” + i);
// Output:
// +1! i = 1
// +1! i = 2
// +1! i = 3
// +1! i = 4
// +1! i = 5
- While loops are also entry-controlled loops, and are used when the number of
iterations is not known beforehand, i.e., in cases when a block of statements is
to be repeated only until a specific condition becomes falsey. Example: int s
= 0;
boolean done = false;
while (!done) {
System.out.println(“Enter a number or ‘stop’ to stop
inputting.”);
String n = key.next();
if (n == “exit”)
done = true;
else
s += Integer.parseInt(n);
}
if (done)
System.out.println(“Rounded sum: “ + Math.round(s)); - Do-while
loops are exit-controlled loops, in which the condition is checked at the exit point
of the loop. The do-while loop works the same way as a while loop, in that it is
also an unfixed loop; however, in while loop, the condition is checked at the entry
point of the loop while in do-while loop, it is done at the end of the loop. This
implies that even if the initial condition is false, the do-while loop will execute the
block of statements at least once. Example:
int p = 1000, r = 10;
double si = 0.0;
do {
si = (p * r) / 100.0;
p = p + si;
} while (p <= 10000);

Jumps in loops.
- The break jump statement transfers the control from within the loop body to
outside the loop. As soon as the control hits the break keyword, it
immediately exits out of the loop and continues with the rest of the program.
- The continue jump statement transfers the control from within the loop body to
the beginning of the loop. As soon as the control hits the continue keyword,
it skips the rest of the loop and starts the next iteration.

Nested for loops.


- Example:
int a, b;
for (a = 1; a <= 5; a++) { // Outer loop
for (b = 1; b <= a; b++) // Inner loop
System.out.print(b);
System.out.println();
}
// Output:
// 1
// 12
// 123
// 1234
// 12345
- break in a nested loop:
• In the outer loop –
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 3; j++)
System.out.println(i * j);
if (i < 2)
break;
System.out.println(“****”);
}
// Output:
// 1
// 2
// 3
// ****
// 2
// 4
// 6
// ****
// 3
// 6
// 9
• In the inner loop –
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 3; j++) {
if (i * j > 8)
break;
System.out.println(i * j); }
}
// Output:
// 1
// 2
// 3
// 2
// 4
// 6
// 3
// 6
// 4
// 8
// 5
- continue in a nested loop:
• In the outer loop –
int i, j;
for (i = 1; i <= 5; i++) {
if (i == 2)
continue;
for (j = 1; j <= 3; j++)
System.out.print(i * j + “ “); }
// Output:
// 1 2 3 3 6 9 4 8 12 5 10 15
• In the inner loop –
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 3; j++) {
if (i * j > 10)
continue;
System.out.print(i * j + “ “); }
}
// Output:
// 1 2 3 2 4 6 3 6 9 4 8 5 10
Class as the Basis of All Computation
Objects encapsulate state and behaviour. Both real-life objects and
software objects incorporate a mechanism by which all the related states, properties,
characteristics and the behaviours are wrapped together in a single, isolated unit, in a
manner that protects the private data items from being accessed by other objects,
unless their behaviour / functions permit the outside objects to do so. This OOP
principle promotes data authenticity and security. Examples:
- The name and roll number of a student belong only to the student himself. No
other student can take upon or modify these properties. However, as per the
general behaviours of students, each of them can address each other by their
names, and yet no stranger can do so – this way, the personal information of
the student and the methods to be able to harness the information remains
encapsulated in a single entity. All these behaviours can be mapped to software
objects by the mechanism of encapsulation and data-hiding.
- The answer booklet of a specific student contains the roll number of the student
and the answers to the questions. No other student is able to access the
contents of the booklet once it is handed back to the examiner. This way, all
the characteristics of the answer booklet is wrapped within the context of the
examination, the examiner and the evaluator themselves – no other outside
entity is able to access them. Similarly, only the assigned evaluator is able to
evaluate the answers in a booklet and no other person is allowed to do so.

Member variables define state. The characteristics and states of a real


world object are always mapped to a software object in the form of its data members.
Example: For a student having the states / characteristics of name, class, roll number
and total marks in the last exam:
Characteristics Member variables

Name: Adolf Genea public String name = “Adolf Genea”;

Class: 10 public int cls = 10;

Roll No.: 47 public int rno = 47;

Total marks: 356.3 public float tmarks = 356.3;

Member methods define behaviour. The behaviour exhibited by a real


world object is always mapped to a software object in the form of its functions /
methods. Example: For a student exhibiting the behaviours of reading, writing and
calculating percentage:
Behaviour Member methods
Reading public void read();

Writing public void write();

Calculate percentage public double calculate();

Class as an abstraction for objects. A class is a prototype for creating


objects possessing the same kinds of data members and member functions. When a
class is created, the data items are merged or grouped together with the belonging
functions, and when an object is instantiated, all the data items and member
functions
described within the class are given a real existence and become accessible to the user
for performing operations. The instantiation of an object is done by the driver code
without it being exposed to the actual implementation details behind its functions.
Thus, a class acts as an abstraction for sets of similar kinds of objects.

Class as an object factory. Factories are work units where industrial-scale


machines are deployed to produce items of similar kinds. A class is of a similar
architecture, in that it can be used to create multiple objects having different states of
the same characteristics, as well as the common functions, described within it. As the
class produces different objects having similar features, it is called an object factory.

Primitive and composite data types.


Composite data-type Primitive data-type

These data types are created by the user These are built-in data types
for the specific purposes of a program, fundamental for the program to
and as such are not available to other store basic types of data.
programs by default.

These are derived from multiple primitive These are independent data types –
data types. they neither depend on nor can be
broken into other entities.

Variable declaration: Variable declaration: <data


<Classname> <variable type> <variable name> =
name> = new <corresponding
<Classname>(); primitive value>;

Class as a composite data type. When a user creates a class, it becomes a


new data type of his choice. He may describe a number of properties inside the class
ranging from different types of primitive data as per the requirements of the problem.
Hence, the class becomes such a data type that uses different primitive types and thus
is a composite data type.

Objects as instances of a class. A class is simply a blueprint of an object,


describing all the properties and methods that the objects may contain. However, it is
not a real entity and it does not consume space in the dynamic memory. Only when
an object is created from a class that all the data members and member functions
described within the class get associated with a real, physical entity that occupies
space in the memory. Since the objects, in a way, realize the classes, they are known
as instances of a class.
User-defined Methods
Need for methods. A method has the following advantages:
- Reusability: The block of code can be reused, as and when necessary, by simply
referring to the method name.
- Modularity: Methods allow dividing a complex computational task or problem
into a collection of smaller, simpler and isolated segments so that the solution
becomes easier, object-specific and modular.
- Efficiency: A program that uses and reuses a method as opposed to writing the
same block of code multiple times occupies less memory space and executes
faster.
- Ease of debugging: A program written using methods can be easily debugged in
case of errors, since errors are now isolated within a specific method or a
group of methods.

Defining a method.
<access specifier> <return type> <method name> (parameter
list>) {
<statement(s)>;
return <value>; // not required if return type is `void` }

Where:
- <access specifier> <return type> <method name> (parameter
list>) is the Header / Method prototype.
• Access specifiers define the scope and accessibility of a function from other
functions, methods or classes. It can be either:
o private – such that only the members of that specific class in
which it is defined can access the method;
o public – such that the method is unprotected, i.e., accessible from
any function inside or outside the defining class;
o protected – such that only all the classes and subclasses within
the package, as well as sub-classes of the defining class inside or
outside the package, can access the method; or
o default, i.e., no access specifier used – such that the method is set
as ‘package-private’, i.e., all the attributes, methods and classes
within the same package only can access the method.
Accessor default private protected public

Same class Yes Yes Yes Yes

Same package - - - -

(a) Subclass Yes No Yes Yes

(b) Non Yes No Yes Yes


subclass

Different - - - -
package

(a) Subclass No No Yes Yes


(b) Non No No No Yes
subclass

• <return type> is a data type keyword before the method name that
indicates the type of outcome of a method to be returned to its caller. In
case a method does not return any value, the return type is void. If a
function is defined with a non-void return type, it must include a
return statement correspondingly.
• <method name> is the name with which the method is identified and called
when necessary.
• (parameter list>) is a comma-separated list of variables along with
their data types, which receive the values passed by the caller during
method call for internal computation. An empty parameter list indicates
that the method does not receive any value from the caller. It has the
general form: (<type1> <var1>, <type2> <var2>, <type3>
<var3>, …).
- {…} is the method block/function body. It contains a set of statements which
are executed when the method is called.
- return <value> (the return statement) is a form of a jump statement that
sends back the result or the outcome of the method to the caller. • It is always
used at the end / exit point of a method.
• No statement in the function body placed after the return statement will be
executed.
{
int s = m + n;
return s;
int p = n – m;
}
Here, the bolded statement will not be executed because the control exits
the function body as soon as it hits the return statement.
• It may only return a single value from a method to the caller. • A function
may have more than one termination points with suitable guard
clauses/conditions.
if (a > b)
return a;
else
return b;
In this case, if the first condition is true, the value of a will be returned;
otherwise, b will be returned. Such a condition which allows multiple
termination points in a method is called a guard clause.
• In case, in a method, multiple return statements are implied to be executed,
only the first one will be executed by the control.
{
int s = 0;
int p = 0;
s = m + n;
p = m – n;
return s;
return p;
}
In this case, only the first return statement is executed, and the bolded
return statement is ignored.
• Once the control returns from a method, it cannot re-enter the method until
the next method call.

Ways of defining a method.


- Parameterized method, in which some variable values are received from the
caller.
• Non-void method –
public int factorial (int n) {
int f = 1, i;
for (i = 1; i <= n; i++)
f *= i;
return f;
}
• void method –
public void factorial (int n) {
int f = 1, i;
for (i = 1; i <= n; i++)
f *= i;
System.out.println (“Factorial of “ + n + “ is “ + f); }
- Non-parameterised method, in which no values are received from the caller. •
Non-void method –
public int factorial () {
int n = 5, f = 1, i;
for (i = 1; i <= n; i++)
f *= i;
return f;
}
• void method –
public void factorial () {
int n = 5, f = 1, i;
for (i = 1; i <= n; i++)
f *= i;
System.out.println (“Factorial of “ + n + “ is “ + f); }

Invoking a method. The process of utilising the code defined in a method in


the program is referred to as calling or invoking a method or function.
- For parameterised methods [refer Ways of defining a method for the
factorial() function]:
• Non-void methods –
public class Factorial {
public int factorial (int n) {…}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter a number: “);
int a = key.nextInt();
Factorial fct = new Factorial(); // Creating an object //
of the class int f = fct.factorial(a); // Calling the
method // `factorial` with the // parameter `a`.
System.out.println(“The factorial of “ + a + “ is “ +f); }
}
• void methods –
public class Factorial {
public int factorial (int n) {…}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter a number: “);
int a = key.nextInt();
Factorial fct = new Factorial(); // Creating an object //
of the class fct.factorial(a); // Calling the method
`factorial` with // the parameter `a`.
}
}
- For non-parameterised methods [refer Ways of defining a method for the
factorial() function]:
• Non-void methods –
public class Factorial {
public int factorial (int n) {…}
public static void main(String[] args) {
Factorial fct = new Factorial(); // Creating an object //
of the class int f = fct.factorial(); // Calling the
method // `factorial`.
System.out.println(“The factorial is “ + f);
}
}
• void methods –
public class Factorial {
public int factorial (int n) {…}
public static void main(String[] args) {
Factorial fct = new Factorial(); // Creating an object //
of the class fct.factorial(); // Calling the method
`factorial`. }
}

Kinds of parameters.
- The parameters defined in the method header which function to receive the
values from its caller are called Formal parameters.
- The values actually passed to the method at the time of calling it are known as
Actual parameters.
- Illustration:
import java.util.Scanner;
public class Summing {
public int add (int m, int n) { // formal parameters
int s = 0;
s = m + n; Value of a is passed to
return s; } the function as m.

public static void main (String[] args) {


Scanner key = new Scanner(System.in);
System.out.println(“Enter two numbers:”);
int a = key.nextInt(); Value of b is passed to the function as
int b = key.nextInt(); n.
Summing obj = new
Summing();
int p = obj.add(a, b); // actual parameters
System.out.println(“Sum = “ + p);
}
}

static methods.
Static methods Non-static methods

These methods are considered to be These methods are the members of all
the members tied to the class itself. instances of the class.

These methods can only use the These methods can only use the
properties or methods declared within properties or methods defined as a
its block or those specified as static part of its ‘data members’ and, as
in the class. such, cannot directly access the
static variables in the class.

Static methods can be directly called Non-static methods can be called from
from the main() function without the main() function by creating an
creating an instance of the class. instance of the class.
Reason: The main() method, by Reason: static functions, including
convention, is also static. main() can only directly access
other static elements.

Calling static methods from Calling non-static methods from


non-static methods: static methods:

public static void add (int public void add (int m, int
m, int n) { n) {
System.out.println(m + System.out.println(m +
n); } n); }
public void addThree (int public static void main
m, int n, int o) { (String[] args) {
System.out.println( <Classname> obj = new
<Classname>.add( <Classname>();
<Classname>.add(m, n), o obj.add(a, b); // access via
) instance
); // indirect access }
}

Calling static methods from other Calling non-static methods from


static methods: other non-static methods:
public static void add (int public void add (int m,int n)
m, int n) { { System.out.println(m + n);
System.out.println(m + }
n); }
public static void public void addThree (int
addThree (int m, int n, m, int n, int o) {
int o) { System.out.println(add(add m,
System.out.println(add(add(m, n), o)); // direct access
n), o)); // direct access }
}
public static void main
(String[] args) {
int a = 6, b = 7;
add(a, b); // direct access }
Passing values to functions.
Actual parameters to functions can be passed through two different ways.
Call/pass by value Call/pass by reference

It is a mechanism where a copy of the It is a mechanism where the memory


values of the actual parameters are addresses (references) of the actual
passed to the formal parameters, such parameters to the formal parameters,
that both the sets of parameters point such that both of the sets of parameters
to different memory locations. point to the same memory locations.

Any changes made to the formal Any changes made to the formal
parameters do not reflect on the values parameters necessarily reflect on the
of the actual parameters. actual parameters.

Example: Example:
public void add (int m, int public void add (int[] arr) {
n) { for (int i = 1; i < arr.length;
m = m + n; i++)
System.out.println(“Sum=“+m); arr[0] += arr[i];
} System.out.println(
“Sum = ” + arr[0]);

public static void main }


(String[] args) { public static void
<Classname> obj = new main(String[] args) {
<Classname>(); <Classname> obj = new
int a = 3, b = 5; <Classname>();
obj.add(a, b); int[] a = {1, 3, 5, 2,
} 9}; obj.add(a);
}
Here, the values of m and n (formal
parameters) are independent of those Here, the first element of the array,
of a and b (actual parameters). arr[0], is modified by the
Changes to m here will not reflect on function add() (to the formal
a. parameter). This change is also
reflected in the original array, i.e.,
a[0] is modified (actual
parameter).

Pure and impure functions.


Pure functions Impure functions

Such functions are primarily used for Such functions are primarily used for
reading or displaying some data, and writing some new data or modifying
usually return a value to its caller; the existing data; hence, they are also
hence, they are also called Accessors. called Mutators.

They do not cause any change in the They change the internal state of the
internal state of the object or in the object and/or the values of the actual
actual parameters. parameters.
They are usually called by-value. They are called by-reference if it
changes the actual parameters of the
object.

Example: Example:
public class Example { public class Example {
int a = 12; int a = 12;
public void add (int x) { public void add (int x) {
int s = a + x; a += x;
System.out.println(s); } // } // mutates the instance
does not mutate values; only variable without returning
prints the sum public int addN (int[] x) {
public int subtract (int x) { for (int i = 0; i <
int d = a - x; x.length; i++)
return d; a += x[i];
} // does not mutate values; return a;
only returns the difference } } // mutates the instance
variable and returns it
public void inc2 (int[] x) {
for (int i = 0; i <
x.length; i++)
x[i] += 2;
} // mutates the actual
parameter
}

Function overloading.
- The process of defining multiple functions or methods bearing the same
function name but different lists of parameters, differing either in number or
in types of parameters or both, is called Function Overloading, and the
functions so defined are called Overloaded functions.
- The process of function overloading is the software implementation of the
principle of polymorphism in Java.
- When any overloaded function is called, during program compilation, the
compiler finds the best suitable match of the arguments or actual parameters
given to the function call with the corresponding formal parameters. This
phenomenon is termed as Early / Static Binding.
- Examples:
• int area (int a, int b);
double area (double a, double b);
double area (double a, int b);
These are valid overloaded function prototypes as the parameter types are
different.
• int area (int a, int b);
int area (int a, int b, int h);
These are valid overloaded function prototypes as the number of
parameters are different.
• int area (int a, int b);
int area (int x, int y);
These are NOT valid overloaded function prototypes as neither the types
nor the number of parameters is different.
- Illustration:
public class Area {
// Area of a circle
public double area (double r) {
double ar = 2269/7.0 * r * r;
return ar;
}
// Area of a square
public float area (float s) {
The first float ar = s * s;
overload is return ar;
executed }
because it is // Area of a rectangle
the best match
public double area (double l,
(double r).
double b) { double ar = l * b;
The third return ar;
overload is public static void main
executed as it’s the best match (double (String[] args) { Area obj
l, double b). = new Area();
} double m = obj.area(3);
// Driver code
The second overload is
executed because it is the
best match (float s).
float n = obj.area(3.5f);
double o = obj.area(6, 9.2);
System.out.println(“Areas:”);
System.out.println(“\tof a circle with r = 3: “ + m);
System.out.println(“\tof a square with r = 3.5: “ + n);
System.out.println(“\tof a rectangle with l = 6 and b = 9.2: “
+ o);
}
}
Constructors
Definition. A member method bearing the same name as that of the class used to
initialize the instance variables of the objects during object creation is called a
constructor.

Characteristics.
- The constructor is defined with the same name as that of the class. - It is only
used to initialize the data members or instance variables, and not for any other
task.
- It is implicitly called when an object is instantiated from a class. Classname obj
= new Classname(); // this calls the constructor - It does not return
any data, and no return type is specified in the method prototype.
- It is always public, as the constructor is implicitly called from outside the class
while creating an object.

Types.
- A constructor that is implicitly created by the compiler in the absence of a user
defined one in order to initialize all instance variables with valid default initial
values is called a Default constructor. Illustration:
public class Test {
char c;
int i;
short s;
long l;
float f;
double d;
String t;
boolean b;
public void display() {
System.out.println(“Initial values of:”);
System.out.println(“c=”+c); // prints: c=
System.out.println(“i=”+i); // prints: i=0
System.out.println(“s=”+s); // prints: s=0
System.out.println(“l=”+l); // prints: l=0
System.out.println(“f=”+f); // prints: f=0
System.out.println(“d=”+d); // prints: d=0
System.out.println(“t=”+t); // prints: t=null
System.out.println(“b=”+b); // prints: b=false
}
public static void main(String[] args) {
Test obj = new Test();
obj.display();
}
}
• The default initial values for different data types are as follows:
Data type Default initial value

byte 0

char ‘\u0000’
[Represents the non
printable null character]

short 0

int 0

long 0L

float 0.0f

double 0.0

boolean false

String null

- A constructor that initialises the instance variables of all the objects with fixed
values readily available within the constructor is called a Non-parameterised
constructor. Such a constructor has no formal parameters defined in the
method prototype, hence the name. Illustration:
public class Interest {
double rate, time;
public Interest() {
rate = 6.0; // %
time = 4.5; // years
}
public void display(double principal) {
System.out.println(“Principal: “ + principal);
System.out.println(“Rate of interest: “ + rate + “%”);
System.out.println(“Time (in years): “ + time); // All
objects created will have the same values of `rate` // and
`time`.
double interest = principal * rate * time / 100.0;
double amount = principal + interest;
System.out.println(“Interest: “ + interest);
System.out.println(“Amount: “ + amount);
}
public static void main(String[] args) {
Test obj = new Test();
obj.display(5000);
}
}
- A constructor defined by the user that initialises the instance variables with
different values, passed into it via parameters at the time of creating an object,
is called a Parameterised constructor. Illustration:
public class BankUser {
String name;
double balance;
public BankUser(String n, double b) {
name = n;
balance = b;
}
// Instance variables are initialised with the values of the
// parameters passed during object creation.
public void withdraw (double amt) {
double newBal = balance – amt;
if (newBal < 10)
System.out.println(“New balance cannot be less than 10!”);
else {
balance = newBal;
System.out.println(“Withdrawal successful! New balance: “ +
newBal);
}
}
public void deposit (double amt) {
balance += amt;
System.out.println(“Deposit successful! New balance: “ +
balance);
}
public void enquiry() {
System.out.println(“Name: “ + name);
System.out.println(“Balance: “ + balance);
}
public static void main(String[] args) {
BankUser bnk = new BankUser(“Adolf”, 50000.0);
bnk.enquiry();
bnk.withdraw(6000);
bnk.deposit(200);
bnk.enquiry();
}
}

Differences between constructors and methods.


Constructors Methods/Functions

Constructors have the same name as Functions have names different to that
that of the class. of the class.

Constructors are implicitly called For using a member function, it needs


during object creation, and as such are to be called manually by the user.
not called manually by the user.

Constructors never return a value. Functions may or may not return a


value.

Constructors are almost always public. Functions can be public, private


or protected depending on the use
case.

Library Classes
Wrapper classes. A wrapper class is a class that wraps, encapsulates or
contains a primitive data type. It serves two needs:
- Using a wrapper class, primitive data items can be converted into composite
objects.
- Wrapper classes contain useful methods for manipulating the corresponding
primitive data.
There are eight wrapper classes in Java.
Primitive data type Corresponding wrapper class

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

Methods of wrapper classes.


- Conversion of Strings to other primitive data types:
Outp Method Usage
ut
data
type

int Integer.parseInt(String s) String s = “42”;


int n =
Integer.parseInt(s);

long Long.parseLong(String s) String s =


“9999999999”;
long n =
Long.parseLong(s);

float Float.parseFloat(String s) String s =


“300.5”; float f
=
Float.parseFloat(s);

double Double.parseDouble(String s) String s =


“24.334834232”;
double d =
Double.parseDouble(s);

If the input strings contain characters other than numbers, the methods throw
java.lang.NumberFormatException.
- Useful methods of class Character:
Method Usage Example

boolean To check if the boolean p =


isLetter( given character Character.isLetter(‘c’);
ch ar c) is an alphabet. boolean q =
Character.isLetter(‘6’);
// p = true, q = false

boolean To check if the boolean p =


isDigit(c given character Character.isDigit(‘c’);
ha r c) is a digit. boolean q =
Character.isDigit(‘6’);
// p = false, q = true

boolean To check if the boolean p =


isLetterOr given character Character.isLetterOrDigit(‘c’)
D is an alphabet ; boolean q =
igit(char OR digit. Character.isLetterOrDigit(‘6’)
c) ; boolean r =
Character.isLetterOrDigit(‘@’)
; // p = true, q = true, r =
false

boolean To check if the boolean p =


isWhitesp given character Character.isWhitespace(‘
ac e(char is a whitespace ’); boolean q =
c) (blank space). Character.isWhitespace(‘\n’
Valid ); boolean r =
whitespaces in Character.isWhitespace(‘@’
Java are: ); // p = true, q = true,
‘\n’, ‘ ‘ r = false
(blank space),
‘\r’,
‘\t’, etc.

boolean To check if the boolean p =


isLowerCa given argument Character.isLowerCase(‘c’
se (char is a lowercase ); boolean q =
c) alphabet. Character.isLowerCase(‘L’
); boolean r =
Character.isLowerCase(‘4’)
; // p = true, q = false,
r = false

boolean To check if the boolean p =


isUpperCa given argument Character.isUpperCase(‘c’
se (char is an uppercase ); boolean q =
c) alphabet. Character.isUpperCase(‘L’
); boolean r =
Character.isUpperCase(‘4’)
; // p = false, q = true,
r = false

char To convert the char p =


toLowerCa given alphabet Character.toLowerCase(‘c’
se (char into its ); char q =
c) uppercase Character.toLowerCase(‘L’);
variant. If non
alphabet is

passed, the char r =


same Character.toLowerCase(‘4’)
character is ; // p = ‘C’, q = ‘L’, r =
returned. ‘4’

char To convert the char p =


toLowerCa given alphabet Character.toLowerCase(‘c’
se (char into its ); char q =
c) uppercase Character.toLowerCase(‘L’
variant. If non ); char r =
alphabet is Character.toLowerCase(‘4’)
passed, the ; // p = ‘C’, q = ‘L’, r =
same ‘4’
character is
returned.

char To convert the char p =


toLowerCa given alphabet Character.toLowerCase(‘c’
se (char into its ); char q =
c) uppercase Character.toLowerCase(‘L’
variant. If non ); char r =
alphabet is Character.toLowerCase(‘4’)
passed, the ; // p = ‘C’, q = ‘L’, r =
same ‘4’
character is
returned.
char To convert the char p =
toLowerCa given alphabet Character.toLowerCase(‘c’
se (char into its ); char q =
c) lowercase Character.toLowerCase(‘L’
variant. If non ); char r =
alphabet is Character.toLowerCase(‘4’)
passed, the ; // p = ‘c’, q = ‘l’, r =
same ‘4’
character is
returned.

char To convert the char p =


toUpperCa given alphabet Character.toUpperCase(‘c’
se (char into its ); char q =
c) uppercase Character.toUpperCase(‘L’
variant. If non ); char r =
alphabet is Character.toUpperCase(‘4’)
passed, the ; // p = ‘C’, q = ‘L’, r =
same ‘4’
character is
returned.

Autoboxing and Unboxing.


- The automatic conversion of primitive data type into an object of its equivalent
Wrapper class is known as Autoboxing.
• Syntax: <Wrapper class> <objectName> = new <Wrapper
class>(<primitive value>);
• Need for autoboxing:
o To pass a primitive type data to a function that uses a Wrapper object
as its argument.
o To make use of primitive type data for the creation of ArrayLists,
HashMaps, etc.
• Examples:
Double d = new Double(12.42);
Float f = new Float(0.004f);
- The conversion of an object of a Wrapper class into its corresponding primitive
data type is called Unboxing.
• Syntax: <Primitive type> <var> = <Wrapper object>; •
Need for unboxing:
o To pass the value of a wrapper object to a function requiring
arguments of primitive type data.
o To use the data from ArrayLists, HashMaps, etc. as primitive data
values.
Encapsulation
Access specifiers. Access specifiers define the scope and accessibility of a
property or a function from other functions, methods or classes. It can be either:
- private – such that only the members of that specific class in which it is
defined can access the property/method;
- public – such that the property/method is unprotected, i.e., accessible from
any function inside or outside the defining class;
- protected – such that only all the classes and subclasses within the package,
as well as sub-classes of the defining class inside or outside the package, can
access the property/method; or
- default, i.e., no access specifier used – such that the method is set as
‘package-private’, i.e., all the attributes, methods and classes within the same
package only can access the property/method.
Accessor default private protected public

Same class Yes Yes Yes Yes

Same package - - - -

(a) Subclass Yes No Yes Yes

(b) Non Yes No Yes Yes


subclass

Different package - - - -

(a) Subclass No No Yes Yes

(b) Non No No No Yes


subclass

Scope of variables. The scope of a variable refers to the extent or lifetime of its
usage in a certain block of code in a program. Based on the scope of usage, variables
can be categorised into three types:

- Instance variables:
• The variables that are declared within a class as a part of the blueprint for
creating an object of the class, outside the member methods, are called
instance variables or data members.
• The lifetime of instance variables is up to the end of the class, i.e., they are
accessible in all member methods of the class in which they are declared. • The
scope of the instance variables outside the scope of the object depends on the
access specifier used. [See Access specifiers.]
- Class variables/static data members:
• The variables defined within a class along with the keyword static are
called class variables.
• Non-static data members are separate copies made for each object at the
time of its creation, while static data members are independent
variables associated with the class itself.
• To refer to a static data member, the class name itself is used, if referred
to outside a static method, or nothing, if used within another static
method in the class.
• Example:
public class Sample {
static int count = 0;
public void display() {
System.out.println(“Count = “ + Sample.count); }
public void add() {
Sample.count++;
}
public static void main(String[] args) {
Sample o1 = new Sample();
Sample o2 = new Sample();
o1.add();
o2.add();

o1.display();
o2.display();
// Both the display() will output “count: 2” as `count` //
is a static data member, and hence it is associated // with
the class as a whole.

System.out.println(count); // Prints 2
// No tag is used to refer to `count` as the current //
function is declared static.
}
}
- The variables declared within a specific block of code, e.g. a function or method,
are called Local variables. They temporarily hold the values of variables within
the block they are defined in; thus, their lifetime is till the block of code ends.
Example:
public int add(int a, int b) {
int s = a + b;
return s; // `s` is accessible here as its within the scope.
}
public void display() {
System.out.println(add(3, 5));
// `s` will NOT be accessible here as its outside the scope.
}
Arrays
Definition. A composite data storage structure created in the memory to
represent a number of values of the same data type, such that all the values are
arranged consecutively and are assigned to a single variable with different
‘subscripts’, is called a dimensional array.

Use.
- Often times, in a program, a need for storing a large amount of distinct but
related data arises. For smaller sizes of such data, multiple variables can be
initialized and each be used in the rest of the program for performing the
suitable operations; however, if the operation is the same for all such data
items, or if the size is too large to declare separate variables (say, 100), arrays
enter the scene.
- Arrays allow for storing a lot of related data, of the same data type, in a single
variable with different subscripts or indices. Arrays get rid of the unwanted
complexity and repetition that arises while using separate variables of the
same data type.
- Arrays also allow better management of the dynamic memory – separate
variables may be created anywhere in the memory so long as free space is
found, while an array stores all the data consecutively.

Array as a Composite Data Type. An array allows the user to store


multiple data items using the same variable name but different indices and of the
same data type. Essentially, an array can be considered as a composite data type too,
as it refers to the usage of encapsulating a lot of data under a single component.
Thus, in a way, arrays can be called as composite, non-primitive or reference data
types.

Size occupied by an array in the memory. The size that an array


occupies in the dynamic memory depends upon:

- the type of data it is supposed to store; and


- the number of data types.

Essentially: Size of an array = size of a single data item of the


corresponding data type × number of data items.

For example, if an array is to store five integers, then the size occupied by it in the
memory is 4 bytes per element × 5 elements = 20 bytes.

Types. An array can store multiple arrays as well. In this regard, usually, arrays can
be classified into two categories:

- Single-dimensional arrays (SDAs) are used to store data in such a way that
each element represents one and only one distinct entity. In other words, SDAs
can be thought of as data structures that can be represented along the x-axis.
Y

ABCD0 1 2 3 4
X

(Data can be stored in a single dimension only)

- Double-dimensional arrays (DDAs) are used to store data in such a way that
each element of the ‘outer’ array represents a related set of other elements,
which itself is the ‘inner’ array. This structure is similar to the concept of rows
and columns – each element of the ‘outer’ array may be considered as a row
and each element within a row as a column. DDAs can be also thought of as
structures that can be represented along both the x- and the y-axes.

Y
A3 A2 B1 D3 D2

A1 C3 C2 D1

B3 B2 C1
3 2 1
A0 B0 C0 D0
0
X
0 1 2 3 4

(Data can be stored in two dimensions)

.length statement.
- The .length property of an array can be used to find the number of elements an
array can store.
- In the case of SDAs, it returns the number of elements it can store; in the case of
DDAs, it returns the number of rows only.
- Syntax: int l = arr.length;
- It is to be noted that for any array, its last element has an index of
<array>.length – 1, since all arrays are zero-indexed [more about indexes
in the next section].

Working with SDAs.


- An SDA can be created like so:
<data type>[] <var> = new <data type>[<number of values>];
Examples:
• int[] m = new int[10]; // stores 10 integers
• float[] n = new float[10]; // stores 10 single-precision
decimals
• char[] c = new char[10]; // stores 10 characters
• String[] s = new String[10]; // stores 10 strings - Elements of
an SDA are used as <var>[<index>], where <index> is a number denoting
the position of the element, such that the first element of the array has an index
of 0. That is, all arrays in Java are zero-indexed. Example:
• To print the third element of an array m, we use:
System.out.println(m[2]); // third element = 2nd index • To
print the last element of an array m with a given size of l, we use:
System.out.println(m[l – 1]); // ‘l’th element = ‘l-1’th index
- Assigning readymade values to the elements of an array can be done in the
following manner:
<data type>[] <var> = new <data type>[<size>];
<var> = {<elem0>, <elem1>, <elem2>, ..., <elem<size – 1>>};
Example:
int[] m = new int[5];
m = {3, 6, 12, 8, 9};
Alternatively, an array can be assigned directly while declaring it, like so:
int[] n = {3, 6, 12, 8, 9};
- Inputting data into an array can be done by assigning each value inputted into a
corresponding element of the array via its subscript. Illustration: import
java.util.Scanner;
public class Names {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter names of 15 students.”); //
Declaring names[] to store 15 Strings
String[] names = new String[15];
// Looping through each index of the array; notice that //
the loop begins at i = 0 and ends at i = 14. for (int i =
0; i < 15; i++) {
names[i] = key.nextLine();
// Each consecutive input is stored in the ‘i'th element
// of the array.
}
}
}
- One of the most basic operations that can be performed on a composite data
structure like an array is the process of searching. It refers to the procedure
whereby the existence of a value among the elements of an array can be
determined, and if present, its index or position. Two of the algorithms used
for this are Linear/sequential search and Binary search.
• Linear search is one of the simplest algorithms for searching a value in an
array. In it, the target value is sequentially compared with each and every
element of the array, starting from the first one. If a match is found, it can
be concluded that the search was successful – the target value exists in the
array – and the position at which the match occurred can be outputted.
Example:
int[] arr = {3, 6, 12, 8, 9};
int target = 6;
int targetIdx = -1;
for (int i = 0; i < 5; i++) {
if (arr[i] == target) {
targetIdx = i;
break;
}
}
// An index can never be -1. Thus, by using -1 as a //
placeholder, we can check if the target index is still //
-1, in which case, we determine that the element was //
not found in the array.
if (targetIdx == -1)
System.out.println(”Search unsuccessful.”);
// If the target index is anything but -1, we know that the
// linear search was successful.
else {
System.out.println(“Search successful.”);
System.out.println(“Element found at index “ + targetIdx);
}
• Another technique used for searching an element in a given array in a much
more efficient and faster manner as compared to linear search is Binary
search. The only prerequisite for this is that the array used for binary
searching must be sorted. The algorithm is as follows –
o Find the value stored in the middle element of the array.
o Compare the target value with the middle element.
▪ If the middle element is equal to the target element, the search
is successful; the target is exactly at the middle index.
▪ If the middle element is smaller than the target element, it
means the target value must be present in the higher half.
Thus, the first/lower half is discarded.
▪ If the middle element is greater than the target element, it
means the target value must be present in the lower half.
Thus, the second/higher half is discarded.
o Repeat the above process with the half that was not discarded. o If
the size of the halves considered reduces to a single element and the
target element still does not match any element, the search is
unsuccessful.
Example:
int[] arr = {1, 4, 11, 13, 19, 27};
// Notice that the given array is sorted.
int target = 13;
int lowerBound = 0, upperBound = arr.length – 1;
int targetIdx = -1;
while (lowerBound <= upperBound) {
int middleIdx = (lowerBound + upperBound) / 2;
if (arr[middleIdx] < target)
lowerBound = middleIdx + 1;
// By making the lower bound equal to succeeding index //
of the middle one, we effectively discard the first //
half of the array. The next scan will be conducted // on
the latter half (i.e. [middleIdx + 1] to // [upperBound]).
else if (arr[middleIdx] > target)
upperBound = middleIdx – 1;
// By making the upper bound equal to preceding index //
of the middle one, we effectively discard the second //
half of the array. The next scan will be conducted // on
the first half (i.e. lowerBound to
// [middleIdx – 1]).
else if (arr[middleIdx] == target) {
targetIdx = middleIdx;
// If the middle element is exactly equal to the target,
// we found a match; the search is successful. break;
}
}
if (targetIdx == -1)
System.out.println(“Search unsuccessful”);
// If an element were found, it cannot have an index of
// -1. Thus, if `targetIdx` is still -1 from the initial
// declaration, it means the search is unsuccessful. else {
System.out.println(“Search successful”);
System.out.println(“The target was found at index “ +
targetIdx);
}
• Difference between linear search and binary search.
Linear Search Binary Search

It works on both sorted and It works only on sorted data


unsorted arrays. items, either in ascending or
descending order.

It begins at the start of the array In it, an array is divided into two
and continues till the last index halves and then the desired data
(or till the target index if the item is recursively scanned either
element is found). in the first or the second half.
- Another useful and common operation on arrays is sorting. It is the process
wherein the elements of an array are arranged in such a way that they are in a
logical sequence. Usually, if they are numbers, they are sorted in ascending or
descending; if they are characters or Strings, they are sorted in alphabetical
order. Two of the most common algorithms for sorting are Selection sort and
Bubble sort.
• In selection sort, if the elements are to be sorted in ascending order, the
lowest element is interchanged with the element available at the first index
and so on until the end of array is reached.
Illustration (ascending order):
Algorithm Code

for(int i = 0; i < arr.length – 1; i++) {

Iterate through int minIdx = i;


the array and for (int j = i + 1; j < arr.length;
locate the j++) if (arr[j] < arr[minIdx])
smallest minIdx = j;
number.

Swap the int tmp = arr[i];


smallest arr[i] = arr[minIdx];
number with the arr[minIdx] = tmp;
0th value.

Repeat the }
process for all // The outer loop runs `length – 1` times
but one // because at that point in time, all the
elements in the // elements would already be sorted, with
array. // the largest element being at the end.
[Swap the next
smallest
element with
the ith
element.]

Example:
1. [i = 0, minIdx = 0] Since the 0th element is the smallest, the 0th
element is swapped with the 0th element, i.e. no change in the array.

3 12 5 7 9
2. [i = 1, minIdx = 2] Since the next smallest element is at index 2,
the 1st element is swapped with the 2nd element.

3 5 12 7 9
3. [i = 2, minIdx = 3] Since the next smallest element is at index 3,
the 2nd element is swapped with the 3rd element.
3 5 7 12 9

4. [i = 3, minIdx = 4] Since the next smallest element is at index 4,


the 3rd element is swapped with the 4th element.

3 5 7 9 12

5. The loop ends with the array now completely sorted in ascending order. •
In bubble sort, the array is sequentially scanned several times and during each
iteration, a pair of consecutive elements are compared and interchanged, if
necessary, to arrange them in the required order. While it is an easier
approach as compared to selection sort, it takes a lot of time if the array is
large.
Illustration (ascending order):
Algorithm Code

for(int i = 0; i < arr.length – 1; i++) {

Iterate through for (int j=0; j < arr.length-i-1; j++)


the array and {
compare each if (arr[j] > arr[j + 1])
consecutive
pair of
elements.

If the first {
number in the int tmp = arr[j];
pair is arr[j] = arr[j + 1];
bigger than arr[j + 1] = tmp;
the second, }
swap }
them.

Repeat the }
iterations for // The outer loop runs `length – 1` times
all but one // because at that point in time, all the
element in // elements would already be sorted, with
the array. // the largest element being at the end.

// The inner loop runs from 0 to //


`length – i - 1` because after //
completion of the previous set of //
iterations, the `length-i-1`th element //
would be in the correct place.
Example:
1. [i = 0, j = 0] Since 0th element < 1st element, we keep them as it
is and not swap it (no change in array).
3 12 5 7 9
2. [i = 0, j = 1] Since 1st element > 2nd element, we swap them.

3 5 12 7 9

3. [i = 0, j = 2] Since 2nd element > 3rd element, we swap them.

3 5 7 12 9

4. [i = 0, j = 3] Since 3rd element > 4th element, we swap them.

3 5 7 9 12
5. The remaining iterations from i = 1 to i = 3 will not make any
changes since the array is now completely sorted in ascending order.

Working with DDAs.


- A DDA can be created like so:
<data type>[][] <var> = new <data type>[<rows>][<columns>];
Examples:
• int[][] m = new int[5][5];
// stores 25 integers in 5 rows and 5 columns
• float[][] n = new float[3][8];
// stores 24 single-precision decimals in 3 rows and 8
columns
• char[][] c = new char[4][4];
// stores 16 characters in 4 rows and 4 columns
• String[][] s = new String[3][4];
// stores 12 strings in 3 rows and 4 columns
- Elements of a DDA are used as <var>[<row>][<column>], where <row> and
<column> are numbers denoting the position of the element, such that the
first row/column has an index of 0. Example:
• To print the third element of the second row of a DDA m, we use:
System.out.println(m[1][2]);
// second row = 1st index; third column = 2nd index • To print
the last element of the last row of a DDA array m with the total number of
rows being r and columns being c, we use:
System.out.println(m[r – 1][c – 1]);
// ‘r’th row = ‘r-1’th index; ‘c’th column = ‘c-1’th index -
Assigning readymade values to the elements of an array can be done in the
following manner:
<data type>[][] <var> = new <data type>[<rows>][<columns>];
<var> = {
{<r0c0>, <r0c1>, <r0c2>, ..., <r0<columns – 1>>}, {<r1c0>,
<r1c1>, <r1c2>, ..., <r1<columns – 1>>}, ...,
{<r<rows – 1>c0>, ..., <r<rows – 1>c<columns – 1>>} }
Example:
int[][] m = new int[3][3];
m = {
{3, 6, 12},
{4, 1, 2},
{7, 7, 23}
};
Alternatively, an array can be assigned directly while declaring it, like
so: int[][] n = {
{3, 6, 12},
{4, 1, 2},
{7, 7, 23}
};
- Inputting data into an array can be done by assigning each value inputted into a
corresponding column of the array via the corresponding row and column
subscripts. Illustration:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter 15 integers in the 3x5 matrix”);
// Declaring m[] to store 15 integers in a 3x5 matrix.
int[][] m = new int[3][5];
// Looping through each row of the array; notice that //
the loop begins at i = 0 and ends at i = 2. for (int i =
0; i < 3; i++) {
// Looping through each column of the ‘i'th row; notice //
that the loop begins at j = 0 and ends at j = 4. for (int j =
0; j < 5; j++) {
m[i][j] = key.nextInt();
// Each consecutive input is stored in the ‘j'th column //
of the ‘i'th row of the array.
}
}
}
}
- Displaying the elements of a DDA in the form of a matrix can be done like so:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
// Declaring the 4x4 matrix
int[][] m = new int[4][4];
// Inputting data
System.out.println(“Enter 16 integers in a 4x4 matrix”);
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
m[i][j] = key.nextInt();
// Displaying m[][] in the form of a matrix
System.out.println(“The numbers in the matrix are:”);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(m[i][j] + “ “);
// This prints the jth column of the ith row of the //
matrix with a whitespace after it.
}
System.out.println(); // This concludes the ith row. }
}
}
- Finding the sum of elements in a row or column can be done like so:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
// Declaring the 4x4 matrix
int[][] m = new int[4][4];
// Inputting the matrix
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
m[i][j] = key.nextInt();
}
}
// Finding the sum of elements of each row
for (int i = 0; i < 4; i++) {
int r = 0;
for (int j = 0; j < 4; j++)
r += m[i][j];
System.out.println(“Sum of the elements of row #” + (i+1) +
“ is “ + r);
}
// Finding the sum of elements of each column
for (int i = 0; i < 4; i++) {
int c = 0;
for (int j = 0; j < 4; j++)
c += m[j][i];
System.out.println(“Sum of the elements of column #” + + (i
+ 1) + “ is “ + c); }
// Notice that if the first subscript changes while // the
second remains constant, the values of the // <second
subscript>th column can be determined. // Otherwise, if the
first remains constant and the second // tends to change, the
values in the <first subscript>th
// row can be determined.
}
}
- Finding the sum of the numbers in the diagonals – left and right – of a DDA
cum-matrix can be done like so:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
// Declaring the 4x4 matrix
int[][] m = new int[4][4];
// Inputting the matrix
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
m[i][j] = key.nextInt();
}
}
// Finding the sum of the left diagonal
int ld = 0;
for (int i = 0; i < 4; i++)
ld += m[i][i];
// Notice that if we keep both the subscripts the same //
and change both of them in the loop, we get a pattern //
like this: 1st row, 1st column; 2nd row, 2nd column // and
so on, which is exactly the left diagonal of the // matrix.

// Finding the sum of the right diagonal


int rd = 0;
for (int i = 0; i < 4; i++)
rd += m[i][3 – i];
// Notice that keeping the second subscript as the last //
index of the array minus the first subscript, we get // a
pattern like this: 1st row, 4th column; 2nd row, 3rd //
column; 3rd row, 2nd column and so on, which is exactly //
the right diagonal of the matrix.
}
}
String handling
String class.
The default java.lang package contains the String class, which functions as a
built-in data type representing a set of alphanumeric and special characters as a
single unit. A string literal, i.e., a set of characters enclosed within double quotes, has
the String data type.

Creating a string can be done in many ways:


- String s1 = “Hello, world!”;
- String s2 = new String(“Hello, world!”);
- char[] sch = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘ ‘, ‘w’, ‘o’, ‘r’,
‘l’, ‘d’, ‘!’};
String s3 = new String(sch); // “Hello, world!”
// Joins all the characters in the array sch[].
- String s4 = new String(sch, 0, 5); // “Hello”
// Joins 5 characters from the 0th index of sch[].

Methods of the String class.


Method Usage Example

String trim() Removes leading and String a = “ HI WORLD!


trailing whitespaces “; String b = a.trim();
from a string; rest of // b = “HI WORLD!”
the whitespaces will
remain unchanged.
String Converts all the String a = “HI, World!”;
toLowerCase() uppercase alphabets String b =
in the string to a.toLowerCase(); // b =
lowercase. Other “hi, world!”
characters will
remain unchanged.

String Converts all the String a = “Hi, World!”;


toUpperCase() lowercase alphabets String b =
in the string to a.toUpperCase(); // b =
uppercase. Other “HI, WORLD!”
characters will
remain unchanged.

int length() Returns the number String a = “Hello,


of characters in the world!”; int l =
string. a.length();
[Distinction from // l = 13
<array>.length:
.length() is a
function of an
instance of the
String class, while
.length is a data
member or
property intrinsic
to the array.]

char Returns the character String a = “HI, World!”;


charAt(int n) present at the nth char b = a.charAt(4);
index in the string. // b = ‘W’
[Indexes of
characters in a
String behave
similarly to those of
an array: the first
character has an
index of 0.]

int Returns the index String a = “Hello,


indexOf(cha position of the first World!”; int b =
r ch) occurrence of the a.indexOf(‘o’);
given character in // b = 4
the string. [If the
given character is
not found, the
function returns -1.]

int Returns the index String a = “Hello,


lastIndexOf(c position of the last World!”; int b =
ha r ch) occurrence of the a.lastIndexOf(‘o’); // b =
given character in 8
the string. [If the
given character is
not found, the
function returns -1.]

String Joins, appends or String a = “Hello,”;


concat(Strin concatenates the String b = “ World!”;
g str) characters of str String c = a.concat(b);
with the instance // c = “Hello, World!”
string.
[This function is
equivalent to using
the concatenation
operator + on two
or more
strings.]

boolean Compares str with String a = “Hello!”;


equals(Strin the instance string String b = “hi”;
g str) and checks if they String c = “Hello!”;
are equal in all String d = “hello!”;
respects. boolean x = a.equals(b);
boolean y = a.equals(c);
boolean z = a.equals(d);
// x = false, y = true, z=false

boolean Compares str with String a = “Hello!”;


equalsIgnoreC the instance string String b = “hi”;
as e(String and checks if they String c = “Hello!”;
str) are equal in terms of String d = “hello!”;
length and order of boolean x = a.equals(b);
characters, ignoring boolean y = a.equals(c);
the case of the boolean z = a.equals(d);
alphabets. // x = false, y = true, z = true

int Compares str String a = “Hello!”;


compareTo(Str with the instance String b = “hi”;
in g str) string String c = “Hello!”;
lexicographically, String d = “hello!”;
i.e., like comparing int x = a.compareTo(b);
two words in a int y = a.compareTo(c);
dictionary, and int z = a.compareTo(d);
returns an integer // x = -32 because the first
corresponding to the different characters, ‘H’ and
difference in ASCII ‘h’ have ASCII values of 72 and
104, whose difference is -32.
values of the first
// y = 0 because there is no
distinct characters
difference in the strings (both
in the string. are equal)
If the return value is // z = -32; similar reason to x
negative, it means
the instance string
is
smaller than str, i.e.
the instance string
may appear before
str in a dictionary.
If the
return value is
positive, the
instance string is
greater. If the
return value is 0,
the strings are
equal.

int Similar function to String a = “Hello!”;


compareToIgno compareTo, but String b = “hi”;
re here, the case of the String c = “Hello!”;
Case(String alphabets is ignored. String d = “hello!”;
str) int x = a.compareTo(b);
int y = a.compareTo(c);
int z = a.compareTo(d);
// x = -4 because the first
different characters, ‘e’ and
‘i’ (not ‘H’ and ‘h’ as casing
is ignored), have ASCII values
of 101 and 105, whose difference
is -4.
// y = 0 as there is no
difference in the strings
// z = 0; although there is a
difference in the first
characters ‘H’ and ‘h’,
the casing is ignored.

String Replaces all String a = “Henlo!”;


replace(char occurrences of Stirng b = a.replace(‘n’,
oldChar, char oldChar in the ‘l’); // b = “Hello!”
newChar) string with
newChar and
returns the modified
string.

String Extracts a set of String a = “Hello,


substring(in characters from world!”; String b =
t the string a.substring(7); // b =
beginIndex) starting with “world!”;
(and including)
the character at
beginIndex and
ending with the last
character in the
string.
String Extracts a set of String a = “Hello, world!”;
substring(int characters from String b = a.substring(0,
beginIndex, the string 5); // b = “Hello”;
int endIndex) starting with
(and including)
the character at
beginIndex and
ending with (but
excluding) the
character at
endIndex.

boolean Checks if the String a = “Hello,


startsWith(St instance string has world!”; boolean x =
ri ng str) str at the a.startsWith(“Hello”);
beginning, i.e., as boolean y =
its prefix. a.startsWith(“Hi”); // x =
true, y = false

boolean Checks if the String a = “Hello,


endsWith(Strin instance string has world!”; boolean x =
g str) str at the end, a.endsWith(“world!”);
i.e., as its suffix. boolean y =
a.endsWith(“friend!”);
// x = true, y = false

String Converts the value of int a = 61;


valueOf(<prim the primitive type double b = 3.141592653589;
it ive type> data x into a char c = ‘@’;
x) String. boolean d = false;

Writing Programs(Section-B)
Question 3
Kind of question. This involves creating a large sophisticated class with
methods defined for different purposes, data members defined appropriately, a
constructor to initialize the data members and most likely, main() method to create
an object of the class and call the methods. The methods themselves are quite trivial;
they usually include:
- A method to input data from the user. This method will receive the input from
the keyboard and assign the values to the respective data members. - A method to
calculate and populate the necessary data members with the calculated values.
This usually involves calculating discounts, electricity bills, travel costs, cab fares,
student grades, etc.
- A method to display the data members in a presentable format to the console.
This involves a series of System.out.printlns to print a label and the
corresponding data member.

Attemptability. Very easy. Does not require a lot of logical analysis of the
question.
Length. May get very long for complicated calculation methods.

Question 4
Kind of question. This involves operations on SDAs. It is asked to input a fixed
number of integers, characters or strings into a single-dimensional array and perform
a given algorithm for searching (Linear search or Binary search) or sorting (Selection
sort or Bubble sort). The question may not mention the use of an array or the data
type directly or even whether to sort or not.

Sample.
Write a program to input the names and total marks of 25 students and print the
names based on the descending order of their marks.
Here, the first step would be to create two arrays: one being a String[] for storing
25 names and another being either int[] or double[] for storing the marks.
Then, using either Selection sort or Bubble sort, the marks and names arrays must be
sorted in such a manner that the highest scorer appears on top.

Solution:
import java.util.Scanner;
public class Marks {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
// Declaring n[] and m[] for storing names and marks.
String n[] = new String[25];
double m[] = new double[25];
// Inputting data into the arrays.
for (int i = 0; i < 25; i++) {
System.out.println(“Enter name of student #” + (i + 1)); n[i]
= key.nextLine();
System.out.println(“Enter marks of student #” + (i + 1)); m[i]
= key.nextInt();
key.nextLine(); // Printing the sorted arrays
} System.out.println(“Name\tMarks”)
// Sorting the arrays based on ; for (int i = 0; i < 25; i++)
descending order of marks using
This empty nextLine() is a workaround
Selection sort. for absorbing the extra newline that the
for (int i = 0; i < 24; i++) { previous nextInt() adds and does not
int maxIdx = i; account for. In the exam, however, this is not
for (int j = i + 1; j < 25; j++) too necessary to include.
if (m[j] > m[maxIdx]) maxIdx =
j;
String tmpName = n[i]; Notice that we check if the jth element is
int tmpMark = m[i]; greater than the current maximum index.
n[i] = n[maxIdx]; This is because we want the sorting to
m[i] = m[maxIdx]; happen in descending order, therefore, we
n[maxIdx] = tmpName; select the next biggest element and swap it
m[maxIdx] = tmpMark; with the ith element.
}
System.out.println(n[i] + “\t” + m[i]);
}
}

Attemptability. Not too bad. If one remembers or deduces the appropriate code
to use for the algorithms, it becomes trivial.

Length. Medium-sized program. Not too long, not too short.

Question 5
Kind of question. This involves different kinds of String manipulations, such
as extracting characters and counting their types (uppercase, lowercase, etc.),
conversion of the string into uppercase or lowercase, counting the number of vowels
or consonants, sorting the string alphabetically, etc.
Samples.
- Define a class to accept a string. Count and display the number of uppercase
and lowercase consonants in it.
Sample Input: HellO, World!
Sample Output:
Number of uppercase consonants: 2
Number of lowercase consonants: 5

import java.util.Scanner;
public class ConsonantCount {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter a string:”);
String s = key.nextLine();
int lc = 0, uc = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
// Extract the `i`th character
char c = s.charAt(i);
// Check if the character is a letter
if (Character.isLetter(c)) {
// Check if the letter is a consonant
char cl = Character.toLowerCase(c);
if (cl != ‘a’ && cl != ‘e’ && cl != ‘i' && cl != ‘o’ && cl
!= ‘u’) {
// Check if the consonant is uppercase
if (Character.isUpperCase(c))
uc++;
else // Consonant is lowercase
lc++;
}
}
}
System.out.println(“Number of uppercase consonants: “+uc);
System.out.println(“Number of lowercase consonants: “+lc); }
}
- Define a class to accept a String and change the case of each letter of the string.
Display the new string.
Sample Input: WelComE TO School
Sample Output: wELcOMe to sCHOOL [ICSE 2008]

import java.util.Scanner;
public class InvertCase {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter a string:”);
String s = key.nextInt();
String ms = “”;
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (Character.isLowerCase(c))
ms += Character.toUpperCase(c);
else if (Character.isUpperCase(c))
ms += Character.toLowerCase(c);
else
ms += c;
}
System.out.println(“String with case inverted:\n” + ms); }
}
- Define a class to accept a word in lowercase and display the new word after
removing all the repeated characters.
Sample Input: applications
Sample Output: aplictons

import java.util.Scanner;
public class RemoveRepeated {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter a word:”);
String w = key.next();
String mw = “”;
int len = w.length();
for (int i = 0; i < len; i++) {
char c1 = w.charAt(i);
boolean isRepeated = false;
for (int j = 0; i < mw.length(); i++) {
char c2 = mw.charAt(j);
if (c1 == c2)
isRepeated = true;
}
if (!isRepeated)
mw += c1;
}
System.out.println(“New word after removing duplicate
characters: “ + mw);
}
}
- 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 [ICSE 2018]
import java.util.Scanner;
public class CapitalizeString {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter a string:”);
String s = key.nextLine();
s = “ “ + s.trim();
String ns = “”;
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c == ‘ ‘) {
char c2 = s.charAt(i + 1);
ns += “ “ + Character.toUpperCase(c2);
}
else
ns += c;
}
System.out.println(“Capitalized string:\n” + ns); }
}
- Write a program to input a sentence. Count and display the frequency of each
letter in the sentence in alphabetical order.
Sample Input: COMPUTER APPLICATIONS
Sample Output:
Character Frequency
A2
C2
I1
L2
M1
N1
O2
P3
R1
S1
T2
U 1 [ICSE 2010]

import java.util.Scanner;
public class Frequency {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.println(“Enter a sentence:”);
String s = key.nextLine().toUpperCase();
int l = s.length();
int[] freqs = new int[26];
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if(Character.isLetter(c))
freqs[c – 65]++;
}
System.out.println(“Character\tFrequency”);
for (int i = 0; i < freqs.length; i++) {
if (freqs[i] == 0) continue;
System.out.println((char)(i + 65) + “\t” + freqs[i]); }
}
}
- Define a class to store names of 20 students and their phone numbers
correspondingly in two different SDAs. Enter a name separately and search
for it in the list of given names. If it is present, display the name with the
student’s phone number. Otherwise, display a message: “Name not found”.
Use linear search technique.

import java.util.Scanner;
public class Students {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
// Declaring n[] and p[] for storing names and phone nos.
String[] n = new String[20];
long[] p = new long[20];
// Inputting names and phone numbers
for (int i = 0; i < 20; i++) {
System.out.println(“Enter name of student #” + (i + 1));
n[i] = key.nextLine();
System.out.println(“Enter phone number of student #” + (i +
1));
p[i] = key.nextLong();
key.nextLine(); // Absorbs extra newlines
}
System.out.println(“Enter name to be searched for:”);
String target = key.nextLine();
int idx = -1;
for (int i = 0; i < 20; i++) {
if (n[i].equalsIgnoreCase(target)) {
idx = i;
break;
}
}
if (idx > -1) {
System.out.println(“Name: “ + n[idx]);
System.out.println(“Phone no.:” + p[idx]);
}
else
System.out.println(“Name not found”);
}
}
- Write a program to accept 10 different city names into an SDA. Arrange the
names in ascending order by using the Bubble Sort technique and display
them.
Sample Input: Delhi, Bengaluru, Agra, Mumbai, Kolkata
Sample Output: Agra, Bengaluru, Delhi, Kolkata, Mumbai [ICSE 2008]

import java.util.Scanner;
public class CitySort {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
// Declaring the array
String[] cities = new String[10];
// Inputting 10 cities
System.out.println(“Enter names of 10 cities”);
for (int i = 0; i < 10; i++)
cities[i] = key.nextLine();
// Sorting them alphabetically using Bubble sort
for (int i = 0; i < 9; i++) {
for (int j = 0; j < (9 – i); j++) {
if(cities[j].compareTo(cities[j+1]) > 0) { String
tmp = cities[j];
cities[j] = cities[j + 1];
cities[j + 1] = tmp;
}
}
}
// Printing the sorted list of cities
System.out.println(“Cities arranged in ascending order:”);
for (int i = 0; i < 10; i++) {
System.out.println(cities[i]);
}
}
}
- Write a program to input forty [terms] in an array. Arrange these words in
descending order of letters using Selection Sort technique. Print the sorted
array.
Sample Input: New Delhi, Bengaluru, Agra, Mumbai, Kolkata Sample
Output: New Delhi, Mumbai, Kolkata, Bengaluru, Agra [ICSE 2017] import
java.util.Scanner;
public class TermSort {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
// Declaring the array
String[] w = new String[40];
// Inputting 40 words into w[]
System.out.println(“Enter forty different words:”);
for (int i = 0; i < 40; i++)
w[i] = key.nextLine();
// Sorting the array in descending order via selection sort
for (int i = 0; i < 39; i++) {
int maxIdx = i;
for (int j = i + 1; j < 40; j++)
if (w[j].compareTo(w[maxIdx]) > 0)
maxIdx = j;
String tmp = w[i];
w[i] = w[maxIdx];
w[maxIdx] = tmp;
}
// Printing the sorted array
System.out.println(“The words arranged in descending order
are as follows:”);
for (int i = 0; i < 40; i++)
System.out.println(w[i]);
}
}

Attemptability. Fairly easy. One must know the prescribed string functions,
character functions, loop logic, etc. to be able to answer this perfectly.

Length. Short.

Question 6
Kind of question. This involves operations on matrix-cum-DDAs. One has to
input the values to a DDA of given number of rows and columns, and perform some
common summing operations, such as sum of even elements, sum of odd elements,
sum of each row, sum of each column, sum of left or right diagonal, etc.

Attemptability. Very easy. If one remembers the way to input and access
elements into and from a DDA, it becomes trivial.

Length. Fairly long, mostly because of the repeated double loops.

Question 7
Kind of question. This involves detection of special numbers like Tech number,
Duck number, etc. There is not much that can be said about the specifics of these
special numbers, since there are a horde of them. Usually, the detections involve
reversing, sum of digits in a certain order, iterating through each digit and
performing
some checks, etc. The definition of the special number will always be given in the
question.

Attemptability. Fairly difficult if the logic of the special number is


complicated. Length. Low-to-medium sized programs.

Question 8
Kind of question. This involves function overloading. Usually, one is asked to
define two overloads, each being a short logical operation like printing patterns,
detection of special numbers, numeric digit manipulations, etc. This can be replaced
with a menu-driven question of a similar manner.

Attemptability. Could be logically heavy if the given operations have a lot of


moving parts.

Length. Usually medium-sized.

Note
The order of questions as given above may be different; the types of questions,
however, remain the same.

You might also like