Jaca Docx2
Jaca Docx2
Jaca Docx2
Syllabus:
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.
Objectives:
✓ Fundamentals of object-oriented programming concepts such as data abstraction, encapsulation,
inheritance, polymorphism.
✓ JVM Architecture and its working.
✓ Expressions and Flow of control
Outcomes:
➢ Apply the principles of object oriented concepts on real world problems.
➢ Able to perform type conversions
➢ Understand the flow of control in java programming
Unit-1
Small Questions:
1) How to use break and continue statements in java? [Set-1, April –18-R16].
2) Write about the relationship between OOPs, OODesign and OOAnalysis. [Set-2, April–18-R16].
3) What is data abstraction? Differentiate data and procedural abstractions. [Set-3, April–18-R16].
4) What are the components of JAVA platform? Explain. [Set-4, April–18-R16].
5) Support the statement “java byte code gives high performance”. [Set-1, April –18-R13].
6) Support the statement “java is dynamic”. Discuss. [Set-2, April –18-R13].
7) Support the statement “java is Architecture-Neutral” [Set-3, April –18-R13].
8) Support the statement “java is robust”. Discuss. [Set-4, April –18-R13].
Big Questions:
1. How to perform type casting in java? Differentiate it from primitive type conversion with an example
program. [Set-1,April – 2018-R16].
2. Write a java program to illustrate the usage of conditional statements and looping statements. [Set-1,April –
2018-R16].
3. Write about the role of JVM, JAVA API in developing the platform independent java program with suitable
example. [Set-2,April – 2018-R16].
4. What are the two control structures used in java for making decisions? Explain with an example program.
[Set-2,April – 2018-R16].
5. Write a java program that inputs an integer, ‘n’ from the command line and displays the string
“1+2+3+…+n=sum” and also compute the sum. [Set-3, April –18-R13].
6. How to implement precedence rules and associativity in java language? Give an example. [Set-3, April –
18-R13].
7. What are the different primitive data types in java? Give their sizes in bits. How they are different from
reference data types? [Set-4, April –18-R13].
8. Write a java program to illustrate the increment & decrement operators, shift operators and ternary operator.
[Set-4, April –18-R13].
Introduction
This tutorial will help you to understand about Java OOP’S concepts with examples. Let’s discuss what are
the features of Object Oriented Programming. Writing object-oriented programs involves creating classes,
creating objects from those classes, and creating applications, which are stand-alone executable programs
that use those objects.
A class is a template, blueprint, or contract that defines what an object’s data fields and methods will be.
An object is an instance of a class. You can create many instances of a class. A Java class uses variables to
define data fields and methods to define actions. Additionally, a class provides methods of a special type,
known as constructors, which are invoked to create a new object. A constructor can perform any action, but
constructors are designed to perform initializing actions, such as initializing the data fields of objects.
Objects are made up of attributes and methods. Attributes are the characteristics that define an object; the
values contained in attributes differentiate objects of the same class from one another. To understand this
better let’s take the example of Mobile as an object. Mobile has characteristics like a model, manufacturer,
cost, operating system etc. So if we create “Samsung” mobile object and “IPhone” mobile object we can
distinguish them from characteristics. The values of the attributes of an object are also referred to as the
object’s state.
Output :
When you create a subclass by extending an existing class, the new subclass contains data and methods that
were defined in the original superclass. In other words, any child class object has all the attributes of its
parent. Sometimes, however, the superclass data fields and methods are not entirely appropriate for the
subclass objects; in these cases, you want to override the parent class members. Let’s take the example
used in inheritance explanation.
package oopsconcept;
public class OverridingDemo {
public static void main(String[] args) {
//Creating Object of SuperClass and calling getModel Method
Mobile m = new Mobile("Nokia", "Win8", "Lumia",10000);
System.out.println(m.getModel());
//Creating Object of Sublcass and calling getModel Method
Android a = new Android("Samsung", "Android", "Grand",30000);
System.out.println(a.getModel());
//Creating Object of Sublcass and calling getModel Method
Blackberry b = new Blackberry("BlackB", "RIM", "Curve",20000);
System.out.println(b.getModel());
}
}
Abstraction
All programming languages provide abstractions. It can be argued that the complexity of the problems
you’re able to solve is directly related to the kind and quality of abstraction. An essential element of object-
oriented programming is an abstraction. Humans manage complexity through abstraction. When you drive
your car you do not have to be concerned with the exact internal working of your car(unless you are a
mechanic). What you are concerned with is interacting with your car via its interfaces like steering wheel,
brake pedal, accelerator pedal etc. Various manufacturers of car have different implementation of the car
working but its basic interface has not changed (i.e. you still use the steering wheel, brake pedal,
accelerator pedal etc to interact with your car). Hence the knowledge you have of your car is abstract.
A powerful way to manage abstraction is through the use of hierarchical classifications. This allows you to
layer the semantics of complex systems, breaking them into more manageable pieces. From the outside, a
car is a single object. Once inside, you see that the car consists of several subsystems: steering, brakes,
sound system, seat belts, heating, cellular phone, and so on. In turn, each of these subsystems is made up of
more specialized units. For instance, the sound system consists of a radio, a CD player, and/or a tape
player. The point is that you manage the complexity of the car (or any other complex system)through the
use of hierarchical abstractions.
An abstract class is something which is incomplete and you can not create an instance of the abstract class.
If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if
it does not contain any abstract method and implements all abstract method inherited from abstract class or
Let's take an example of Java Abstract Class called Vehicle. When I am creating a class called Vehicle, I
know there should be methods like start() and Stop() but don't know start and stop mechanism of every
vehicle since they could have different start and stop mechanism e.g some can be started by a kick or some
can be by pressing buttons.
The advantage of Abstraction is if there is a new type of vehicle introduced we might just need to add one
class which extends Vehicle Abstract class and implement specific methods. The interface of start and stop
method would be same.
package oopsconcept;
public abstract class VehicleAbstract {
public abstract void start();
public void stop(){
System.out.println("Stopping Vehicle in abstract class");
}
}
class TwoWheeler extends VehicleAbstract{
@Override
public void start() {
System.out.println("Starting Two Wheeler");
}
}
class FourWheeler extends VehicleAbstract{
@Override
public void start() {
System.out.println("Starting Four Wheeler");
}
}
package oopsconcept;
public class VehicleTesting {
public static void main(String[] args) {
VehicleAbstract my2Wheeler = new TwoWheeler();
VehicleAbstract my4Wheeler = new FourWheeler();
my2Wheeler.start();
my2Wheeler.stop();
my4Wheeler.start();
my4Wheeler.stop();
}
}
Output :
Applications of OOP:
The promising areas includes the followings,
This language was initially called “Oak”, (Oak is a tree name). By default the name “Oak” is registered by
some other company, so it is renamed as “Java” in 1995.
The primary motivation was the need for a platform-independent (that is, architecture-neutral) language
that could be used to create software to be embedded in various consumer electronic devices, such as
microwave ovens and remote controls.
The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a
specific target. Although it is possible to compile a C++ program for just about any type of CPU, to do so
requires a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and time-
consuming to create.
An easier—and more cost-efficient—solution was needed. In an attempt to find such a solution, Gosling
and others began work on a portable, platform-independent language that could be used to produce code
that would run on a variety of CPUs under differing environments. This effort ultimately led to the creation
of Java.
An application is a program that runs on your computer, under the operating system of that
computer. That is, an application created by Java is more or less like one created using C or C++. The
ability to create applets makes java as an important language.
An applet is an application designed to be transmitted over the Internet and executed by a Java-
compatible Web browser. An applet is actually a tiny Java program, dynamically downloaded across the
network, just like an image, sound file, or video clip. In other words, an applet is a program that can react
to user input and dynamically change.
Security:
➢ Security is the main problem when program is transmitted over internet. When a program is
downloaded there is chance of a viral infection.
➢ Prior to Java, most users did not download executable programs frequently, and those who
downloaded, scanned them for viruses prior to execution.
➢ In addition to viruses, another type of malicious program, that can gather private information, such
as credit card numbers, bank account balances, and passwords, by searching the contents of your
computer’s local file system.
➢ Java answers both of these concerns. When a Java-compatible Web browser is used, one can freely
download Java applets without fear of viral infection or malicious intent.
➢ Java achieves this protection by confining a Java program to the Java execution environment and
not allowing it access to other parts of the computer.
Portability
As discussed earlier, many types of computers and operating systems are in use throughout the
world—and many are connected to the Internet. For programs to be dynamically downloaded to all the
various types of platforms connected to the Internet, some means of generating portable executable code is
needed. Java is also a portable language.
Indeed, Java’s solution to these two problems is both elegant and efficient with the use of java byte code
and JVM.
Phase 5: Execution
In Phase 5, the JVM executes the program’s bytecodes, thus performing the actions specified by the
program. The JVM is invoked by the java command. For example, to execute a Java application called
Welcome, type the command
➔ java Welcome
in a command window to invoke the JVM, which would then initiate the steps necessary to execute the
application.
Byte code is nothing but the intermediate representation of Java source code which is produced by the Java
compiler by compiling that source code.
This byte code is an machine independent code. It is not completely a compiled code but it is an
intermediate code which is later interpreted and executed by JVM.
Byte code is a machine code for JVM. But the machine code is platform specific whereas bytecode is
platform independent that is the main difference between them. It is stored in .class file which is created
after compiling the source code.
JVM :
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM and JRE are platform dependent
because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
1. Simple
2. Secure
3. Portable
Simple
➢ Java is a simple programming language. Java was designed to be easy for the programmer to learn
and use effectively.
➢ Java is very easy to understand because Java inherits the C/C++ syntax and many of the object-
oriented features of C++.
➢ Some of the more confusing concepts from C++ like pointers and multiple inheritance are
eliminated from Java.
Object-Oriented
➢ Java programs are robust (strong) because they don’t crash easily like C or C++.
➢ Two of the main reasons for program failure are: memory management mistakes and mishandled
exceptional conditions (that is, run-time errors).
Java programs are robust because of two reasons:
1. Excellent exception handling
2. Proper memory management
An Exception is a run time error such as “divide by zero”, “file not found” e.t.c. Due to exceptions
data will be lost. Java helps in this area by providing object-oriented exception handling to handle all run-
time errors.
Memory management can be a difficult, tedious task in traditional programming environments like
C/C++. In C/C++, the programmer must manually allocate and free all dynamic memory. Java virtually
eliminates memory management problems by managing memory allocation and deallocation . (In fact,
deallocation is completely automatic, because Java provides garbage collection for unused objects.)
Architecture-Neutral
Java enables the creation of cross-platform programs by compiling into an intermediate code called
Java byte-code. This byte code can be interpreted on any system that provides a Java Virtual Machine.
Other interpreted systems, such as BASIC, Tcl, and PERL, suffer from performance deficits. Java is
designed to perform well on very low-power CPUs.
The Java bytecode was carefully designed so that it would be easy to translate directly into native
machine code for very high performance by using a just-in-time compiler. So java is a “High-performance
cross-platform” language.
Distributed
➢ On internet information is distributed between various computers. Java is designed for the distributed
environment of the Internet, because it handles TCP/IP protocols.
➢ In java objects from two different computers allows to access methods remotely. Java supports
Remote Method Invocation (RMI) which enables a program to invoke methods across the network.
➢ This feature brings an unparalleled level of abstraction to client/ server programming.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe
manner. This is crucial to the robustness of the applet environment, in which small fragments of bytecode
may be dynamically updated on a running system.
Multithreaded
➢ Multithreading is the ability of an application to perform more than one task at a time.
➢ A multi-threaded program is one in which there exists multiple flows of control called threads.
➢ A thread represents an individual process to execute a group of statements.
➢ Whenever we write a java program there exists by default two threads.
1. Foreground / child thread
2. Background / main(parent) thread
➢ A fore ground thread is one which always executes user defined subprograms. In a java program
there is a possibility of existing ‘n’ number of foreground threads.
➢ A background thread is one which always monitors the status of foreground threads. In each and
every java program there exists only one background thread.
➢ First background thread will be created, and later foreground threads will be created.
Portable:
The name of the class defined by the program is also Example. In Java, all code must reside inside a class.
By convention, the name of that class should match the name of the file that holds the program.
Comments
The contents of a comment are ignored by the compiler.
Java supports three styles of comments.
• Single line comment: //
• Multiline comment: /* ………….. */
• Documentation comment: /** ……….. */. This type of comment is used to produce an HTML file
that documents your program. This type of comment is readable to both, computer and human.
Defining a class
This line uses the keyword class to declare that a new class is being defined. Example is an
identifier that is the name of the class. The entire class definition, including all of its members, will be
between the opening curly brace and the closing curly brace ({, }).
public static void main(String args[])
This is the line at which the program will begin executing. All Java applications begin execution by
calling main( ).
The function main( ) must be declared as public, since it must be called by code outside of its class when
the program is started.
The keyword static allows main( ) to be called without having to instantiate a particular instance of the
class. This is necessary since main( ) is called by the Java interpreter before any objects are made.
Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no
way to run these classes. In applets you won’t use main( ).
The keyword void simply tells the compiler that main( ) does not return a value.
In main( ), there is only one parameter. String args[ ] declares a parameter named args, which is an array
of instances of the class String. (Arrays are collections of similar objects.) Objects of type String store
character strings. In this case, args receives any command-line arguments present when the program is
executed.
To display output
System.out.println("Welcome to Java");
This line outputs the string “Welcolme to java” 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. The line begins with System.out. in which System is a predefined class that provides access to the
system, and out is the output stream that is connected to the console.
Note:
➢ Every statement in Java ends with a semicolon.
➢ Java is a case sensitive language.
System.out.println()
num = 100;
System.out.println("This is num: " + num);
The first line declares an integer variable called num assigns to num the value 100. The next line of code
outputs the value of num preceded by the string “This is num:”.
In this statement, the plus sign causes the value of num to be appended to the string that precedes it, and
then the resulting string is output. (Actually, num is first converted from an integer into its string
equivalent and then concatenated with the string that precedes it.
Using the + operator, you can string together as many items as you want within a single println( )
statement.
The built-in method print( ) is just like println( ), except that it does not output a newline character
System.out.print("Example to display output ");
C:\>java Example
When the program is run, the following output is displayed:
Welcome to java
Data types
Java is a Strongly Typed Language.
1. Every variable has a type, every expression has a type, and every type is strictly defined.
2. All assignments, whether explicit or via parameter passing in method calls, are checked for type
compatibility.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and Boolean.
These can be put in four groups:
■ Integers: This group includes byte, short, int, and long, which are for whole valued signed numbers.
■ Floating-point numbers: This group includes float and double, which represent numbers with
fractional precision.
■ Characters: This group includes char, which represents symbols in a character set, like letters and
numbers.
■ Boolean: This group includes boolean, which is a special type for representing true/false values.
In C and C++ allow the size of an integer to vary based upon the execution environment. Because of Java’s
portability requirement, all data types have a strictly defined range. For example, an int is always 32 bits,
regardless of the particular platform
a. Integers:
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Bytes and shorts are 32-bit values to improve performance, The width and ranges
of these integer types vary widely, as shown in this table:
Example: short s;
short t;
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –
2,147,483,648 to 2,147,483,647. Variables of type int are commonly employed to control loops and to
index arrays. The int type is the most versatile and efficient type.
Long:
long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to
hold the desired value. The range of a long is quite large.
b. Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. For example: square root of a value. There are two kinds of floating-point
types, float and double, which represent single- and double-precision numbers, respectively.
Name Width Range
Double 64 4.9e–324 to 1.8e+308
Float 32 1.4e−045 to 3.4e+038
float
The type float specifies a single-precision value that uses 32 bits of storage. Variables of type float are
useful when you need a fractional component, but don’t require a large degree of precision.
Example: float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. All transcendental math
functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy
over many iterative calculations double is the best choice.
class Area{
public static void main(String args[]) {
double pi, r, a;
r = 10.8;
pi = 3.1416;
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
Variables
Declaring a Variable
A variable must be declared before it is used.
The basic form of a variable declaration is:
type identifier [ = value][, identifier [= value] ...] ;
➢ The type is one of Java’s atomic types, or the name of a class or interface.
➢ The identifier is the name of the variable.
➢ The variable can be initialized by specifying an equal sign and a value.
➢ Keep in mind that the initialization expression must result in a value of the same type as that
specified for the variable.
➢ To declare more than one variable of the specified type, use a comma-separated list.
Example:
int a, b, c;
int d = 3, e, f = 5; // declares three more ints, initializing
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.
A short program that computes the length of the hypotenuse of a right triangle given the lengths of its two
opposing sides:
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
➢ Java allows variables to be declared within any block. A block is begun with an opening curly brace
and ended by a closing curly brace.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
UNIT-1 JAVA PROGRAMMING Page 27
y is: -1
y is now: 100
As you can see, y is reinitialized to –1 each time the inner for loop is entered. Even though it
is subsequently assigned the value 100, this value is lost.
Operators :
Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and
logical. Java also defines some additional operators that handle certain special situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators:
The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean
types, but you can use them on char types, since the char type in Java is a subset of int.
The following simple example program demonstrates the arithmetic operators. It also illustrates the
difference between floating-point division and integer division.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
When you run this program, you will see the following output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
This version uses the += compound assignment operator. Both statements perform the same action: they
increase the value of a by 4.
There are compound assignment operators for all of the arithmetic, binary operators.
UNIT-1 JAVA PROGRAMMING Page 29
Thus, any statement of the form
var = var op expression;
can be rewritten as
var op= expression;
The compound assignment operators provide two benefits. First, they save you a bit of typing, because they
are “shorthand” for their equivalent long forms. Second, they are implemented more efficiently by the Java
run-time system than are their equivalent long forms.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
output:
a=6
b=8
c=3
Increment and Decrement
The ++ and the – – are Java’s increment and decrement operators.
The increment operator increases its operand by one. The decrement operator decreases its operand by one.
For example, this statement:
x = x + 1;
can be rewritten like this by use of the increment operator: x++;
Java defines several 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.
00101010 42
& 00001111 15
00001010 10
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the resultant bit
is a 1, as shown here:
00101010 42
| 00001111 15
00101111 47
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on the right. This
means that when a left shift is applied to an int operand, bits are lost once they are shifted past bit position
31. If the operand is a long, then bits are lost after bit position 63.
Since each left shift has the effect of doubling the original value, programmers frequently use this fact as an
efficient alternative to multiplying by 2.
The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its
general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in value. That is, the >> moves all of
the bits in the specified value to the right the number of bit positions specified by num.
When a value has bits that are “shifted off,” those bits are lost. For example, the next code fragment shifts
the value 35 to the right two positions, which causes the two low-order bits to be lost, resulting again in a
being set to 8.
int a = 35;
a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens:
00100011 35
>> 2
00001000 8
Each time you shift a value to the right, it divides that value by two—and discards any remainder. the
previous contents of the top bit. This is called sign extension and serves to preserve the sign of negative
numbers when you shift them right. For example, –8 >> 1 is –4, which, in binary, is
11111000 –8
>> 1
11111100 –4
It is interesting to note that if you shift –1 right, the result always remains –1, since sign extension keeps
bringing in more ones in the high-order bits.
To accomplish this, you will use Java’s unsigned, shift-right operator, >>>, which always shifts zeros into
the high-order bit.
The following code fragment demonstrates the >>>. Here, a is set to –1, which sets all 32 bits to 1 in
binary. This value is then shifted right 24 bits, filling the top 24 bits with zeros, ignoring normal sign
extension. This sets a to 255.
The outcome of these operations is a boolean value. The relational operators are most frequently used in
the expressions that control the if statement and the various loop statements.
Java provides two interesting Boolean operators not found in many other computer languages. These are
secondary versions of the Boolean AND and OR operators, and are known as short-circuit logical
operators.
If you use the || and && forms, Java will not bother to evaluate the right-hand operand when the outcome
of the expression can be determined by the left operand alone. This is very useful when the right-hand
operand depends on the value of the left one in order to function properly.
For example, the following code fragment shows how you can take advantage of short-circuit logical
evaluation to be sure that a division operation will be valid before evaluating it:
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception when
denom is zero. If this line of code were written using the single & version of AND, both sides would be
evaluated, causing a run-time exception when denom is zero.
The assignment operator is used to assign a value to variable.The assignment operator is the single equal
sign, =.
It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression.
Using a “chain of assignment” is an easy way to set a group of variables to a common value.
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ?.
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then
expression2 is evaluated; otherwise, expression3 is evaluated.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Output:
Absolute value of 10 is 10
Java has well-defined rules for specifying the order in which the operators in an expression are evaluated
when the expression has several operators. For example, multiplication and division have a higher
precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.
Precedence order.
When two operators share an operand the operator with the higher precedence goes first. For example, 1 +
2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher
precedence than addition.
Associativity.
When an expression has two operators with the same precedence, the expression is evaluated according to
its associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with
the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to
the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator
has left-to-right associativity. Some operators are not associative: for example, the expressions (x <= y <=
z) and x++-- are invalid.
There is no explicit operator precedence table in the Java Language Specification. Different tables on the
web and in textbooks disagree in some minor ways.
Short circuiting. When using the conditional and and or operators (&& and ||), Java does not evaluate the
second operand unless it is necessary to resolve the result. This allows statements like if (s != null &&
s.length() < 10) to work reliably. Programmers rarely use the non short-circuiting versions (& and |) with
boolean expressions.
Precedence order gone awry Sometimes the precedence order defined in a language do not conform with
mathematical norms. For example, in Microsoft Excel, -a^b is interpreted as (-a)^b instead of -(a^b). So -
1^2 is equal to 1 instead of -1, which is the values most mathematicians would expect. Microsoft
acknowledges this quirk as a “design choice.” One wonders whether the programmer was relying on the C
precedence order in which unary operators have higher precedence than binary operators. This rule agrees
with mathematical conventions for all C operators, but fails with the addition of the exponentiation
operator. Once the order was established in Microsoft Excel 2.0, it could not easily be changed without
breaking backward compatibility.
When one type of data is assigned to another type of variable, an automatic type conversion will take place
if the following two conditions are met:
1. The two types are compatible.
2. The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the int type is always
large enough to hold all valid byte values, so no explicit cast statement is required.
For widening conversions, the numeric types, including integer and floating-point types,
are compatible with each other.
However, there are no automatic conversions from the numeric types to char or boolean. Also, char and
boolean are not compatible with each other.
As mentioned earlier, Java also performs an automatic type conversion when storing a literal integer
constant into variables of type byte, short, long, or char.
Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if
you want to assign an int value to a byte variable? This conversion will not be performed automatically,
because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion,
since you are explicitly making the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit
type conversion.
Here, target-type specifies the desired type to convert the specified value to. For example, the following
fragment casts an int to a byte. If the integer’s value is larger than the range of a byte, it will be reduced
modulo (the remainder of an integer division by the) byte’s range.
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer type:
truncation. As you know, integers do not have fractional components. Thus, when a floating-point value is
assigned to an integer type, the fractional component is lost.
For example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1.
The 0.23 will have been truncated. Of course, if the size of the whole number component is too large to fit
into the target integer type, then that value will be reduced modulo the target type’s range.
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
When the d is converted to an int, its fractional component is lost. When d is converted to a byte, its
fractional component is lost, and the value is reduced modulo 256, which in this case is 67.
Control Statements:
Control statements can be put into the following categories: selection, iteration, and jump.
➢ Selection statements allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
➢ Iteration statements enable program execution to repeat one or more statements (that is, iteration
statements form loops).
➢ Jump statements allow your program to execute in a nonlinear fashion.
Java’s Selection Statements
Java supports two selection statements: if and switch. These statements allow you to control the
flow of your program’s execution based upon conditions known only during run time.
If:
The if statement is Java’s conditional branch statement. It can be used to route program execution through
two different paths.
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.
The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it
exists) is executed. In no case will both statements be executed. For example, consider the following:
int a, b;
// ...
if(a < b) a = 0;
else b = 0;
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are they both set to zero.
Most often, the expression used to control the if will involve the relational operators.
However, this is not technically necessary. It is possible to control the if using a single boolean variable.
class BoolIf {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
Nested ifs
Anested if is an if statement that is the target of another if or else. Nested ifs are very common in
programming. When you nest ifs, the main thing to remember is that an else statement always refers to the
nearest if statement that is within the same block as the else and that is not already associated with an else.
Here is an example:
if(i = = 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
As the comments indicate, the final else is not associated with if(j<20) because it is not in the same block
(even though it is the nearest if without an else). Rather, the final elseis associated with if(i==10). The
inner else refers to if(k>100) because it is the closest if within the same block.
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
The if statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the ladder is bypassed.
class Test {
public static void main(String args[]) {
int x = 30;
if( x == 0 ) {
System.out.print("Value of X is 0");
}
else if( x >0 ) {
System.out.print("Value of X is Positive");
}
else if( x < 0 ) {
System.out.print("Value of X is Negative");
}
}
}
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
switch
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to
different parts of your code based on the value of an expression. As such, it often provides a better
alternative than a large series of if-else-if statements.
switch (expression) {
case value1:
// statement sequence
The expression must be of type byte, short, int, or char; each of the values specified in the case statements
must be of a type compatible with the expression.
Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case
values are not allowed.
The break statement is used inside the switch to terminate a statement sequence. When a break statement
is encountered, execution branches to the first line of code that follows the entire switch statement. This
has the effect of “jumping out” of the switch.
You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch.
Since a switch statement defines its own block, no conflicts arise between the case constants in the inner
switch and those in the outer switch.
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer
switch. The count variable is only compared with the list of cases at the outer level. If count is 1, then
target is compared with the inner list cases.
Output:
i is 0, j is 1
Iteration Statements
Java’s iteration statements are for, while, and do-while. These statements create loops. A loop repeatedly
executes the same set of instructions until a termination condition is met.
while
The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its
controlling expression is true.
Here is its general form:
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. The curly braces are unnecessary if only a single statement is being
repeated.
class WhileDemo {
public static void main(String args[]) {
int n = 5;
while(n > 0) {
System.out.println("Value = " + n);
do-while
Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will
not execute even once if the condition is initially false (the body of the loop will not be executed at all).
However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional
expression is false initially. In other words, there are times when you would like to test the termination
expression at the end of the loop rather than at the beginning. To serve this purpose java supplies do-while
loop.
The do-while loop always executes its body at least once, because its conditional expression is at the
bottom of the loop.
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional
expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.
class DoWhile {
public static void main(String args[]) {
int n = 5;
do {
System.out.println("Value = " + n);
n--;
} while(n > 0);
}
}
The do-while loop is especially useful when you process a menu selection, because you will usually want
the body of a menu loop to execute at least once.
Import java.util.scanner;
public class ConsoleMenuDemo {
public static void main(String[] args) {
// Local variable
int choice,a,b;
Scanner s=new Scanner(System.in);
switch (choice) {
case 1: System.out.println(" enter value of a and b");
a = s.nextInt();
b = s.nextInt();
System.out.println(“a+b =”+(a+b));
break;
default:
System.out.println("Invalid selection");
break; // This break is not really necessary
}
}
}
for:
There are two forms of the for loop. The first is the traditional form that has been in use since the original
version of Java. The second is the new “for-each” form.
When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression
that sets the value of the loop control variable, which acts as a counter that controls the loop. It is important
to understand that the initialization expression is only executed once.
Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable
against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop
terminates.
Next, the iteration portion of the loop is executed. This is usually an expression that increments
or decrements the loop control variable.
The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and
then executing the iteration expression with each pass. This process repeats until the controlling expression
is false.
class ForTick {
public static void main(String args[]) {
int n;
for(n=5; n>0; n--)
System.out.println("tick = " + n);
}
}
Output:
tick = 5
tick = 4
tick = 3
tick = 2
tick = 1
Some times, the variable that controls a for loop is only needed for the purposes of the loop and is not used
elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the
for.
A foreach style loop is designed to cycle through a collection of objects, such as an array, in strictly
sequential fashion, from start to finish. The for-each style of for is also referred to as the enhanced for
loop.
The general form of the for-each version of the for is shown here:
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the
elements from a collection, one at a time, from beginning to end. There are various types of collections that
can be used with the for.
Example:
As this output shows, the for-each style for automatically cycles through an array in sequence from the
lowest index to the highest.
With each pass through the loop, x is automatically given a value equal to the next element in nums. Thus,
on the first iteration, x contains 1; on the second iteration, x contains 2; and so on.
Not only is the syntax streamlined, but it also prevents boundary errors.
Although the for-each for loop iterates until all elements in an array have been examined, it is possible to
terminate the loop early by using a break statement.
There is one important point to understand about the for-each style loop.
Its iteration variable is “read-only” as it relates to the underlying array. An assignment to the
iteration variable has no effect on the underlying array. In other words, you can’t change the contents of the
array by assigning the iteration variable a new value.
Example:
The enhanced version of the for also works on multidimensional arrays. Remember, multidimensional
arrays consist of arrays of arrays. (For example, a two-dimensional array is an array of one-dimensional
arrays.)
This is important when iterating over a multidimensional array, because each iteration obtains the next
array, not an individual element. Furthermore, the iteration variable in the for loop must be compatible
with the type of array being obtained.
For example, in the case of a two-dimensional array, the iteration variable must be a reference to a one-
dimensional array. In general, when using the for-each for to iterate over an array of N dimensions, the
objects obtained will be arrays of N–1 dimensions. To understand the implications of this, consider the
following program. It uses nested for loops to obtain the elements of a two-dimensional array in roworder,
from first to last.
In the program, pay special attention to this line: for(int x[] : nums)
break
➢ By using break, you can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
➢ When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++)
{
if(i == 5) break; // terminate loop if i is 10
System.out.println("i = " + i);
}
System.out.println("Loop complete.");
Java does not have a goto statement, but there are a few places where the goto is a valuable and legitimate
construct for flow control. For example, 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. By using this form of
break, you can break out of one or more blocks of code. These blocks need not be part of a loop or a
switch.
They can be any block. Further, you can specify precisely where execution will resume, because this form
of break works with a label. As you will see, break gives you the benefits of a goto without its problems.
break label;
Most often, label is the name of a label that identifies a block of code. This can be a stand-alone
block of code but it can also be a block that is the target of another statement.
When this form of break executes, control is transferred out of the named block. The labeled block must
enclose the break statement, but it does not need to be the immediately enclosing block.
To name a block, put a label at the start of it. A label is any valid Java identifier followed by a colon. Once
you have labeled a block, you can then use this label as the target of a break statement. Doing so causes
execution to resume at the end of the labeled block.
For example, the following program shows three nested blocks, each with its own label. The break
statement causes execution to jump forward, past the end of the block labeled second, skipping the two
println( ) statements.
Output:
One of the most common uses for a labelled break statement is to exit from nested loops.
For example, in the following program, the outer loop executes only once:
Continue:
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the
loop but stop processing the remainder of the code in its body for this particular iteration. The continue
statement performs such an action.
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.
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
This code uses the % operator to check if i is even. If it is, the loop continues without printing
a newline. Here is the output from this program:
1
3
5
7
9
As with the break statement, continue may specify a label to describe which enclosing loop to continue.
Here is an example program that uses continue to print a triangular multiplication table for 0 through 9.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<=5; i++) {
for(int j=0; j<=5; j++) {
if(j = = i) {
System.out.println();
continue outer;
}
System.out.print(" " + j);
}
}
System.out.println();
}
}
Output:
0
01
012
0123
01234
Return:
The return statement is used to explicitly return from a method. That is, it causes program control to
transfer back to the caller of the method.
At any time in a method the return statement can be used to cause execution to branch back to the caller of
the method. Thus, the return statement immediately terminates the method in which it is executed.
The following example illustrates this point. Here, return causes execution to return to the Java run-time
system, since it is the run-time system that calls main().
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
output:
Before the return.
As you can see, the final println( ) statement is not executed. As soon as return is executed,
control passes back to the caller.
One last point: In the preceding program, the if(t) statement is necessary. Without it, the Java compiler
would flag an “unreachable code” error because the compiler would know that the last println( ) statement
would never be executed. To prevent this error, the if statement is used here to trick the compiler for the
sake of this demonstration.