CTA Notes
CTA Notes
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.
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).
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
• Non-numeric types:
Data type Keyword Size
- 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.
- Relational operators:
Operator Mathematical Example
equivalent
- Logical operators:
Name Symbol Truth table
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
Precedence of operators.
Larger number means higher precedence.
Precedence Operator Name Associativity
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.ceil(a) Retur
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.
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.
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 package - - - -
Different - - - -
package
• <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.
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.
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.
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 }
}
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]);
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();
}
}
Constructors have the same name as Functions have names different to that
that of the class. of the class.
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
If the input strings contain characters other than numbers, the methods throw
java.lang.NumberFormatException.
- Useful methods of class Character:
Method Usage Example
Same package - - - -
Different package - - - -
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.
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
- 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
.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].
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
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
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
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.
3 5 12 7 9
3 5 7 12 9
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.
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.
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.
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.
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.
Note
The order of questions as given above may be different; the types of questions,
however, remain the same.