Chapter2 Oop
Chapter2 Oop
2-4
Object-oriented Programming
Paradigm 3-4
Object-oriented Analysis (OOA) phase determines
the functionality of the system.
• Unified Modeling Language (UML) helps to create visual models in the system.
• The actual implementation of these visual models is done using an OOP language.
Object-oriented Programming Paradigm 4-4
• An OOP language is based on certain principles that are as follows:
• Object – Represents an entity which possesses certain features and
behaviors.
• Class – Is a template that is used to create objects of that class.
• Abstraction – Is a design technique that focuses only on the essential
features of an entity for a specific problem domain.
• Encapsulation – Is a mechanism that combines data and implementation
details into a single unit called class.
• Inheritance – Enables the developer to extend and reuse the features of
existing classes and create new classes. The new classes are referred to as
derived classes.
• Polymorphism – Is the ability of an object to respond to same message in
different ways.
Concept of an Object 1
• An object represents a real-4-world entity.
• Any tangible or touchable entity in the real-world can be
described as an object.
• Following figure shows some real-world entities:
Concept of an Object 2-4
Window-
Applets based
Application
Java
Applications
JavaBeans Enterprise
Component Components
Server-side
Web
Components
Structure of a Java Class 1-5
• The Java programming language is designed around object-oriented features and
begins with a class design.
• The class represents a template for the objects created or instantiated by the
Java runtime environment.
• The definition of the class is written in a file and is saved with a .java
extension.
Structure of a Java Class 2-5
• Following figure shows the basic structure of a Java class.
package
• Identifies the classes and packages that are used in a Java class.
Structure of a Java Class 4-5
• Helps to narrow down the search performed by the Java compiler by informing it about the
classes and packages.
• Mandatory to import the required classes, before they are used in the Java program.
• Some exceptions wherein the use of import statement is not required are as follows:
• If classes are present in the java.lang package.
• If classes are located in the same package.
• If classes are declared and used along with their package name.
For example, java.text.NumberFormat nf = new
java.text. NumberFormat();
Structure of a Java Class 5-5
class
Variables
Constructors
• Are also methods or functions that are invoked during the creation of an object.
• Used to initialize the objects.
Developing a Java Program on
Windows
• To create, compile, and execute a Java program, perform the following steps:
Create a Java Program 1-4
Build and
Create a Java Compile
execute Java
program .javafile
program
•
Create a Java Program 2-4
• class is a keyword and HelloWorld is the name of the class.
• The entire class definition and its members must be written within the opening
and closing curly braces {}.
• The area between the braces is known as the class body and contains the code
for that public class HelloWorld { class.
• Following
c ode snippet demonstrates a simple Java prograpublic static
void main(String[] args) m: {
System.out.println(“Welcome to the world of Java”);
}
}
where, source - Is one or more file names that end with a .java
extension.
Compile .java File 3-4
• Following table lists some of the options that can be used with the javac
command:
Option Description
-classpath Specifies the location for the imported classes (overrides
Compile
-d
.javaSpecifies
Filethe4-4 the CLASSPATH environment variable)
destination directory for the generated class
• files
-g Prints all debugging information instead of the default line
number and file name
-verbose Generates message while the class is being compiled
-version Displays version information
Sourcepath Specifies the location of the input source file
-help Prints a synopsis of standard options
For javac -d c:\
example, HelloWorld.java will create and save
HelloWorld.class file in the C:\ drive.
• To compile the HelloWorld.java program from the Windows platform, the
user can:
• Click Start menu.
Compile .java File 5-4
• Choose Run.
• Enter the cmd command to display the Command Prompt window.
• Set the drive and directory path to the directory containing .java file. For example, cd
H:\Java.
• Type the command, javac HelloWorld.java and press Enter.
Build and Execute Java Program 1-4
• The JVM is at the heart of the Java programming language.
• It is responsible for executing the .class file or bytecode file.
• The .class file can be executed on any computer or device, that has
the JVM implemented on it.
Build and Execute Java Program 2-4
• Following figure shows the components of JVM involved in the execution of the
compiled bytecode.
The class loader component of JVM loads all the
necessary classes from the runtime libraries required
for execution of the compiled bytecode.
Build and Execute Java Program 3-4
The bytecode verifier then checks the code to
ensure that it adheres to the JVM specification.
• The Java interpreter command, java is used to interpret and run the Java
bytecode. Syntax
Build and Execute Java Program 4-4
• The java.exe java
syntax [option] classname [arguments]] to use
the command is as follows:
where,
classname: Is the name of the class file.
arguments: Is the arguments passed to the main function.
• Select IDE language as English from the drop-down list. Also, select the Platform as
Windows from the drop-down list.
Download and Install NetBeans IDE 4-5
• Click Download under the installer All. The Save As dialog box is opened with netbeans7.1.2-
ml-windows.exe installer file. This installer will support development of all technologies in
the NetBeans IDE.
• Click Save to save the installer file on the local system. • Double-click netbeans-7.1.2-ml-
the installer.
windows.exe to run • To install the 1NetBeans IDE, perform the
following steps:
• Click Next at the Welcome page of the installation wizard. 2
• Click Next in the License Agreement page after reviewing the 3 license agreement, and
select the acceptance check box.
Download and Install NetBeans IDE 5
• At the JUnit License Agreement page, decide if you want to install JUnit-and click 5 4 the
• Select either the default installation directory or specific directory where the NetBeans IDE needs to be
installed. Set the path of the default JDK installation and
5 click Next.
• The GlassFish Server Source Edition 3.1.2 installation page is displayed. You can
6 either select the default location or specify
another location to install the GlassFish Server.
• To install the Apache Tomcat Server, on the installation page, either select the 7 default location
or specify another location and then, click Next.
• The Summary page is opened. The list of components that are to be installed is
8
displayed,
• After the installation is completed, click Finish to complete and close the setup
10 page.
HelloMessageApp program.
Output
window that displays the output of the
Comments in Java
• Are placed in a Java program source file.
• Are used to document the Java program and are not compiled by the compiler.
• Are added as remarks to make the program more readable for the user.
• Are of three types:
• Single-line comments
• Multi-line comments
• Javadoc comments
Syntax
• The syntax for applying the comments is as follows:
// Comment text
/**
* @param args the command line arguments
*/ public static void main(String[]
args) {
}
}
Variables
are used in a Java program to store data that changes during the execution of the
program.
are the basic units of storage in a Java program.
can be declared to store values, such as names, addresses, and salary details.
must be declared before they can be used in the program.
A variable declaration begins with data type and is followed by variable name and a
semicolon.
Syntax
datatype variableName;
where, datatype: Is a valid data type in
Java.
variableName: Is a valid variable name.
Following code snippet demonstrates how to declare variables in a Java program:
...
int rollNumber;
char gender;
...
In the code, the statements declare an integer variable named rollNumber, and a
character variable called gender.
These variables will hold the type of data specified for each of them.
-2
examples of valid and invalid Java variable names:
Literals are constant values assigned to variables directly in the code without
any computation.
Similarly, variable gender is a character variable and is initialized with a character ‘M’.
Assigning Value to a Variable 2-3
The values assigned to the variables are called as literals.
After the variable declaration
Following code snippet demonstrates the initialization of variables after they are
declared:
int rollNumber; // Variable is declared
// Declares three integer variables x, y, and z
int x, y, z;
Instance variables
The state of an object is represented as fields or attributes or instance variables in
the class definition.
Each object created from a class will have its own copy of instance variables.
Following figure shows the instance variables declared in a class template:
Different Types of Variables 2Static variables -3
These are also known as class variables.
Only one copy of static variable is maintained in the memory that is shared by all the
objects belonging to that class.
These fields are declared using the static keyword.
Following figure shows the static variables in a Java program:
Different Types of Variables 3Local variables -3
The variables declared within the blocks or methods of a class are called local variables.
A method represents the behavior of an object.
The local variables are visible within those methods and are not accessible outside them.
A method stores it temporary state in local variables.
There is no special keyword available for declaring a local variable, hence, the position of
declaration of the variable makes it local.
Scope and Lifetime of Variables 1-3
In Java, variables can be declared within a class, method, or within any block. A scope
determines the visibility of variables to other part of the program.
Languages
such as Java
C/C++
Globa Metho
Local Class
l d
Class scope
The variables declared within the class can be instance variables or static variables.
The instance variables are owned by the objects of the class and their existence or
scope depends upon the object creation.
Static variables are shared between the objects and exists for the lifetime of a class.
Scope and Lifetime of Variables 2-3
Method scope
The variables defined within the methods of a class are local variables.
This means memory is allocated for the variables when the method is invoked and
destroyed when the method returns.
The parameter variables are also treated as local variables which means their
existence is till the method execution is completed.
Scope and Lifetime of Variables 3-3
Following figure shows the scope and lifetime of variables x and y defined within the
Scope and Lifetime of Variables 4-3
Java program:
Data Types When you define a variable in Java, you must inform the compiler what kind of a
variable it is.
That is, whether it will be expected to store an integer, a character, or some other
kind of data.
This information tells the compiler how much space to allocate in the memory
depending on the data type of a variable.
Thus, the data types determine the type of data that can be stored in variables and
the operation that can be performed on them.
In Java, data types fall under two categories that are as follows:
Primitive data
types Reference data types
Primitive Data Types The Java programming language provides eight
primitive data types to store data
in Java programs.
A primitive data type, also called built-in data type, stores a single value at a time,
such as a number or a character.
The size of each data type will be same on all machines while executing a Java
program.
The primitive data types are predefined in the Java language and are identified as
reserved words.
• Following figure shows the primitive data types that are broadly grouped into four groups:
Integer Types• The integer data types supported by Java are byte, short, int,
and long.
• These data type can store signed integer values.
• Signed integers are those integers, which are capable of representing positive as well as negative
numbers, such as -40.
• Java does not provide support for unsigned integers.
• Following table lists the details about the integer data types:
byte short int long
A signed 8-bit type. A signed 16-bit type. Signed 32-bit type. Signed 64-bit type.
Range:
9,223,372,036,854,775,8
Range: -32,768 to Range: -2,147,483,648
Range: -128 to 127 08 to
32,767 to 2,147,483,647
9,223,372,036,854,775,8
07
Used to store Used to store the total Used to store very large
Useful when
smaller numbers, for salary being paid to all values such as
working with
example, employee the employees of the population of a
raw binary data.
number. company. country.
Keyword: byte Keyword: short Keyword: int Keyword: long
...
String str = “A String Data”;
...
The statement, String str creates an String object and is not of a primitive data type.
When you enclose a string value within double quotes, the Java runtime environment
automatically creates an object of String type.
Also, once the String variable is created with a value ‘A String Data’, it will remain
constant and you cannot change the value of the variable within the program.
However, initializing string variable with new value creates a new String object.
Following table lists and describes the three reference data types:
Data Type Description
It is a collection of several items of the same data type. For
Array
example, names of students in a class can be stored in an array.
Integer Literals
Integer literals are used to represent an int value, which in Java is a 32-bit integer
value.
Integers literals can be expressed as:
Literals 2
Decimal values have a base of 10 and consist of numbers from 0 through 9. For
example, int decNum = 56;.
Hexadecimal values have a base of 16 and consist of numbers 0 through 9 and letters
A through F. For example, int hexNum = 0X1c;.
Binary values have a base of 2 and consist of numbers 0 and 1. Java SE 7 supports -
4 binary literals. For example, int binNum = 0b0010;.
An integer literal can also be assigned to other integer types, such as byte or long.
When a literal value is assigned to a byte or short variable, no error is generated, if the
literal value is within the range of the target type.
Literals 3
Integer numbers can be represented with an optional uppercase character (‘L’) or
lowercase character (‘l’) at the end.
This will inform the computer to treat that number as a long (64-bit) integer.
Floating-point Literals
-4
Exponent is indicated by an E or e followed by a decimal number, which can be
e+208, 7.436E6, 23763E-05, and so on.
positive or negative. For example,
Type suffixD, d, F, or f.
Literals 4
Floating-point literals in Java default to double precision.
A float literal is represented by F or f appended to the value, and a double literal is
represented by D or d.
Boolean Literals
Boolean literals are simple and have only two logical values - true and false.
These values do not convert into any numerical representation.
A true boolean literal in Java is not equal to one, nor does the false literal equals to
zero.
They can only be assigned to boolean variables or used in expressions with boolean
operators.
Character Literals -4
Character literals are enclosed in single quotes.
All the visible ASCII characters can be directly enclosed within quotes, such as ‘g’, ‘$’,
and ‘z’.
Literals 5
Single characters that cannot be enclosed within single quotes are used with escape
sequence.
Null Literals
When an object is created, a certain amount of memory is allocated for that object.
The starting address of the allocated memory is stored in an object variable, that is, a
reference variable.
However, at times, it is not desirable for the reference variable to refer that object.
In such a case, the reference variable is assigned the literal value null. For example,
Car toyota = null;.
String Literals
In the floating
-point literal, underscore cannot be placed adjacent to a
decimal point.
1234_9876_5012_5454L Valid
Invalid, as underscore placed at the
_8976
beginning
3.14_15F Valid
0b11010000_11110000_00001111 Valid
Invalid, as underscore is adjacent to a
3_.14_15F
decimal point
Invalid, an underscore is placed after the
0x_78
hexadecimal
Escape Sequences 1-3
An escape sequence is a special sequence of characters that is used to represent characters,
which cannot be entered directly into a string.
• For example, to include tab spaces or a new line character in a line or to include
characters which otherwise have a different notation in a Java program (\ or “),
escape sequences are used.
An escape sequence begins with a backslash character (\), which indicates that the character
(s) that follows should be treated in a special way.
The output displayed by Java can be formatted with the help of escape sequence characters.
Syntax
final data-type variable-name = value;
Constants and Enumerations 2-5
where, final: Is a keyword and denotes that the variable is declared as a
constant.
Following code snippet demonstrates the code that declares the constant variables:
// Calculates the value for the area variable
area = PI * radius * radius;
System.out.println(“Area of the circle is: “ + area);
}
}
In the code, a constant variable PI is assigned the value 3.14159, which is a fixed value.
The output of the code is shown in the following figure:
Constants and Enumerations 3-5
Java SE 5.0 introduced enumerations.
Unlike C++, where enumeration was a list of named integer constants, in Java,
enumeration is a class type.
Syntax
enum enum-name {
constant1, constant2, . . . , constantN
}
Constants and Enumerations 4-5
• Though, enumeration is a class in Java, you do not use new operator to instantiate it.
• Instead, declare a variable of type enumeration to use it in the Java program.
• This is similar to using primitive data types.
• The enumeration is mostly used with decision-making constructs, such as switch-case
statement.
• Following code snippet demonstrates the declaration of enumeration in a Java
program:
Constants and Enumerations 5-5
public class EnumDirection {
/**
* Declares an enumeration
*/ enum
Direction {
East, West, North, South
}
/**
* @param args the command line arguments
*/ public static void main(String[]
args) {
// Declares a variable of type Direction
Direction direction;
print() and
println()
printf()
format()
• The methods uses the appropriate toString() method for conversion of the values.
• These
methods public class DisplaySum {
can also /**
* @param args the command line arguments
*/ public static void main(String[]
args) { “ + sum + “.”); int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
System.out.print(“The sum of “);
System.out.print(num1);
System.out.print(“ and “);
System.out.print(num2);
System.out.print(“ is “);
System.out.print(sum);
be used to print mixture combination of strings and numeric values as strings on the standard
output.
• Following code snippet demonstrates the use of print() and println()
methods:
System.out.println(“.”);
int num3 = 2;
sum = num1 + num2 + num3;
System.out.println(“The sum of “ + num1 + “, “ + num2 + “ and “ +
num3 + “ is
}
}
Syntax
%[arg_index$] [flags] [width] [.precision] conversion character
where, arg_index: Is an integer followed by a $ symbol. The integer indicates
that the argument should be printed in the mentioned position.
flags: Is a set of characters that format the output result. There are different flags
available in Java.
‘format()’ Method 2-3
Following table lists some of the flags available in Java:
-3 the keyboard.
It breaks the input into tokens and translates individual tokens depending on their
data type.
To use the Scanner class, pass the InputStream object to the constructor as follows:
Formatted Input 2
Scanner input = new Scanner(System.in);
Here, input is an object of Scanner class and System.in is an input stream object.
Following table lists the different methods of the Scanner class that can be used to
accept numerical values from the user:
Following code snippet demonstrates the -3 Scanner class methods and how
they can be used to accept values from the user:
public class FormattedInput {
/**
* @param args the command line arguments
*/ public static void main(String[]
args) {
3
The output of the code is shown in the following figure:
Formatted Input 5
Operators
Operators are set of symbols used to indicate the kind of operation to be
performed on data.
Consider the expression:
Z = X + Y;
Here, • is called the Operator and the operation performed is
+
addition.
-2
operator, there are combined operators that allow
you to use a value in an expression, and then, set its value to the result of
that expression. X = 3;
X += 5;
The second statement stores the value 8, the meaning of the statement is that X = X +
5.
Following code snippet demonstrates the use of assignment operators:
...
x = 10; // Assigns the value 10 to variable
x x += 5; // Increments the value of x by 5
x -= 5; // Decrements the value of x by 5 x
*= 5; // Multiplies the value of x by 5 x /=
2; // Divides the value of x by 2
x %= 2; // Divides the value of x by 2 and the remainder is returned
Arithmetic Operators Arithmetic operators manipulate numeric data
The prefix version (++variable) will increment the value before evaluating.
The postfix version (variable++) will first evaluate and then, increment the original
value.
Following code snippet demonstrates the use of unary operators:
...
int i = 5; int j = i++; // i=6, j=5 int k = ++i; //i=6,k=6 i = -
i ; //now i is -6 boolean result = false; //result is false
result = !result; //now result is true
…
Conditional Operators 1
The conditional operators test the
-2
relationship between two operands.
boolean expressions.
These operators exhibit short-circuit behavior, which means that the second operand is
evaluated only if required.
public class TestLogicalOperators {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{ int first = 10; int second = 20;
-2
data.
As someCondition variable evaluates to true, the value of value1 variable is assigned to the
result variable.
Thus, the program prints 10 on the console.
Operator Precedence 1• Expressions that are written generally
consist of several operators. -2
• The rules of precedence decide the order in which each operator is evaluated in any
given expression.
• Following table lists the order of precedence of operators from highest to lowest in
which operators are evaluated in Java:
•True
7
Operator • When two operators with the same precedence appear in an expression,
the expression Associativity 1-2
is evaluated, according to its associativity.
• For example, in Java the - operator has left-associativity and x - y - z is
interpreted as (x - y) - z, and = has right-associativity and x = y = z is
interpreted as x = (y = z).
• Following table shows the Java operators and their associativity:
Operator Consider the following expression: Associativity 2-2
2+10+4-5*(7-1)
• The ‘*’ has higher precedence than any other operator in the equation.
• However, as7-1 is enclosed in parenthesis, it is evaluated first.
1 • 2+10+4-5*6
• Next, *
‘ ’ is the operator with the highest precedence.
• Since there are no more parentheses, it is evaluated according to the rules.
2 • 2+10+4-30
• As ‘+’ and -
‘ ‘ have the same precedence, theassociativity
left works out.
• 12+4-30
3
Type Casting Type conversion or typecasting refers to changing an entity of one data type
into another.
• For instance, values from a more limited set, such as integers, can be stored in a more
compact format.
• There are two types of conversion:
known as casting.
Explicit type conversion can also be achieved with
Implicit Type Casting 2• The primitive numeric data types that can be
implicitly cast are as follows:-3
byte (8 bits) to short, int, long, float, double
Syntax
(target data type) value;
Following figure shows the explicit type casting of data types:
Explicit Casting 2• Following code snippet adds a -2float value to an
int and stores the result as an
integer:
...
float a = 21.3476f; int b = (int) a + 5;
...
The float value in a is converted into an integer value 21.
It is then, added to 5, and the resulting value, 26, is stored in b.
This type of conversion is known as truncation.
The fractional component is lost when a floating-point is assigned to an integer type,
resulting in the loss of precision.
Summary Variables store values required in the program and should be declared
before they are used. In Java, variables can be declared within a class, method, or
within any block.
Data types determine the type of values that can be stored in a variable and the
operations that can be performed on them. Data types in Java are divided mainly into
primitive types and reference types.
A literal signifies a value assigned to a variable in the Java program. Java SE 7 supports
the use of the underscore characters (_) between the digits of a numeric literal.
The output of the Java program can be formatted using three ways: print() and
println(), printf(), format(). Similarly, the Scanner class allows the user to read or accept
values of various data types from the keyboard.
Operators are symbols that help to manipulate or perform some sort of function on
data.
Parentheses are used to change the order in which an expression is evaluated.
The type casting feature helps in converting a certain data type to another data type.
The type casting can be automatic or manual and should follow the rules for
promotion.