Bsc20 Java e Content U Sample
Bsc20 Java e Content U Sample
E-Content
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
Unit-1:
Introduction to OOP, procedural programming language and object-oriented language,
principles of OOP, applications of OOP, history of java, java features, JVM, program structure.
Variables, primitive data types, identifiers, literals, operators, expressions, precedence rules
and associativity, primitive type conversion and casting, flow of control.
Introduction to OOP
Object-oriented programming (OOP) is one of the most interesting and useful innovations in
software development. OOP has strong historical roots in programming paradigms and
practices. It addresses the problems commonly known as the software crisis. Software have
become inherently complex which has led to many problems within the development of large
software projects. Many software have failed in the past.
The term ‘software crisis’ describes software failure in terms of Exceeding software budget
Software not meeting clients’ requirements Bugs in the software OOP is a programming
paradigm which deals with the concepts of object to build programs and software applications.
It is modeled around the real world. The world we live in is full of objects. Every object has a
well-defined identity, attributes, and behavior. Objects exhibit the same behavior in
programming. The features of object-oriented programming also map closely to the real-world
features like inheritance, abstraction, encapsulation, and polymorphism.
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
objects: Creator objects: Humans, Employees, Students, Animal Physical objects: Car, Bus,
Plane Objects in computer system: Monitor, Keyboard, Mouse, CPU, Memory
1.3.3 Abstraction Can you classify the following items? Elephant CD player Television
Table Chair Tiger How many classes do you identify here? The obvious answer anybody
would give is three, i.e., Animal, Furniture, and Electronic items. But how do you come to this
conclusion? Well, we grouped similar items like Elephant and Tiger and focused on the generic
characteristics rather than specific characteristics. This is called abstraction. Everything in this
world can be classified as living or non-living and that would be the highest level of
abstraction.
Another well-known analogy for abstraction is a car. We drive cars without knowing the
internal details about how the engine works and how the car stops on applying brakes. We are
happy with the abstraction provided to us, e.g., brakes, steering, etc. and we interact with
them. In real life, human beings manage complexity by abstracting details away. In
programming, we manage complexity by concentrating only on the essential characteristics
and suppressing implementation details.
1.3.4 Inheritance
Inheritance is the way to adopt the characteristics of one class into another class. Here we
have two types of classes: base class and subclass. There exists a parent–child relationship
among the classes. When a class inherits another class, it has all the properties of the base
class and it adds some new properties of its own. We can categorize vehicles into car, bus,
scooter, ships, planes, etc. The class of animals can be divided into mammals, amphibians,
birds, and so on. The principle of dividing a class into subclass is that each subclass shares
common characteristics with the class from where they are inherited or derived. Cars,
scooters, planes, and ships all have an engine and a speedometer. These are the
characteristics of vehicles. Each subclass has its own characteristic feature, e.g., motorcycles
have disk braking system, while planes have hydraulic braking system. A car can run only on
the surface, while a plane can fly in air and a ship sails over water
Inheritance aids in reusability. When we create a class, it can be distributed to other
programmers which they can use in their programs. This is called reusability. Suppose
someone wants to make a program for a calculator, he can use a predefined class for
arithmetic operations, and then he need not define all the methods for these operations. This
is similar to using library functions in procedural language. In OOP, this can be done using the
inheritance feature. A programmer can use a base class with or without modifying it. He can
derive a child class from a parent class and then add some additional features to his class.
1.3.5 Encapsulation Encapsulation is one of the features of object-oriented methodology. The
process of binding the data procedures into objects to hide them from the outside world is
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
called encapsulation (see Fig. 1.2). It provides us the power to restrict anyone from directly
altering the data. Encapsulation is also known as data hiding. An access to the data has to be
through the methods of the class. The data is hidden from the outside world and as a result, it
is protected. The details that are not useful for other objects should be hidden from them. This
is called encapsulation. For example, an object that does the calculation must provide an
interface to obtain the result. However, the internal coding used to calculate need not be
made available to the requesting object. Method Accessing data Method Data Method Fig. 1.2
Diagrammatic Illustration of a C
1.3.6 Polymorphism
Polymorphism simply means many forms. It can be defined as the same thing being used in
different forms. For example, there are certain bacteria that exhibit in more than one
morphological form. In programming, polymorphism is of two types: compile-time and
runtime polymorphism. Runtime polymorphism, also known as dynamic binding or late
binding, is used to determine which method to invoke at runtime. The binding of method call
to its method is done at runtime and hence the term late binding is used. In case of compile-
time polymorphism, the compiler determines which method (from all the overloaded
methods) will be executed. The binding of method call to the method is done at compile time.
So the decision is made early and hence the term early binding. Compile-time polymorphism in
Java is implemented by overloading and runtime polymorphism by overriding. In overloading,
a method has the same name with different signatures. (A signature is the list of formal
argument that is passed to the method.) In overriding, a method is defined in subclass with the
same name and same signature as that of parent class. This distinction between compile-time
and runtime polymorphism is of method invocation. Compile-time polymorphism is also
implemented by operator overloading which is a feature present in C++ but not in Java.
Operator overloading allows the user to define new meanings for that operator so that it can
be used in different ways. The operator (+) in Java is however an exception as it can be used
for addition of two integers as well as concatenation of two strings or an integer with a string.
This operator is overloaded by the language itself and the Java programmer cannot overload
any operator.
PROCEDURAL LANGUAGE VS OOP Table 1.1 highlights some of the major differences between
procedural and object-oriented programming languages. Table 1.1 Procedural Language vs
OOP Procedural Language Separate data from functions that operate on them. OOP
Encapsulate data and methods in a class. Not suitable for defi ning abstract types.
Debugging is diffi cult. Diffi cult to implement change. Not suitable for larger programs and
applications. Analysis and design not so easy. Faster. Less fl exible. Data and procedure
based. Less reusable. Only data and procedures are there. Use top-down approach.
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
Suitable for defi ning abstract types. Debugging is easier. Easier to manage and implement
change. Suitable for larger programs and applications. Analysis and design made easier.
Slower. Highly fl exible. Object oriented. More reusable. Inheritance, encapsulation,
and polymorphism are the key features. Use bottom-up approach. Only a function call
another. Example: C, Basic, FORTRAN. Object communication is there. Example: JAVA, C+
+, VB.NET, C#.NET.
APPLICATIONS OF OOP
The basic thought behind object-oriented language is to make an object by combining data
and functions as a single unit and then operate on that data. In procedural approach, the focus
is on business process and the data needed to support the process. For example, in the last
decade, a problem bothered every programmer, popularly known as the Y2K problem.
Everybody related to the computer industry was afraid of what will happen past midnight 31
December 1999. The problem arises due to the writing convention of the year attribute. In
early programming days, a programmer wrote a year in two digits, so there was a problem to
distinguish the year 1900 from 2000 because if we write only the last two digits of a year, the
computer cannot differentiate between the two. Nobody perceived this problem and used the
date and year code as and when required, thus aggravating the problem. The solution to this
problem was to analyze multiple lines of codes everywhere and change the year to four digits
rather than two. It seems simple to change the state variable of year but analyzing a code of
several thousands of lines to find how many times you have used date in your code is not an
easy task. If object-oriented programming language had been used, we could have created a
Date class with day, month, and year attributes in it. Wherever the date functionality would be
required, a Date object would be created and used. At a later point of time, if a change is
required, for example, the year of Date class needs to be changed to four digits, then this
change would be incorporated in the class only and this change would automatically be
reflected in all the objects of the Date class whenever they are created and used. So, the
change would have to be done at one place only, i.e., the class and wherever the objects of
the class are being used, the changes would be reflected automatically. There is no need to
analyze the whole code and change it. In OOP, we access data with the help of objects, so it is
very easy to overcome a problem without modifying the whole system. Likewise, OOP is used
in various fields, such as Real-time systems Neural networks Artificial intelligence
Expert systems
HISTORY OF JAVA
It is often believed that the Java was developed specifically for the World Wide Web. Java as it
was initially developed was intended for the Web. However, it was improved to be a standard
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
programming language for the Internet application. Bill Joy, the Vice President at Sun Micro
systems, was thought to be the main person to conceive the idea of a programming language
that later became Java. In late 1970s, Bill Joy wanted to design a language that could contain
the best features of languages like MESA and C. He found that C++ was inefficient for rewriting
Unix operating system. In 1991, it was this desire to invent a better programming tool that
propelled Joy in the direction of Sun’s mammoth project called as the ‘ Stealth Project.’ This
name was given by Scott McNealy, Sun’s president. In January 1991, a formal team of persons
like Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton (formerly the project leader of
Sun’s Open Windows user environment), and several other individuals met in Aspen, Colorado
for the first time to plan for the Stealth Project. Stealth Project was all about developing
consumer electronic devices that could all be centrally controlled and programmed from a
handheld remote control like device. James Gosling was made responsible for suggesting a
proper programming language for the project. Initially he thought of using C++, but soon after
was convinced about the inadequacy of C++ for this particular project. He took the first step
towards the development of an independent language that would fit the project objectives by
extending and modifying C++. The idea of naming the language as ‘Oak’ struck Gosling while
staring at an oak tree outside his office window. Unfortunately, this name had already been
patented by some other programming language. Owing to the fear of copyright violation, the
name ‘Oak’ was dropped. The team struggled to find a proper name for the language for many
days. After so many brainstorming sessions, one day finally a thought struck their mind during
a trip to the local coffee shop as recalled by Gosling. The term ‘Java’ in USA is generally a slang
used for coffee. Java is also the name of a coffee produced on the islands of Java in Indonesia.
There are some other views also towards the naming convention used for naming the
language as Java. One of it speculates that the name Java came from several individuals
involved in the project: James Gosling, Arthur Van Goff, Andy Bechtolsheim.
JAVA FEATURES
2.6.1 Platform Independence Java was designed not only to be cross-platform in source form,
like the previous languages (C, C++), but also in compiled binary form. To achieve this, Java is
compiled to an intermediate form called the bytecode (see Figs 2.3 and 2.4). This bytecode is
a platform-independent code that is read by a special native program called the Java
interpreter that executes the corresponding native machine instructions. The Java compiler is
also written in Java. The bytecodes are precisely defined to remain uniform on all platforms.
The second important part of making Java cross-platform is the uniform definition of
architecture-dependent constructs. In contradiction to other languages, integers in Java are
always four bytes long, and floating point variables follow the IEEE floating point arithmetic
754 standard. You don’t have to worry about the meaning of any type, as it is not going to
change when you transit between different architectures, e.g., Pentium to Sparc. In Java,
everything is well defined. However, the virtual machine and some of its parts have to be
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
class loader (part of the JVM) is responsible for loading trusted classes (e.g., basic Java class
library classes). User-defined class loaders (not part of JVM) are the subclasses of
java.util.Class Loader class that are compiled and instantiated just like any other Java class. The
bytecode verifier verifies the code and ensures that the code is fit to be executed by the JVM.
Figure 2.6 shows the flow of data and control from Java source code through the Java compiler
to the JVM. The code is not allowed to execute until it has passed the verifier’s test.
But there remains the drawback of an extra compilation step after every correction during
debugging. Also, the interpretation of bytecode is still slower in many cases than a program in
local machine code. Advanced JVM can ameliorate this, and in many cases, reach speeds
similar to programs compiled to local machine code.
2.6.4 Java is Robust
The type checking of Java is at least as strong as that of C++. The compile-time and runtime
checks in Java catch many errors and make them crash-proof. The program cannot crash the
system. To sum up, Java is one of the most robust languages to have ever evolved. Automatic
garbage collection of allocated memory is the biggest contributor here. 2.6.5 JAVA Language
Security Features Java has several language features that protect the integrity of the security
system and prevent several common attacks. Security Through Definition Java is strict in its
definition of the language: All primitive data types in the language have a specifi c size.
All operations are defi ned to be performed in a specifi c order. Security Through Lack of
Pointer Arithmetic Java does not have pointer arithmetic, so Java programmers cannot forge a
pointer to memory. All methods and instance variables are referred to with their symbolic
names. Users cannot write a code that interprets system variables or accesses private
information stored in a system.
Security Through Garbage Collection Garbage collection makes Java programs more secure
and robust by automatically freeing memory, once it is no longer needed.
Java Security Model Java’s security model is focused on protecting users from hostile programs
downloaded from untrusted sources across a network. Programs downloaded over the
Internet are executed in a sandbox. It cannot take any action outside the boundaries specified
by the sandbox. The sandbox for untrusted Java applets, for example, prohibits many
activities, including Reading or writing to the local disk Making a network connection to
any host, except the host from which the applet came Creating a new process Loading
a new dynamic library and directly calling a native method By making it impossible for the
downloaded code to perform certain actions, Java’s security model protects the user from the
threat of hostile codes.
Java is Multithreaded
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
To explore this property, you must know the meaning of multithreading. It can be explained
well with the help of an example. Consider a four-gas burner on which food is cooked. The
cook, in order to save time, puts milk to boil on one gas burner, rice on the other, makes
chapattis on the third, and vegetable on the fourth. The cook switches between all the items
to be cooked so that neither of the items are red-heated to lose their taste. He may
lower/brighten up the gas as and when required. Here the cook is the processor and the four
items being cooked are threads. The processor (cook) switches from one thread to another. A
thread can be loosely defined as a separate stream of execution that takes place
simultaneously and independent of everything else that might be happening. Threads are
independent parts of a process that run concurrently. Using threads, a program cannot hold
the CPU for a long duration intentionally (e.g. infinite loop). The beauty of multithreading is
that the other tasks that are not stuck in the loop can continue processing without having to
wait for the stuck task to finish. Threads in Java can place locks on shared resources so that
while one thread is using it, no other thread is allowed to access it. This is achieved with the
help of synchronization.
Automatic Memory Management
Automatic garbage collection (memory management) is handled by the JVM. To create an
instance of a class, the ‘new’ operator is used (refer to Chapter 4). However, Java
automatically removes objects that are not being referenced. This is known as garbage
collection.
The advantages and disadvantages of garbage collection are listed below.
Advantages
Reduces the possibility of memory leaks, since memory is freed as needed. A memory
leak occurs when the memory allocated is not released, resulting in an unnecessary
consumption of all the available memory.
Memory corruption does not occur.
Disadvantage
Garbage collection is considered one of the greatest bottlenecks in the speed of execution.
Dynamic Binding
The linking of data and methods to where they are located is done at runtime. New classes can
be loaded at runtime. Linking is done on-the-fly, i.e., on-demand. Good Performance
Interpretation of byte code slowed performance in early versions, but advanced virtual
machines with adaptive optimization and just-in-time compilation (combined with other
features) provide high speed code execution. Built-in Networking Java was designed with
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
networking in mind and comes with many classes to develop sophisticated Internet
communications.
No Pointers
Java uses references instead of pointers. A reference provides access to objects. The
programmer is relieved from the overhead of pointer manipulation.
No Global Variables In Java, the global namespace is the class hierarchy and so, one cannot
create a variable outside the class. It is extremely difficult to ensure that a global variable is
manipulated in a consistent manner. Java allows a modified type of the global variable called
static variable.
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
includes JVM, class libraries, and other supporting files. JRE = JVM + Core Java API libraries JDK
= JRE + development tools like compilers
Tools such as javac (compiler), java (interpreter), and others are provided in a bundle,
popularly known as Java Development Kit (JDK). JDK comes in many versions (enhanced in
each version) and is different for different platforms such as Windows and Linux. A runtime
bundle is also provided as a part of JDK (popularly known as Java Runtime Environment).
JAVA VIRTUAL MACHINE
At the heart of the Java platform lies the JVM. Most programming languages compile the
source code directly into machine code, suitable for execution on a particular microprocessor
architecture. The difference with Java is that it uses bytecode, an intermediate code. Physical
Machine JVM Java bytecode executes on a virtual machine. Actually, there wasn’t a hardware
implementation of this microprocessor available when Java was first released. Instead, the
processor architecture is emulated by software known as the virtual machine. This virtual
machine is an emulation of a real Java processor—a machine within a machine (Fig. 2.4). The
virtual machine runs on top of the operating system, which is demonstrated in Fig. 2.5. The
JVM is responsible for interpreting Java bytecode, and translating this into actions or operating
system calls. The JVM is responsible for catering to the differences between different
platforms and architectures in a way that the developers need not be bothered about it. The
JVM forms a part of a large system, the JRE. JRE varies according to the underlying operating
system and computer architecture. If JRE for a given environment is not available, it is
impossible to run the Java software.
3.1 VARIABLES
Variable is a symbolic name refer to a memory location used to store values that can change
during the execution of a program. Java declares its variables in the following manner: int Data
type noofwatts Identifier = 100; // variable declaration Literal A variable declaration involves
specifying the type (data type), name (identifier), and value (literal) according to the type of
the variable. Let us have a look at the three components in detail.
3.2 PRIMITIVE DATA TYPES Primitive data types are the basic building blocks of any
programming language. A primitive data type can have only one value at a time and is the
simplest built-in form of data within Java.
All variables in Java have to be declared before they can be used, that is why Java is termed as
a strongly typed language. There are eight primitive data types in Java, as follows: byte short
int long float double char boolean For whole number For real numbers Characters Boolean
Java is portable across computer platforms. C and C++ leave the size of data types to the
machine and the compiler, but Java specifies everything.
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
IDENTIFIER
Identifiers are names assigned to variables, constants, methods, classes, packages, and
interfaces. No limit has been specified for the length of a variable name. Identifiers can have
letters, numbers, underscores, and any currency symbol. However they may only begin with a
letter, underscore, or a dollar sign. Digits cannot be the first character in an identifier.
3.3.1 Rules for Naming
1. The fi rst character of an identifi er must be a letter, an underscore, or a dollar sign ($). 2.
The subsequent characters can be a letter, an underscore, dollar sign, or a digit. Note that
white spaces are not allowed within identifi ers. 3. Identifi ers are case-sensitive. This means
that Total_Price and total_price are different identifi ers. Do not use Java’s reserved keywords.
A few examples of legal and illegal identifi ers are shown below.
Keywords //Package Declaration Keywords are predefined identifiers meant for a specific
purpose and cannot be used for identifying used defined classes, variables, methods,
packages, and interfaces. All keywords are in lower case. Table 3.1 lists the keywords in Java.
3.4 LITERALS
A literal is a value that can be passed to a variable or constant in a program. Literals can be
numeric (for byte, short, int, long, float, double), boolean, character, string notations or null
literals. Numeric Literals can be represented in binary, decimal, octal, or hexadecimal
notations. These literals can be assigned to all numeric types in Java including char (based on
their respective range and size). Binary literals are a combination of 0’s and 1’s. Binary literals
can be assigned to variables in Java 7. Binary literals must be prefixed with 0b or 0B (zerob or
zeroB). For example, char bin1 = 0b1010000; char bin2 = 0b1010001; float bin3 = 0b1010000;
int bin4 = 0b1010001; // value in bin1 will be P // value in bin2 will be Q // value in bin3 will be
80.0 // value in bin4 will be 81 In case octal literals have to be specified, the value must be
prefixed with a zero and only digits from 0 to 7 are allowed. For example, int x = 011; char
y=0150; float z=0234; //value in x is 9 // value in y will be h // value in z will be 156.0
Hexadecimal literals are prefixed with 0x or 0X; the digits 0 through 9 and a through f (or A
through F) are only allowed. For example, int y = 0x0001; char x=0x45; float y=0xA3; //value in
y is 1 // value in x will be E // value in y will be 163.0 All integer literals are of type int, by
default. To define them as long, we can place a suffix of L or l after the number for instance:
long l = 2345678998L; All floating literals are of type double, by default. To define them as
float literals, we need to attach the suffix F or f. For double literals, D or d are suffixed at the
end; however, it is optional. For instance, float f = 23.6F; double d = 23.6;
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
For char literals, a single character is enclosed in single quotes. You can also use the prefix \u
followed by four hexadecimal digits representing the 16-bit unicode character: char c = '\
u004E'; char sample = 'A'; char example = 'a'; A single quote, a backslash or a unprintable
character (such as a horizontal tab) can be specified as a character literal with the help of an
escape sequence. An escape sequence represents a character by using a special syntax that
begins with a single backslash character. Unicode is a type of escape sequence (refer Table
3.2). Furthermore, the syntax of unicode escape sequence consists of \uxxxx (where each x
represents a hexadecimal digit).
For instance, char c = '\t'; // creates a character that represents horizontal tab (Refer Table
3.3). Unicode characters can be assigned to strings in Java 7. Unicode 6, which has thousands
of characters, cannot be accommodated in a 16-bit char data type. Increasing the size of char
data type would lead to backward compatibility problems. To maintain compatibility with the
application and standards, the string (“U+hex”) is used to express unicode characters in Java. A
boolean literal is specified as either true or false. By default, it takes the value false (Refer
Table 3.4). The following code fragment demonstrates a boolean literal: boolean firstRoll =
true; String literals consist of zero or more characters within double quotes. For instance,
String s = "This is a String Literal"; Null literals are assigned to object reference variables (see
Chapter 4 for object references). s = null; Table 3.4 shows a summary of the data types along
with their respective default values, size, and range.
3.5 OPERATORS null An operator performs an action on one or more operands. An operator
that performs an action on one operand is called a unary operator (+, –, ++, – –). An operator
that performs an action on two operands is called a binary operator (+, –, / , * , and more). An
operator that performs an action on three operands is called a ternary operator (? :). Java
provides all the three operators. Let us begin the discussion with binary operators. 3.5.1
Binary Operators Java provides arithmetic, assignment, relational, shift, conditional, bitwise,
and member access operators. Assignment Operators It sets the value of a variable (or
expression) to some new value. The simple ‘=’ operator sets the left-hand operand to the
value of the right-hand operand. The assignment operator has right to left associativity
(discussed in Section 3.7); so the statement a = b = 0; would assign 0 to b then b to a. Java
supports the following list of shortcut or compound assignment operators: += –= *= /= %= &=
|= ^= <<=>>= >>>= These operators allow you to combine two operations into one: one fixed
as assignment plus another one. These operators will be explained shortly according to their
counterparts. Arithmetic Operators Arithmetic operators are used for adding (+), subtracting
(–), multiplying (*), dividing (/), and finding the remainder (%). Java does not support operator
overloading. There are certain languages like C++ that allow programmers to change the
meaning of operators enabling them to act in more than one way depending upon the
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
operands. But there are certain operators which are overloaded by Java itself like + operator
which behaves differently when applied to different operands. For example, if + operator is
used and one of the operands is a string, then the other operand is converted to a String
automatically and concatenated. It is evident in the following examples in the System.
out.println statement when the String in the quotes is concatenated with the values of the
result or individual primitives. In addition to these operators, arithmetic compound
assignment operators are also provided by Java: +=, – =, /=, *=, %=. For example, a += b; a –=
b; a *= b; a /= b; a % = b; // evaluated as a = a + b; // evaluated as a = a – b; // evaluated as
a = a * b; // evaluated as a = a / b; // evaluated as a = a % b Let us take an example to
demonstrate the use of these operators in Java. A close look at the program will show us that
the + operator can be used for two purposes: concatenation and addition in the print
statements.
Relational Operators Relational operators in Java return either true or false as a boolean type.
Table 3.6 shows a list of all the relational operators in Java. Relational operators in C++ returns
an integer where the integer value of zero may be interpreted as false and any non-zero value
may be interpreted as true.
Boolean Logical Operators Boolean logical operators are: conditional OR (||), conditional
AND (&&), logical OR (|), logical AND (&), logical XOR (^), unary logical NOT (!). Boolean logical
operators are applied to boolean operands or expressions (Section 3.6) and return a boolean
value. The bitwise logical AND (&), logical OR (|), logical XOR (^) and logical NOT (~) operators
are applied to integers to perform bitwise logical operations discussed later. Logical OR results
in true if one of the operands is true. Logical AND results in false if one of the operands is false.
Logical XOR works like OR with an exception, that is, in case if both the operands of an XOR
operator are true then the answer is false. Logical NOT is just the compliment of the boolean
operand. Conditional OR (||) and AND (&&) operators also known as short-circuit operators
conditionally evaluate the second operand or expression. In case of OR, if the first operand is
true, no matter what the second operand is, the answer is true. In case of AND, if the first
operand is false, no matter what the second operand is, the answer is false. So there is no
need to evaluate the second operand. In addition to these operators, boolean compound
assignment operators are also provided by Java: &=, |=, ^=. For example, a &= b; a |= b; a ^=
b; // evaluated as a = a & b; // evaluated as a = a | b; // evaluated as a = a ^ b;
Bitwise Operators Bitwise operators include and, or, xor, not, right shift, left shift, and
unsigned right shift. In Java, bitwise operators operate on int and long values. If any of the
operand is shorter than an int, it is automatically promoted to int before the operations are
performed (see Section 3.8). Table 3.7 lists the bitwise operators and how they function.
Shift operators shift the bits depending upon the type of operator. The left shift operator shifts
the numbers of bits specified towards the left. Bits are discarded from the left and added from
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
the right with the value of bits being zero. The right shift operator shifts the numbers of bits
specified towards right. Bits are discarded from the right and added from the left side with the
value of bits being that of the sign bit. The unsigned right shift shifts the numbers of bits
specified towards right. Bits are discarded from the right and added from the left side with the
value of bits being zero. For example, let us assume x = 4 and this x is to be shifted by the shift
distance of 1. int y = x >> 1; //y has the value 2, value is halved in each successive right shift =
00000000 00000000 00000000 00000100 >> 1 = 00000000 00000000 00000000 00000010
(which is 2) int y = x << 1; // y has the value 8, value is doubled in each successive left shift int y
= x >> 1; // same as right shift for positive numbers. If we provide a negative number to be left
or right shifted, then the negative numbers are represented in 2’s compliment arithmetic and
then shifted. If we provide an int negative shift distance as shown in the following example,
first the negative shift distance is ANDed with the mask 11111 (i.e., 31) and the result is the
new shift distance. If we provide a long negative shift distance as shown in the following
example, first the negative shift distance is ANDed with the mask 111111 (i.e., 63), and the
result is the new shift distance.
3.5.2 Unary Operators
Unary operators, as the name suggest, are applied to only one operand. They are as follows: +
+, - -, !, and ~. The unary boolean logical not (!) and bitwise logical not (~) have already been
discussed. Increment and Decrement Operators Increment and decrement operators can be
applied to all integers and floating-point types. They can be used either in prefix (– –x, ++x) or
postfix (x– –, x++) mode. Prefix Increment/Decrement Operation int x = 2; int y = ++x; // x = 3,
y = 3 int z = --x; // x = 1, z = 1 Postfix Increment/Decrement Operation int x = 2; int y = x++; //
x == 3, y == 2 int z = x--; // x = 1, z = 2
3.5.3 Ternary Operators Ternary operators are applied to three operands. This conditional
operator (? :) decides, on the basis of the first expression, which of the two expressions to be
evaluated. operand1 ? operand2 : operand3
operand1 must be of boolean type or an expression producing a boolean result. If operand1 is
true, then operand2 is returned. If operand1 is false, then operand3 is returned. This operator
is similar to an if conditional statement. For example, String greater = x < y ? "Y is greater" : " X
is greater"; If the value of x is less than y, “Y is greater” string is retuned and stored in the
variable: greater, else “X is greater” is retuned and stored in the variable: greater. 3.6
EXPRESSIONS
An expression is a combination of operators and/or operands. Java expressions are used to
create objects, arrays, pass values to methods and call them, assigning values to variables, and
so on. Expressions may contain identifiers, types, literals, variables, separators, and operators
(we have already discussed all these topics). For example, int m = 2,n = 3,o = 4; int y = m * n *
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
o; m=2 is an expression which assigns the value 2 to variable m. Similarly, n=3 and o=4 are
expressions where n and o are being assigned values 3 and 4. m * n * o is also an expression
wherein the values of m, n, and o are multiplied and the result is stored in the variable y.
3.7 PRECEDENCE RULES AND ASSOCIATIVITY
Precedence rules are used to determine the order of evaluation priority in case there are two
operators with different precedence. Associativity rules are used to determine the order of
evaluation if the precedence of operators is same. Associativity is of two types: Left and Right.
Left associativity means operators are evaluated from left to right and vice versa for right
associativity. Precedence and associativity can be overridden with the help of parentheses.
Conversions that are implicit in nature are termed as widening conversions. In an assignment
statement, the types of the left-hand-side and right-hand-side must be compatible. If the right
hand-side can fit inside the left-hand-side, the assignment is completed. For example, a
smaller box can be placed in a bigger box and so on. A byte value can be placed in short, short
in an int , int in long , and so on (see widening conversion). Any value can be assigned to a
double. Any value except a double can be assigned to a float. Any whole number value can be
assigned to a long; and int, short, byte, and char can all fit inside int. For example, byte b = 10;
int i = b; // byte variable // implicit widening byte to int Type conversion or promotion also
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
takes place while evaluating the expressions involving arithmetic operators. For example, int i
= 10; double d = 20; d = i + d; //int variable //int literal assigned to a double variable
//automatic conversion int to double In the previous statement, the int value i is promoted to
double and then the two double values (i & d) are added to produce a double result. The basic
rule is that if either of the variables in a binary operation (involving arithmetic, relational,
equality) is double, then Java treats both values as double. If neither value is a double but one
is a float, then Java treats both values as float. If neither is a float or a double but one is a long,
then Java treats both values as long. Finally, if there are no double, float, or long, then Java
treats both values as an int, even if there are no int in the expression. Therefore, the result will
be a double, float, long or int depending on the types of the operands. For example, consider
the following declarations: byte b = 10; short s = 30; The following statement is invalid because
while evaluating the expression, byte and short are automatically promoted to int, so the
result is an int and short is used to store the result which is smaller than int. short z = b*s; int i
= b*s; //invalid //valid In case of bitwise and, or, xor, if one of the operand is broader than int,
then both operands are converted to long; else both are converted to int. If bitwise not
operator is applied to an operand shorter than int, it is promoted to int automatically. In case
of shift operators, if a single operand has a type narrower than int then it is also promoted to
int, otherwise not. Let us take an interesting case float f=3; // legal; int literal assigned to a
float variable The last declaration of a float variable shows that suffix f of F was not used while
assigning value and yet it was considered a legal statement. The reason is because 3 is an int
and an int value can be directly assigned to a float. But if the declaration would have been
float f = 3.0; // illegal;
Casting is also known as narrowing conversion (reverse of widening conversion).
If you want to assign long values to int variables or double values to float variables, then the
compiler will not allow you to do so unless you explicitly tell it that you really want to do so
with the help of a cast. When it is necessary to put a bigger value into a particular smaller type,
use a cast. For example, consider the reverse of the box example. A bigger box has to be
placed in a small box. Then the bigger box has to be chopped so that the bigger box (which has
now become smaller) can be placed in the small box. Casting is not implicit in nature. It has to
be explicitly mentioned by preceding it with the destination type specified in the parentheses.
For instance, int i = (int)(8.0/3.0); A cast lets the compiler know that you are serious about the
conversion you plan to make. When a value is cast before assignment, the right hand side is
chopped down to fit into the left hand side. For casting a floating-point number to an int or a
long, the fractional part is truncated resulting in an integer. If the resulting integer is small
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
enough to fit in the left hand side, the assignment is completed. But if the number is too large,
then the integer is set to the largest possible value of its left-hand-side type. If the real number
is too small, the integer is set to the smallest possible value of its left-hand-side type. For byte
and short, if the value is small enough to fit in the byte and short destination, the assignment
is completed. The dark side of casting is that it may result in the loss of sign, magnitude, and
precision. One more point worth mentioning is that if you try to put a long value into float
variable, Java treats this as a legal statement. For example, long x = 32l; float y = x; // legal
statement The point worth pondering is that how can a long value, which is of 64 bits, be
assigned to a float variable which is of 32 bits? To understand why this is a legal statement we
need to know how floating point numbers are represented. A float or double value is
represented using IEEE 754 binary floating point standard. A floating point number is
represented in four components— sign, mantissa, radix, and exponent. A sign bit is used to
denote a positive number or a negative number. A value of zero in sign bit indicates positive
number and 1 in sign bit indicates a negative number. Mantissa holds the significant digits of
the floating point number and exponent is used for indicating the power (positive or negative)
of the radix. The first bit of the exponent indicates its sign. The format of a floating point
number is shown below:
sign bit * mantissa * 2exponent Java uses a radix of 2. A float variable has 23 bits for mantissa
and 8 bits for exponent. A double variable uses 52 bits for mantissa and 11 bits for exponent.
The bit representation of these variables is shown below: Sign bit 8 exponent bits f l oat
variable Sign bit 23 mantissa bits 11 exponent bits double variable 52 mantissa bits So you can
easily imagine that a float variable can accommodate a lot more values that what a long
variable can because of its representation and format. For a more detailed discussion on
floating point standard refer to IEEE 754 floating point standard.)
FLOW OF CONTROL
Control flow statements help programmers make decisions about which statements to
execute and to change the flow of execution in a program. The four categories of control flow
statements available in Java are conditional statement, loops, exception, and branch.
3.9.1 Conditional Statements Java programs accomplish their tasks by manipulating the
program data using operators and making decisions by testing the state of program data.
When a program makes a decision, it determines, based on the state of the program data
whether certain lines of code should be executed. For example, a program may examine a
variable called flag to determine if it should execute a block of code that saves data into a file
on to the disk. If flag is true, the data is saved; else the data is not saved. The two conditional
statements provided by Java are: if … else and switch-case. if…else The syntax of if statement
is as follows: if (x = = 0) {// Lines of code} else if(x = = 1) {// Lines of code} ……… else {//
Lines of code} The arguments to a conditional statement like if must be a boolean value, which
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
is something that evaluates to true or false. You can have n number of else if (){} statements in
your program, as per your requirement. The if...else condition can also be nested as shown. if
(condition) { if (condition) {//do something based on the condition} }
class IFElseExample
{
public static void main(String args[])
{
int x=20,y=18,z=22;
if (x < y)
{
if (z < x) // x comes before y // z comes first
System.out.println( z + " " + x + " " + y);
else if (z > y) // z comes last
System.out.println(x + " " + y + " " + z);
else // z is in the middle
System.out.println(x + " " + z + " " + y);
}
else
{
if (z < y)
else if ( z > x)
else // y comes before x // z comes first
System.out.println(z + " " + y + " " + x); // z comes last
System.out.println(y + " " + x + " " + z); // z is in the middle
System.out.println(y + " " + z + " " + x);
}
}
}
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
Switch-case
Java has a shorthand for multiple if statement—the switch-case statement. Here is how we
can write the above program using a switch-case:
switch (x)
{
case 0: // Lines of code
doSomething0();
break;
case 1: // Lines of code
doSomething1();
break; . . .
case n: // Lines of code doSomethingN();
break;
default: doSomethingElse();
}
switch-case works with byte, short, char, and int primitive type. It can also be an enum type
(see Chapter 6) or one of the four special wrapper classes (see Chapter 6) namely: Byte for
byte, Short for short, Character for char, Integer for int. We can use strings also with the
switch-case from Java 7 onwards. It means that x must be one of these int, byte, short, char,
enum type, String or (one of the four) wrapper classes. It can also be an expression that
returns an int, byte, short, char or String. The value in x is compared with the value of each
case statement until one matches. If no matching case is found, the default case is executed.
Once a case is matched, all subsequent statements are executed till the end of the switch
block or you break out of the block. Therefore, it is common to include the break statement at
the end of each case block, unless you explicitly want all subsequent statements to be
executed. The following example shows how switch-case can be used in Java. A switch-case is
more efficient than an if-then-else statement, as it produces a much efficient byte code.
3.9.2 Loops
The purpose of loop statements is to execute Java statements many times. There are three
types of loops in Java—for, while, and do-while.
for Loop
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.
PROGRAMMING_IN_JAVA_UNIT_I_OOPS
The for loop groups the following three common parts together into one statement:
(a) Initialization
(b) Condition
(c) Increment or decrement
To execute a code for a known number of times, for loop is the right choice.
The syntax of for loop is
for (int i = 0; i < 5; i ++)
class ForDemo
{
public static void main(String args[])
{ L1 L2 Output for(int i = 1;i <= 5;i++) System.out.println("Square of "+i+" is "+ (i*i)); } }
Prepared by H.Riaz Ahamed, Asst. Professor, Dept. of Computer Science, The New College, Chennai-14.