Java Object-Oriented Programming Basics
Java Object-Oriented Programming Basics
Module-1
Syllabus:
An Overview of Java: Object-Oriented Programming (Two Paradigms,
Abstraction, The Three OOP Principles), Using Blocks of Code, Lexical
Issues (Whitespace, Identifiers, Literals, Comments, Separators, The Java
Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers,
Floating-Point Types, Characters, Booleans), Variables, Type Conversion
and Casting, Automatic Type Promotion in Expressions, Arrays,
Introducing Type Inference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean Logical
Operators, The Assignment Operator, The ? Operator, Operator
Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional
switch), Iteration Statements (while, do-while, for, The For-Each Version of
the for Loop, Local Variable Type Inference in a for Loop, Nested Loops),
Jump Statements (Using break, Using continue, return).
Chapter 2, 3, 4, 5
1. Process-oriented model.
● This approach characterizes a program as a series of linear steps
(that is, code).
● The process-oriented model can be thought of as code acting on
data.
● Procedural languages such as C use this model to considerable
success.
● This approach cannot be used if programs grow larger and complex.
2. Object-oriented programming.
● Object-oriented programming organizes a program around its data
(that is, objects) and a set of well-defined interfaces to that data.
● An object-oriented program can be characterized as data controlling
access to code.
Abstraction
Inheritance
● Inheritance is the process by which one object acquires the properties
of another object.
● This is important because it supports the concept of hierarchical
classification.
● Knowledge is made manageable by hierarchical (that is, top-down)
classifications.
● For example, a Golden Retriever is part of the classification dog, which
in turn is part of the mammal class, which is under the larger class
animal.
● Without the use of hierarchies, each object would need to define all its
characteristics explicitly.
● However, by use of inheritance, an object need only define those
qualities that make it unique within its class. It can inherit its general
attributes from its parent.
Polymorphism (many forms)
● Polymorphism is a feature that allows one interface to be used for a
general class of actions.
● The specific action is determined by the exact nature of the situation.
● Extending the dog analogy, a dog’s sense of smell is polymorphic. If
the dog smells a cat, it will bark and run after it. If the dog smells its
food, it will salivate and run to its bowl. The same sense of smell is at
work in both situations. The difference is what is being smelled, that is,
the type of data being operated upon by the dog’s nose!
● This same general concept can be implemented in Java as it applies to
methods within a Java program.
Comments:
● The contents of a comment are ignored by the compiler.
● A comment describes or explains the operation of the program to
anyone who is reading its source code.
● Example: /* Simple Java Program */
● The keyword void simply tells the compiler that main( ) does not
return a value.
● String[ ] args declares a parameter named args, which is an array of
instances of the class String.
[Link]("Hello World");
● This line outputs the string "Hello World." followed by a new line on the
screen. Output is actually accomplished by the built-in println( )
method. In this case, println( ) displays the string which is passed to
it.
Control Statements
The if Statement
● The Java if statement determines the flow of execution based on
whether some condition is true or false.
● Its syntax is here:
if (condition) statement;
● Here, condition is a Boolean expression.
● If condition is true, then the statement is executed. If condition is false,
then the statement is bypassed.
● Example:
If (num < 100) [Link]("num is less than 100");
● In this case, if num contains a value that is less than 100, the
conditional expression is true, and println( ) will execute. If num
contains a value greater than or equal to 100, then the println( )
method is bypassed.
Java relational operators which may be used in a conditional
expression.
Operator Meaning
< Less than
> Greater than
== Equal to
Blocks of Code
● Java allows two or more statements to be grouped into blocks of code,
also called code blocks.
● This is done by enclosing the statements between opening and
closing curly braces.
● Once a block of code has been created, it becomes a logical unit that
can be used any place that a single statement can.
● A block can be a target for Java’s if and for statements.
● Block for the if statement:
if(x < y)
{ // begin a block
x = y;
y = 0;
} // end of block
Lexical Issues
● Java programs are a collection of whitespaces, identifiers, literals,
comments, operators, separators, and keywords.
Whitespace
● Java is a free-form language.
● This means that you do not need to follow any special indentation
rules.
● In Java, whitespace includes a space, tab, newline, or form feed.
Identifiers (Variables)
● Identifiers are used to name things, such as classes, variables, and
methods.
● An identifier may be any sequence of uppercase and lowercase letters,
numbers.
Literals (Constants)
● A constant value in Java is created by using a literal representation of
it.
For example:
100 98.6 ‘X’ “This is a test”
Comments in Java
● single-line : // single line comment
● multiline : / * This is multiline comment */
● documentation comment : /** Documentation Comment */
This type of comment is used to produce an HTML file that documents
your program.
Separators
● The most commonly used separator in Java is the semicolon.
● All separators are shown in the following table:
byte
● The smallest integer type is byte.
● This is a signed 8-bit type that has a range from –128 to 127.
● Declaration : byte x, y ;
Floating-Point Types
● Floating-point numbers, also known as real numbers,
● Used when evaluating expressions that require fractional precision.
● Width and ranges are shown here:
float
● The type float specifies a single-precision value that uses 32 bits of
storage.
● For example, float can be useful when representing dollars and cents.
● Declaration : float hightemp, lowtemp;
double
● Double precision, uses 64 bits to store a value.
● double is the best choice, when need to maintain accuracy over many
iterative calculations, or manipulate large-valued numbers.
Characters
● In Java, the data type used to store characters is char.
● Java uses Unicode to represent characters.
● In Java char is a 16-bit type. The range of a char is 0 to 65,535.
● There are no negative chars.
Booleans
● boolean used for logical values.
● It can have only one of two possible values, true or false.
Floating-Point Literals
● Decimal values with a fractional component.
● They can be expressed in either standard or scientific notation.
Boolean Literals
● Only two logical values that a boolean value can have, true and
false.
● The values of true and false do not convert into any numerical
representation.
Character Literals
● Java uses the Unicode character set.
● A literal character is represented inside a pair of single quotes.
● All of the visible ASCII characters can be directly entered inside the
quotes, such as 'a', 'z', and '@'.
● For characters that are impossible to enter directly, there are several
escape sequences that allow you to enter the character you need, such
as ' \' ' for the single-quote character itself and ' \n' for the newline
character.
String Literals
● String literals are sequence of characters between a pair of double
quotes.
● Examples: "Hello World"
"two\nlines"
“\"This is in quotes\""
Variables
● Variable is a basic unit of storage.
● A variable is defined by the combination of an identifier, a type, and an
optional initializer.
Declaring a variable
● In Java, all variables must be declared before they can be used.
The syntax :
type identifier [ = value ][, identifier [= value ] … ] ;
Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and
f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization
● Java allows variables to be initialized dynamically, using any expression
valid at the time the variable is declared.
● For example, Program to computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:
Lifetime of a variable
● Variables are created when their scope is entered, and destroyed when
their scope is left.
● This means that a variable will not hold its value once it has gone out
of scope.
● Also, a variable declared within a block will lose its value when the
block is left.
● Thus, the lifetime of a variable is confined to its scope.
Example:
Arrays
● An array is a group of data items of same type under a common name.
● Arrays of any type can be created and may have one or more
dimensions.
● A specific element in an array is accessed by its index.
● Arrays helps to group related information.
One-Dimensional Arrays
● A one-dimensional array is, essentially, a list of data items of same
type.
● Creation of Array in Java is a two steps process as described below:
● Syntax to create an array in java :
type[ ] var-name;
Example :
int[ ] month_days ;
● Above declaration shows the fact that month_days is an array
variable, no array actually exists.
● To link month_days with an actual, physical array of integers, you
must allocate one using new and assign it to month_days.
● new is a special operator that allocates memory.
● The syntax of new as it applies to one-dimensional arrays appears as
follows:
array-var = new type [size];
Example :
month_days = new int[12];
● All elements in the array will be initialized to zero.
● We can access a specific element in the array by specifying its index
within square brackets.
● All array indexes start at zero.
For example, (1) Assign the value 28 to the second element of
month_days:
month_days[1] = 28;
(2) Displays the value stored at index 3:
[Link](month_days[3]);
// Demonstrate a one-dimensional array.
public class Array
{
public static void main(String[] args)
{
int[ ] month_days;
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
[Link]("April has " + month_days[3] + " days.");
}
}
Array Initialisation:
//Another Example:
// Program to find the average of a set of numbers.
public class Average
{
public static void main(String[] args)
{
double[ ] nums = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
Multidimensional Arrays:
Output :
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Output:
type var-name[ ];
● Here, the square brackets follow the array variable name, and not the
type specifier.
● For example, the following two declarations are equivalent:
Example:
Operators
Most of java’s operators can be divided into the following four groups:
arithmetic, bitwise, relational, and logical.
Arithmetic Operators
Example:
Output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
Output:
x mod 10 = 2
y mod 10 = 2.25
a = a + 4;
a += 4;
● Advantages : They save you a bit of typing, and in some cases, they
are more efficient than are their equivalent long forms.
Example:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++;
● These operators can appear both in postfix form and prefix form.
// Demonstrate ++.
class IncDec
{
public static void main(String[] args)
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}
Output:
a=2
b=3
c=4
d=1
The Bitwise Operators
● Bitwise operators that can be applied to the integer types: long, int,
short, char, and byte.
● These operators act upon the individual bits of their operands.
For example, the number 42, which has the following bit pattern:
00101010
becomes
11010101
after the NOT operator is applied
The Bitwise AND:
● The left shift operator, <<, shifts all of the bits in a value to the left a
specified number of times.
● Each left shift has the effect of doubling the original value
Output:
Original value of a: 64
i and b: 256 0
// Right shifting
class RightShift
{
public static void main(String[] args)
{
int a = 32; // 0010 0000
a = a >> 2; // 0000 1000
[Link](a);
Relational Operators:
Output:
Example :
int x, y, z;
x = 100;
y = z = 100; // set x, y, and z to 100
The ? Operator
Example :
x = (y == 0) ? 0 : y / 2;
// Demonstrate ?.
class Ternary
{
public static void main(String[] args)
{
int i, k;
i = 10;
k =( i < 0 ) ? -i : i;
[Link]("Absolute value of "+ i + " is " + k);
}
}
Output:
Absolute value of 10 is 10
Operator Precedence
● Operator precedence refers to the rules that control the order in which
operations are performed in an expression without parentheses.
● Parentheses raise the precedence of the operations that are inside
them. This is often necessary to obtain the result you desire.
Control Statements
● Control statements are used to create special feature like logical tests,
loops and branching.
● Java has 3 types of control statements: selection, iteration, and jump.
● Selection (Conditional) statements allow your program to choose
different paths of execution based upon the outcome of an expression.
● Iteration(Looping) statements enable program execution to repeat one
or more statements. (loop)
● Jump statements allow your program to execute in a nonlinear fashion.
Selection Statements
if , if-else, switch
if
Syntax:
if (condition)
statement1;
else
statement2;
● Here, each statement may be a single statement, or a compound
statement enclosed in curly braces (that is, a block).
● The condition is any expression that returns a Boolean value.
● The else clause is optional.
● If the condition is true, then statement1 is executed. Otherwise,
statement2 (if it exists) is executed.
Nested ifs
Example:
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d;
else
a = c;
}
else
a = d;
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
Output:
April is in the Spring.
Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
The switch statement works like this: The value of the expression is
compared
with each of the values in the case statements. If a match is found, the
code sequence following that case statement is executed. If none of the
constants matches the value of the expression, then the default
statement is executed.
}
}
}
}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
[Link]("April is in the " + season + ".");
}
}
While
● It repeats a statement or block while its controlling expression is true.
Syntax:
while(condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition
becomes false, control passes to the next line of code immediately
following the loop.
{
public static void main(String[] args)
{
int n = 10;
while(n > 0)
{
[Link]("tick " + n);
n--;
}
}
}
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
do-while
Syntax:
do {
// body of loop
} while (condition);
class Menu
{
public static void main(String[] args)
{
int choice;
Scanner sc = new Scanner([Link]);
do
{
[Link]("Help on:....... ");
[Link](" 1. Withdraw Money");
[Link](" 2. Deposit Money");
[Link](" 3. Balance Print");
[Link](" 4. New Account");
[Link](" 5. Update Account");
[Link]("ENTER YOUR CHOICE:");
choice = [Link]();
} while( choice < 1 || choice > 5);
switch(choice)
{
case 1:
[Link]("Spend your money wisely");
break;
case 2:
[Link]("Good Job, save your money\
n");
break;
case 3:
[Link]("Take a print\n");
break;
case 4:
[Link]("Visit the Bank to open new
account");
break;
case 5:
[Link]("Visit the Bank to upadte ");
break;
}
}
}
for
Syntax:
// body
}
{
isPrime = false;
break;
}
}
if(isPrime)
[Link]("Prime");
else
[Link]("Not Prime");
}
}
For example
In the example below, the for loop continues to run until the boolean
variable done is set to true. It does not test the value of i.
for( ; ; )
{
// ...
}
Syntax:
● The following fragment uses a traditional for loop to compute the sum
of the values in an array:
int[ ] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;
for(int x : nums)
{
[Link]("Value is: " + x);
sum += x;
}
[Link]("Summation: " + sum);
}
}
class ForEach3
{
public static void main(String[] args)
{
int sum = 0;
int[ ][ ] nums = new int[3][5];
for(int[ ] x : nums)
{
for(int y : x)
{
[Link]("Value is: " + y);
sum += y;
}
}
[Link]("Summation: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90
{
int[ ] nums = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
for(int x : nums)
{
if(x == val)
{
found = true;
break;
}
}
if(found)
[Link]("Value found!");
}
}
------
Nested Loops
Output:
Jump Statements
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
● When used inside a set of nested loops, the break statement will only
break out of the innermost loop.
● Java does not have a goto statement, but the goto can be useful when
you are exiting from a deeply nested set of loops. To handle such
situations, Java defines an expanded form of the break statement
called labelled break. By using this form of break, you can, break
out of one or more blocks of code.
● We can specify precisely where execution will resume, because this
form of break works with a label.
Syntax:
break label;
Output:
Using continue
● Continue is used to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration.
● In while and do-while loops, a continue statement causes control to be
transferred directly to the conditional expression that controls the loop.
● In a for loop, control goes first to the iteration portion of the for
statement and
then to the conditional expression.
● For all three loops, any intermediate code is bypassed.
// Demonstrate continue.
class Continue
{
public static void main(String[] args)
{
for(int i=0; i<10; i++)
{
[Link](i + " ");
if (i%2 == 0)
continue;
[Link]("");
}
}
}
Output:
0 1
2 3
4 5
6 7
8 9
}
[Link](" " + (i * j));
}
}
[Link]();
}
}
Output:
return
// Demonstrate return.
class Return
{
public static void main(String[] args)
{
boolean t = true;
[Link]("Before the return.");
if(t)
return; // return to caller
[Link]("This won't execute.");
}
}
Output:
Review Questions:
Important programs
Develop java programs to convert celcius temperature to
fahrenheit
F=(C×59)+32
import [Link];
Output:
if ([Link] < 3)
{
[Link]("Usage: java MatrixAddition <rows> <cols>
<matrix1 elements> <matrix2 elements>");
return;
}
if ([Link] != 2 + 2 * totalElements)
return;
}
{
matrix1[i][j] = [Link](args[index++]);
}
}
[Link]();
}
}
}
Output
Matrix 1 = [1, 2, 3, 4]
Matrix 2 = [5, 6, 7, 8]