Chapter 01
Chapter 01
Object-Oriented
Programming
CHAPTER ONE
Programming Paradigms
• Programming Paradigm is a way of conceptualizing what it
means to perform computation and how tasks to be carried out
and organized on a computer.
Structured Programming
• Problem solving would involve the analysis of processes in
terms of the procedural tasks carried out and the production of
a system whose representation is based on the procedural flow
of the processes.
• data was separate from code.
• programmer is responsible for organizing everything in to
logical units of code/data.
• A procedural program is divided into functions, and (ideally, at
least) each function has a clearly defined purpose & a clearly
defined interface to the other functions in the program.
Contd…
2. Real-World Modeling
• Unrelated functions and data, the basics of the procedural paradigm,
provide a poor model of the real world.
objects.
Optional
Package Statement
Optional
Import Statements
Optional
Interface Statements
Import statements
• Next to package statements (but before any class
definitions) a number of import statements may exist. This is
similar to #include statements in C or C++.
• Using import statements we can have access to classes that
are part of other named packages.
Example: import java.lang.Math;
Interface Statements
• An interface is like a class but includes a group of method
declarations.
• is also an optional section.
• is used only when we wish to implement the multiple
inheritance features in the program
Class Definitions
• A Java program may contain multiple class definitions.
• Classes are the primary and essential elements of a Java
program.
• These classes are used to map objects of real-world
problems.
• The number of classes depends on the complexity of the
problem.
Main Method
• Since every Java stand-alone program requires a main
1)$amount 5) score
2)6tally 6) first Name
3)my*Name 7) total#
4)salary 8) cast
3. Literals
• Literals in Java are a sequence of characters(digits, letters and
other characters) that represent constant values to be stored in
variables.
• Five major types of literals in Java:
and arranged.
expressions.
• Relational operators
• Logical operators
• Assignment operator
• Increment/Decrement operators
• Conditional operators
• Bitwise operators
• Special operators
A. Arithmetic Operators
• Java has five basic arithmetic operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
3) result = (x != x*y);
now result is assigned the value true because the product of x
and y (15) is not equal to x (3)
C. Logical Operators
Symbol Name
&& Logical AND
|| Logical OR
! Logical NOT
count = count - 1;
can be written as:
--count; or count--;
-- is called the decrement operator.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
7. Special Operators
• Java supports some special operators of interest such as
instanceof operator and member selection operator(.).
int a=110;
float b=23.5;
the expression a+b yields a floating point number 133.5 since the
‘higher’ type here is float.
Contd…
B.Casting a value: is used to force type conversion.
(type-name)expression;
a=(int)21.3/(int)3.5; a will be 7
Operator Precedence and Associativity.
Operator Description Associativity Rank
. Member Selection
() Function call
Left to right 1
[] Array elements reference
- Unary Minus
++ Increment
-- Decrement
! Logical negation Right to left 2
~ One’s complement
(type) Casting
* Multiplication
/ Division Left to right 3
% Modulus
Contd…
Operator Description Associativity Rank
+ Addition
Left to right 4
- Subtraction
<< Left Shift
>> Right Shift Left to right 5
• Data types specify the size and type of values that can
be stored.
• Java language is rich in the data types.
Primitive Non-Primitive
(Intrinsic) (Derived)
Interfaces
Integer Floating-Point Character Boolean
There are two data types that can be used to store decimal
values (real numbers).
C. Character Type
Is used to store character constants in memory.
Java provides a character data type called char
The char data type assumes a size of 2 bytes but, basically,
it can hold only a single character.
There are only two values that a Boolean can take: true or
false.
Example:
int count, x,y; //Declaration
char firstLetterOfName = 'e' ; // Declaration & initialization
Assigning Values to Variables
A variable must be given a value after it has been declared
but before it is used in an expression in two ways:
By using an assignment statement
By using a read statement
Assignment Statement
A simple method of giving value to a variable is through the
assignment statement as follows:
variableName = value;
Example: x = 123, y = -34;
It is possible to assign a value to a variable at the time of
declaration as:
type variableName = value;
Read Statement
It is also to assign value for variables interactively through
the keyboard using the readLine() method which belongs to
the DataInputStream class.
The readLine() method reads the input from the keyboard as
a string which is then converted into the corresponding data
type using the data type wrapper classes.
The wrapper classes are contained in the java.lang
package.
Wrapper classes wrap a value of the primitive types into an
object.
The keywords try and catch are used to handle any errors
that might occur during the reading process.
// A program to read data from the Keyboard
import java.io.DataInputStream;
public class Reading{
public static void main(String[] args)
{
DataInputStream in = new DataInputStream(System.in);
int intNumber=0;
float floatNumber=0.0f;
double doubleNumber=0.0;
String Name=null;
try{
System.out.println("Enter your Name: ");
Name=in.readLine();
System.out.println("Enter an Integer Number: ");
intNumber=Integer.parseInt(in.readLine());
System.out.println("Enter a float Number: ");
floatNumber=Float.parseFloat(in.readLine());
System.out.println("Enter a Double Number Number: ");
doubleNumber=Double.parseDouble(in.readLine());
}
catch(Exception e){}
System.out.println("Hello : "+Name);
System.out.println("The Integer Number is : "+intNumber);
System.out.println("The Float Number is : "+floatNumber);
System.out.println("The Double Number is : "+doubleNumber);
}
}
Scope of Variables
1. Instance Variables: are declared in a class, but outside a method,
constructor or any block.
• are created when an object is created with the use of the key word
'new' and destroyed when the object is destroyed.
• They take different values for each object
2. Class Variables: are also known as static variables, are declared with
the static keyword in a class, but outside a method, constructor or a
block.
• Are global to a class and belong to the entire set of objects that
class creates.
• Only one memory location is created for each class variable.
3. Local Variables: are variables declared and used inside methods.
• Can also be declared inside program blocks that are define between
{ and }.
Control Statements
Generally, the statements inside source programs are
executed from top to bottom, in the order that they appear.
• Control flow statements, however, alter the flow of
execution and provide better control to the programmer on
the flow of execution.
• In Java control statements are categorized into 3 groups:
1. Selection or Decision Making Statements : allow the program to
choose different parts of the execution based on the outcome of an
expression
2. Iteration Statements enable program execution to repeat one or
more statements
3. Jump Statements enable your program to execute in a non-linear
fashion
Selection Statements
• These statements allow us to control the flow of program
execution based on condition.
Java supports 2 selection statements:
if statements
switch statements
If statement:
• It performs a task depending on whether a condition is true or
false.
• It is basically a two-way decision making statement and is used
in conjunction with an expression.
• The if statement may be implemented in different forms
depending on the complexity of conditions to be tested:
Test False
expression
?
True
1. Simple if Statement
An if statement consists of a Boolean expression followed
by one or more statements.
If a case is found whose value matches with the value of the expression,
then the block of the statement(s) that follows the case are executed;
otherwise the default-statement will be executed.
The break statement at the end of each block signals the end of a
particular case and causes an exit from the switch statement.
The ?: (Conditional) Operator
Is useful for making a two-way decisions.
This operator is a combination of ? and : and takes three
operands.
General formula:
conditional expression ? Expression1:expression2;
Example:
for(sum=0, i=1; i<20 && sum<100; ++i)
{
sum=sum+i;
}
Contd…
D. You do not have to fill all three control sections, one or
more sections can be omitted but you must still have two
semicolons.
Example:
int n = 0;
for(; n != 100;) {
System.out.println(++n);
}
Nesting of for loops
You can nest loops of any kind one inside another to any
depth.
Example:
for(int i = 10; i > 0; i--)
{
while (i > 3)
{
if(i == 5){ Inner Outer
break; Loop Loop
}
System.out.println(i);
i--;
}
System.out.println(i*2);
}
Jumps in Loops
Jump statements are used to unconditionally transfer the
program control to another part of the program.
Java has three jump statements: break, continue, and return.
1. The break statement
• A break statement is used to abort the execution of a loop. The
general form of the break statement is given below:
break label;
• It may be used with or without a label.
• When it is used without a label, it aborts the execution of the
innermost switch, for, do, or while statement enclosing the
break statement. When used with a label, the break statement
aborts the execution of any enclosing statement matching the
label.
• A label is an identifier that uniquely identifies a block of code.
Examples
statements.
continue label;
return expression;
index values
Creating an Array
Like any other variables, arrays must be declared and
created in the computer memory before they are used.
Array creation involves three steps:
1. Declare an array Variable
2. Create Memory Locations
3. Put values into the memory locations.
1. Declaration of Arrays
• Arrays in java can be declared in two ways:
i. type arrayname [ ];
ii. type[ ]arrayname;
Example:
int number[];
float slaray[];
float[] marks;
• when creating an array, each element of the array receives
an error.
Contd.
• Java generates an ArrayIndexOutOfBoundsException when
values.
• Each element of the 2-D array is accessed by providing two
indexes for both the column and row of the corresponding element.
For Example,
int value = myarray[1][2];
Contd…
//Application of two-dimensional Array
class MulTable{
final static int ROWS=12;
final static int COLUMNS=12;
public static void main(String [ ]args) {
int pro [ ] [ ]= new int [ROWS][COLUMNS];
int i=0,j=0;
System.out.print("MULTIPLICATION TABLE");
System.out.println(" ");
for (i=1; i<ROWS; i++)
{
for (j=1; j<COLUMNS; j++)
{
pro [i][j]= i * j;
System.out.print(" "+ pro [i][j]);
}
System.out.println(" " );
}
}
}
Strings
• Strings represent a sequence of characters.
• The easiest way to represent a sequence of characters in
Java is by using a character:
char ch[ ]= new char[4];
ch[0] = ‘D’;
ch[1] = ‘a’;
ch[2] = ‘t;
ch[3] = ‘a;
• This is equivalent to String ch=“Hello”;
• Character arrays have the advantage of being able to query
their length.
• But they are not good enough to support the range of
operations we may like to perform on strings.
Contd…
• In Java, strings are class objects and are implemented using
two classes:
String class
StringBuffer
• Once a String object is created it cannot be changed. Strings
are Immutable.
• To get changeable strings use the StringBuffer class.
• A Java string is an instantiated object of the String class.
• Java strings are more reliable and predictable than C++
strings.
• A java string is not a character array and is not NULL
terminated.
Contd…
• In Java, strings are declared and created as follows:
String stringName;
stringName= new String(“String”);
Example:
String firstName;
firstName = new String(“Jhon”);
• The above two statements can be combined as follows:
follows:
String arrayname[] = new String[size];
Example:
String item[]= new String[3];
item[0]= “Orange”;
item[1]= “Banana”;
item[2]= “Apple”;
• It is also possible to assign a string array object to another
17. endsWith(); Tests if this string ends with the specified suffix.
Syntax: public boolean endsWith(String suffix);
Ex: “Figure”.endsWith(“re”); // true
Exercise
1. Consider a two-by-three integer two-dimensional array named array3.
a) Write a statement that declares and creates array3.
b) Write a single statement that sets the elements of array3 in row 1 and
column 2 as zero.
c) Write a series of statements that initializes each element of array3 to
1.
d) Write a nested for statement that initializes each element of array3 to
two.
e) Write a nested for statement that inputs the values for the elements
of array3 from the user.
f) Write a series of statements that determines and prints the smallest
value in array3.
g) Write a statement that displays the elements of the first row of array3.
h) Write a statement that totals the elements of the third column array3.
Contd…
2. Write a Java application program which adds all the numbers ,
except those numbers which are multiples of three, between 1 and
100. (Hint: use continue statement)
3. Write a program which reads the values for two matrices and
displays their product.