Java Notes Upto Control Statements
Java Notes Upto Control Statements
Object-Oriented Thinking
When computers were first invented, programming was done manually by toggling in a binary machine
instructions by use of front panel. As programs began to grow, high level languages were introduced that gives
the programmer more tools to handle complexity. The first widespread high level language is FORTRAN. Which
gave birth to structured programming in 1960’s. The Main problem with the high level language was they have
no specific structure and programs becomes larger, the problem of complexity also increases. So C became the
popular structured oriented language to solve all the above problems.
However in SOP(Standard Operating Procedure), when project reaches certain size its complexity
exceeds. So in 1980’s a new way of programming was invented and it was Object Oriented Programming. Object
Oriented Programming is a programming methodology that helps to organize complex programs through the use
of inheritance, encapsulation & polymorphism. Object Oriented Programming is a Revolutionary idea totally
unlike anything that has came before in programming.
To illustrate the major ideas in object-oriented programming, let us consider how we might go about handling a
Let me emphasize that the mechanism I used to solve my problem was to find an appropriate agent
(namely, Flora) and to pass to her a message containing my request. It is the responsibility of Flora to satisfy my
request. There is some method or some algorithm or set of operations used by Flora to do this. I do not need to
know the particular method that Flora will use to satisfy my request; indeed, often I do not want to know the
details. This information is usually hidden from my inspection.
If I investigated however, I might discover that Flora delivers a slightly diferent message to another againt in my
friend's city. That agent , in turn, perhaps has a subordinate who makes the flowers arrangement. The agent then
passes the flowers , along with yet another message, to a delivery person, and so on. Earlier, the agent in Sally's
city had obtained her flower from a flower wholesaler who, in turn, had interactions with the flower growers,
each of whom had to manage a team of gardeners.
So, our first observation of object-oriented problem solving is that the solution to my problem required
the help of many other individuals (Figure 1.1). Without their help, my problem could not be easily solved. We
phrase this in a general fashion as the following:
An object oriented program is structured as a community of interacting agents, called objects. Each object has a
role to play. Each object provides a service, or performs an action, that is used by other members of the
community.
The chain reaction that ultimately resulted in the solution to my program began with my request to Flora. This
request lead to other requests, which lead to still more requests, until my flowers ultimately reached my friend.
We see, therefore, that members of this community interact with each other by making requests. So, our next
principle of object- oriented problem solving is the vehicle by which activities are initiated:
Action is initiated in object-oriented programming by the transmission of a message to an agent (an object)
responsible for the action. The message encodes the request for an action and is accompanied by any additional
information (arguments) needed to carry out the request. The receiver is the object to whom the message is sent.
If the receiver accepts the message, it accepts the responsibility to carry out the indicated action. In response to
a message, the receiver will perform some method to satisfy the request.
We have noted the important principle of information hiding in regard to message passing that is, the
client sending the request need not know the actual means by which the request will be honored. There is
another principle, all too human, that we see is implicit in message passing. If there is a task to perform, the first
thought of the client is to find somebody else he or she can ask to do the work. This second reaction often
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 3
becomes thin in many programmers with extensive experience in conventional techniques. Frequently, a dificult
hurdle to overcome is the idea in the programmer's mind that he or she must write everything and not use the
services of others.
Information hiding is also an important aspect of programming in conventional languages. In what sense
is a message difierent from, say, a procedure call? In both cases, there is a set of well-defined steps that will be
initiated following the request. But, there are two important distinctions. The first is that in a message there is a
designated receiver for that message; the receiver is some object to which the message is sent. In a procedure
call, there is no designated receiver.The second is that the interpretation of the message is dependent on the
receiver and can vary with difierent receivers.
. Usually, the specific receiver for any given message will not be known until run time, so the
determination of which method to invoke cannot be made until then. Thus, we say there is late binding between
the message (function or procedure name) and the code fragment (method) used to respond to the message. This
situation is in contrast to the very early (compile-time or link-time) binding of name to code fragment in
conventional procedure calls.
1.3 Responsibilities
By discussing a problem in terms of responsibilities we increase the level of abstraction. This permits
greater independence between objects, a critical factor in solving complex problems. The entire collection of
responsibilities associated with an object is often described by the term protocol.
A traditional program often operates by acting on data structures, for example changing fields in an
array or record. In contrast, an object oriented program requests data structures (that is, objects) to perform a
service. This difference between viewing software in traditional, structured terms and viewing it from an
object-oriented perspective can be summarized by a twist on a well-known quote
“Ask not what you can do to your data structures, but rather ask what your data structures can do for you”.
Although I have only dealt with Flora a few times, I have a rough idea of the behavior I can expect when
I go into her shop and present her with my request. I am able to make certain assumptions because I have
information about forists in general, and I expect that Flora, being an instance of this category, will fit the general
pattern. We can use the term Florist to represent the category (or class) of all forists. Let us incorporate these
notions into our next principle of object-oriented programming:
All objects are instances of a class.The method invoked by an object in response to a message is
determined by the class of the receiver. All objects of a given class use the same method in response to
similar messages.
I have more information about Flora not necessarily because she is a florist but because she is a shopkeeper. I
know, for example, that I probably will be asked for money as part of the transaction, and that in return for
payment I will be given a receipt. These actions are true of grocers, stationers, and other shopkeepers. Since the
category Florist is a more specialized form of the category Shopkeeper, any knowledge I have of Shopkeepers
is also true of Florists and hence of Flora.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 5
One way to think about how I have organized my knowledge of Flora is in terms of a hierarchy of categories
(see Figure 1.2). Flora is a Florist, but Florist is a specialized form of Shopkeeper. Furthermore, a Shopkeeper
is also a Human; so I know, for example, that Flora is probably bipedal. A Human is a Mammal (therefore they
nurse their young and have hair), and a Mammal is an Animal (therefore it breathes oxygen), and an Animal is
a Material Object (therefore it has mass and weight). Thus, quite a lot of knowledge that I have that is applicable
to Flora is not directly associated with her, or even with her category Florist.
The principle that knowledge of a more general category is also applicable to a more specific category is
called inheritance. We say that the class Florist will inherit attributes of the class (or category) Shopkeeper.
There is an alternative graphical technique often used to illustrate this relationship, particularly when there
are many individuals.. This technique shows classes listed in a hierarchical tree-like structure, with more abstract
classes (such as Material Object or Animal) listed near the top of the tree, and more specific classes, and finally
individuals, are listed near the bottom. Figure 1.3 shows this class hierarchy for Flora.
“Classes can be organized into a hierarchical inheritance structure. A child class (or subclass) will inherit attributes
from a parent class higher in the tree. An abstract parent class is a class (such as Mammal) for which there are no
direct instances; it is used only to create subclasses.”
we know that mammals give birth to live children, but Phyl is certainly a Mammal, but it lays eggs. To
accommodate this, we need to find a technique to encode exceptions to a general rule.
We do this by declearing that information contained in a subclass can override information inherited from
a parent class. Most often, implementations of this approach takes the form of a method in a subclass having the
same name as a method in the parent class, combined with a rule for how the search for a method to match a
specific message is conducted:
The search for a method to invoke in response to a given message begins with the class of the receiver. If no appropriate
method is found, the search is conducted in the parent class of this class. The search continues up the parent class chain
until either a method is found or the parent class chain is exhausted. In the former case the method is executed; in the
latter case, an error message is issued. If methods with the same name can be found higher in the class hierarchy, the
method executed is said to override the inherited behavior.
Even if the compiler cannot determine which method will be invoked at run time, in many object-oriented
languages, such as Java, it can determine whether there will be an appropriate method and issue an error message
as a compile-time error diagnostic rather than as a run-time message.
If the task of delivering folwers is given to Elizabeth who follow different method in when compare to
florist Flora is an example of one form of polymorphism. As explained, that I do not, and need not, know exactly
what method Flora will use to honor my message is an example of information hiding.
Everything is an object.
An object is a runtime entity in an object oriented programming
Computation is performed by objects communicating with each other. Objects communicate by
sending and receiving messages. A message is a request for action bundled with whatever arguments
may be necessary to complete the task.
Each object has its own memory, which consists of other objects.
Every object is an instance of a class. A class simply represents a grouping of similar objects, such
as integers or lists.
The class is the repository for behavior associated with an object. That is, all objects that are
instances of the same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called the inheritance hierarchy. Memory
and behavior associated with instances of a class are automatically available to any class associated
with a descendant in this tree structure.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 7
Wrapping of data and methods into a single unit (called class)is known as “encapsulation”
Encapsulation makes it possible to treat Object as a blackbox each performing a specific task
without any conceren for internal implementation.
Insulation of the data from direct acess by the program is called as “data hiding”.
Abstraction refers to the act of representing essential features without including background details
or exaplanations
Inheritance is the process by which objects of one class acquire the properties of objects of another
class.Inheritance supports the concept of hierarchical classification as shown below.
Polymorphism means the ability to take more than one form.For example ,an operation may
exhibit different behaviour in different instance.
Figure 1.5:Polymorphism
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role
in the popularity of this language. The features of Java are also known as java buzzwords.
A list of most important features of Java language is given below .
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple:
Secured:
Java is secured because
Robust :
Robust simply means strong. Java uses strong memory management. There is automatic garbage
collection in java. There is exception handling and type checking mechanism in java. All these points
makes java robust.
Architecture-neutral:
Portable :
High-performance:
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower
than a compiled language (e.g., C++)
Distributed :
We can create distributed applications in java. RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares
the same memory. Threads are important for multi-media, Web applications etc
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 11
Platform : Any hardware or software environment in which a program runs, known as a platform. Since Java has
its own Runtime Environment (JRE) and API, it is called platform.
History of Java
Java team members (also known as Green Team), initiated a revolutionary task to develop a language for
digital devices such as set-top boxes, televisions etc. It was best suited for internet programming. Later, Java
technology as incorporated by Netscape.
Firstly, it was called "Greentalk" by James Gosling and file extension as .gt. After that, it was called Oak and
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies. Java is an
island of Indonesia where first coffee was produced (called java coffee).
Applications using Java: There are mainly 4 type of applications that can be created using java
Standalone Application:
o It is also known as desktop application or window-based application. An application that we
need to install on every machine such as media player, antivirus etc. AWT and Swing are used in
java for creating standalone applications.
Web Application:
o An application that runs on the server side and creates dynamic page, is called web application.
Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web applications in
java.
Enterprise Application:
o An application that is distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
Mobile Application:
o An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 12
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at
runtime.implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
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, JRE
and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent
Loads code
Verifies code
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 13
Executes code
Provides runtime environment
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 (i.e. JVM is platform dependent). It is:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
2. Class(Method) Area:Class(Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.
3. Heap:It is the runtime data area in which objects are allocated
4. Stack: Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.Each thread has a private JVM stack, created at the same time as thread. A
new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
5. Program Counter Register:PC (program counter) register. It contains the address of the Java virtual
machine instruction currently being executed.
6. Native Method Stack:It contains all the native methods used in the application
7. Execution Engine:It contains:
1) A virtual processor
2) Interpreter:Readbytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the amount
of time needed for compilation.Here the term compiler refers to a translator from the
instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
1.Open a simple text editor program such as Notepad and type the following content:
2.Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s say, C:\Java
Now let’s compile our first program in the HelloWorld.java file using javac tool.
Syntax: javac programname.java
Type the following command to change the current directory to the one where the source file is stored:
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 15
It’s now ready to run our first Java program. To run java program use following Syntax
That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is no .java or .class
extension). You would see the following output:
Every variable has a type, every expression has a type and all types are strictly define more over every
assignment should be checked by the compiler by the type compatibility hence java language is considered as
strongly typed language. In java, There are two types of Data Types:
byte
short
int
long
float
double
Values of class type are references. Strings are references to an instance of class String.
-9223372036854775808 to
long 8 0
9223372036854775807
2. Non-Primitive Data Types:Derived data types are those that are made by using any other data type and
can make a variable to store multiple values ,for example, arrays.
3. User Defined Data Types: User defined data types are those that user / programmer himself defines.
For example, classes, interfaces.
In java char uses 2 byte in java because java uses unicode system rather than ASCII code system. \u0000
is the lowest range of unicode system.
Unicode System:
Unicode is a universal international standard character encoding that is capable of representing most of the
world's written languages
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 17
1.11 Variables
Introduction of variables:
Name
Value
The binary data contained in memory. The value is interpreted according to the variable's datatype.
Address
The location in memory where the value is stored.
Size
The number of bytes that the variable occupies in memory.
Datatype
The interpretation of the value.
Range
The minimum and maximum values of the variable. The range of a variable depends on its size. In
general, the bigger the size in bytes, the bigger the range.
Declaration of variables:
Syntax:
Datatype variable_name;
Syntax:
Datatype variable_name=value;
Datatype variable_name=Expression;
double a =10.0,b=20.0;
double d=Math.squart(49)+a+b;
Types of Variable
Local Variable
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable .
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
} //end of class
Scope and life time of a variable: The scope determines what objects are visible to other parts of program
and also determine Lifetime of the objects. In java, scope is defined by the class and by the method. The
instance variables and static variables are declared which the class and out of any method ,so this types
variables are available throughout the class The local variables are declared inside the method .so this variables
are available with the block in which there are declared.
The process of converting one data type to another data type is called as Casting
Types of castings:
Casting larger data type into smaller data type may result in a loss of data.
This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the
value narrower.
To create a conversion between two incompatible types, you must use a cast. A cast is
int m=50;
byte n=(byte)m;
When one type of data is assigned to another type of variable, an automatic type conversion
When these two conditions are met, a widening conversion takes place.
Example:
byte b=75;
int a=b;
The int type is always large enough to hold all valid byte values, so no explicit cast statement is
Output: i value is 3
x value is 30.00
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 21
1.12 Arrays
Definition of Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Sytax:
Datatype arrayname[ ];
Or
Datatype[ ] arrayname;
Example :
int a[ ];
int[ ] a; //recommended to use because name is clearly separated from the type int [ ]a;
At the time of declaration we can’t specify the size otherwise we will get compile time error.
Every array in java is an object hence we can create by using new operator.
arrayname=new datatype[size];
Example :
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 22
a= new int[3];
Example:
Diagram:
For every array type corresponding classes are available but these classes are part of java language
and not available to the programmer level.
Rules for creating an Array
Rule 1 :
At the time of array creation compulsory we should specify the size otherwise we will get compile time
error.
Rule 2:
Rule 3 :
If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.
Rule 4:
The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any
other type we will get compile time error.
Rule 5 :
The maximum allowed array size in java is maximum value of int size [2147483647].
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 23
Array initialization:
arrayname[subscript]=value;
Example:
a[0]=10; a[1]=20;a[2]=30;
a[3]=40; a[4]=50;//R.E:ArrayIndexOutOfBoundsException: 4
a[-4]=60;//R.E:ArrayIndexOutOfBoundsException: -4
Diagram:
Note:if we are trying to access array element with out of range index we will get
RuntimeException saying ArrayIndexOutOfBoundsException
Example:
int [] a={10,20,30};//valid
String[] s={"abc","def","jog","lmn”};(valid)
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 24
Whenever we are creating an array every element is initialized with default value automatically.
Example 1:
Array Length:
length Vs length():
length:
length() method:
Example:
System.out.println(x.length);//3
Example:
String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 25
Passing Array to method in java. We can pass the java array to method so that we can reuse the same logic
on any array.
Let's see the simple example to get minimum number of an array using method.
class Testarray2 {
2. Multidimensional Array
In java multidimensional arrays are implemented as array of arrays approach but not matrix form.
Datatype arrayname[ ][ ];
Or
Datatype[ ][ ] arrayname;
int [ ][ ]a; int [ ][ ]a; int a[ ] [ ]; int [ ] [ ]a; int [ ] a[ ]; int [ ]a[ ];
Example :
syntax:
Example:
int a[ ] [ ];
a=new int[3][2];
Syntax
Example1:
a[0]=new int[2];
a[1]=new int[4];
a[2]=new int[3];
Example:
int[][] a={{10,20,30},{40,50}};`
Diagram:
If we want to use this short cut compulsory we should perform declaration, construction and initialization in
a single line. If we are trying to divide into multiple lines then we will get compile time error.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 28
Length variable applicable only for arrays where as length()method is applicable for String objects.
Example :
Diagram:
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print(arr[i][j]+" ");
System.out.println();
}
}
}
Output:1 2 3
245
445
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 29
int[ ][ ][ ] a;
int [ ][ ][ ]a;
int [ ] a[ ][ ];
int [ ][ ]a[ ];
Anonymous Arrays:
Sometimes we can create an array without name such type of nameless arrays are called anonymous arrays.
At the time of anonymous array creation we can’t specify the size otherwise we will get compile time error.
Example :
o Code Optimization : It makes the code optimized, we can retrieve or sort the data easily.
o Random access : We can get any data located at any index position.
o Readability : we can represent multiple values with the same name so that readability of the code
will be improved
o Fixed in size that is once we created an array there is no chance of increasing or decreasing the size
based on our requirement that is to use arrays concept compulsory we should know the size in
advance which may not possible always. We can resolve this problem by using collections.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 30
1.13 Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc 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 −
Show Examples
- (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10
* (Multiplication) Multiplies values on either side of the operator. A * B will give 200
Show Examples
>= (greater than Checks if the value of left operand is greater than or equal to
(A >= B) is not true.
or equal to) the value of right operand, if yes then condition becomes true.
<= (less than or Checks if the value of left operand is less than or equal to the
(A <= B) is true.
equal to) value of right operand, if yes then condition becomes true.
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary
format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Show Examples
Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12
& (bitwise and)
both operands. which is 0000 1100
(A | B) will give 61
| (bitwise or) Binary OR Operator copies a bit if it exists in either operand.
which is 0011 1101
Binary XOR Operator copies the bit if it is set in one operand (A ^ B) will give 49
^ (bitwise XOR)
but not both. which is 0011 0001
Binary Left Shift Operator. The left operands value is moved A << 2 will give 240
<< (left shift)
left by the number of bits specified by the right operand. which is 1111 0000
Binary Right Shift Operator. The left operands value is moved A >> 2 will give 15
>> (right shift)
right by the number of bits specified by the right operand. which is 1111
Shift right zero fill operator. The left operands value is moved
>>> (zero fill A >>>2 will give 15
right by the number of bits specified by the right operand and
right shift) which is 0000 1111
shifted values are filled up with zeros.
Show Examples
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 33
Show Examples
Simple assignment operator. Assigns values from right side operands C = A + B will assign
=
to left side operand. value of A + B into C
Add AND assignment operator. It adds right operand to the left C += A is equivalent
+=
operand and assign the result to left operand. to C = C + A
Divide AND assignment operator. It divides left operand with the C /= A is equivalent to
/=
right operand and assign the result to left operand. C=C/A
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 34
C <<= 2 is same as C
<<= Left shift AND assignment operator.
= C << 2
C >>= 2 is same as C
>>= Right shift AND assignment operator.
= C >> 2
C &= 2 is same as C =
&= Bitwise AND assignment operator.
C&2
Miscellaneous Operators
Conditional Operator ( ? : )
instanceof Operator
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used
to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the
variable. The operator is written as −
Example
publicclassTest {
publicstaticvoid main(String args[]){
int a, b;
a =10;
b =(a ==1)?20:30;
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 35
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}
Output
Value of b is : 30
Value of b is : 20
instanceof Operator
This operator is used only for object reference variables. The operator checks whether the object is of a particular
type (class type or interface type). instanceof operator is written as −
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface
type on the right side, then the result will be true. Following is an example −
Example
publicclassTest{
publicstaticvoid main(String args[]) {
String name ="James";
// following will return true since name is type of String
boolean result = name instanceof(String);
System.out.println( result );
}
}
Output
true
This operator will still return true, if the object being compared is the assignment compatible with the type
on the right.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 36
Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.
1.14 Expressions
Definition: An expression is a series of variables, operators, and method calls (constructed according to the
syntax of the language) that evaluates to a single value
char ch = 'S';
...
if (Character.isUpperCase(aChar)) //Block
... }
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 37
A control statement works as a determiner for deciding the next task of the other statements whether to execute
or not. An ‘If’ statement decides whether to execute a statement or which statement has to execute first between
the two. In Java, the control statements are divided into three categories which are selection statements, iteration
statements, and jump statements. A program can execute from top to bottom but if we use a control statement.
We can set order for executing a program based on values and logic.
Simple if Statement
if…else Statement
Nested if statement
if...else if…else statement
Switch statement
While
Do…while
For
For-Each Loop
Break
Continue
Return
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 38
Decision making statements are statements which decides what to execute and when. They are similar to decision
making in real time. Control flow statements control the flow of a program’s execution. Here flow of execution
will be based on state of a program. We have 4 decision making statements available in Java.
Simple if Statement :
Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of code should
be executed based on the condition.
Syntax:
if (condition)
{
Statemen 1; //if condition becomes true then this will be executed
}
statement 2; //this will be executed irrespective of condition becomes true
or false
Example:
class ifTest {
public static void main(String args[]) {
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}
Output:
After if statement
if…else Statement :
In if…else statement, if condition is true then statements in if block will be executed but if it comes out as false
then else block will be executed.
Syntax: if (condition) {
}
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 39
Example:
class ifelseTest {
public static void main(String args[]) {
int x = 9;
if (x > 10)
System.out.println("i is greater than 10");
else
System.out.println("i is less than 10");
System.out.println("After if else statement");
}
}
Output:
i is less than 10
After if else statement
Nested if statement :
Nested if statement is if inside an if block. It is same as normal if…else statement but they are written inside
another if…else statement.
Syntax: if (condition1)
{
Statemen 1; //executed when condition1 is true
if (condition2)
{
Statement 2; //executed when condition2 is true
}
else
{
Statement 3; //executed when condition2 is false
}
}
Example:
class nestedifTest {
public static void main(String args[]) {
int x = 25;
if (x > 10) {
if (x%2==0)
System.out.println("i is greater than 10 and even number");
else
System.out.println("i is greater than 10 and odd number");
}
else {
System.out.println("i is less than 10");
}
System.out.println("After nested if statement");
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 40
}
}
Output:
i is greater than 10 and odd number
After nested if statement
if…else statement :
if…else if statements will be used when we need to compare the value with more than 2 conditions. They are
executed from top to bottom approach. As soon as the code finds the matching condition, that block will be
executed. But if no condition is matching then the last else statement will be executed.
if (condition1) {
Syntax: Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
Statement 2; // if condition2 becomes true then this will be executed
}
....
....
else {
Statement 3; //executed when no matching condition found
}
Example:
class ifelseifTest {
public static void main(String args[]) {
int x = 2;
if (x > 10) {
System.out.println("i is greater than 10");
}
else if (x <10)
System.out.println("i is less than 10");
}
else {
System.out.println("i is 10");
}
System.out.println("After if else if ladder statement");
}
}
Output:
i is less than 10
After if else if ladder statement
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 41
Switch statement :
Java switch statement compares the value and executes one of the case blocks based on the condition. It is same
as if…else if ladder. Below are some points to consider while working with switch statements:
» case value must be of the same type as expression used in switch statement
» case value must be a constant or literal. It doesn’t allow variables
» case values should be unique. If it is duplicate, then program will give compile time error
class switchDemo{
public static void main(String args[]) {
int i=2;
switch(i)
{
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
case 3:
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
System.out.println("i is not in the list");
break;
}
}
}
Output:
i is 2
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 42
Looping statements are the statements which execute a block of code repeatedly until some condition meet to the
criteria. Loops can be considered as repeating if statements. There are 3 types of loops available in Java.
While :
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes the
body of loop. This is repeated until the condition becomes false. Condition in while loop must be given as a
Boolean expression. If int or string is used instead, compile will give the error.
Syntax:
Initialization;
while (condition)
{
statement1;
increment/decrement;
}
Example:
class whileLoopTest
{
public static void main(String args[])
{
int j = 1;
while (j <= 10) {
System.out.println(j);
j = j+2;
}
}
}
Output:
1 3 5 7 9
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 43
Do…while :
Do…while works same as while loop. It has only one difference that in do…while, condition is checked after the
execution of the loop body. That is why this loop is considered as exit control loop. In do…while loop, body of
loop will be executed at least once before checking the condition
Syntax: do
{
statement1;
}while(condition);
Example:
class dowhileLoopTest {
int j = 10;
do {
System.out.println(j);
j = j+1;
Output: 10
For Statement :
It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in code as
initialization of a variable, a condition and increment/decrement are declared only in a single line of code. It is
easy to debug structure in Java.
statement;
}
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 44
Example:
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:
For-Each Loop :
For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to
increment the value. It returns the elements from the array or collection one by one.
Example:
class foreachDemo {
for (int i : a) {
System.out.println(i);
Output:
10
15
20
25
30
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 45
Branching statements jump from one statement to another and transfer the execution flow. There are 3 branching
statements in Java.
Break :
Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in
loop to stop the execution and comes out of loop. When there are nested loops then break will terminate the
innermost loop.
Example:
class breakTest {
if (j == 4)
break;
System.out.println(j);
System.out.println("After loop");
Output:
4
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 46
After loop
Continue :
Continue statement works same as break but the difference is it only comes out of loop for that iteration and
continue to execute the code for next iterations. So it only bypasses the current iteration.
Example:
class continueTest {
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
Output:
02468
Return :
Return statement is used to transfer the control back to calling method. Compiler will always bypass any sentences
after return statement. So, it must be at the end of any method. They can also return a value to the calling method.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 47
Definition:
A class is a sort of template which has attributes and methods. An object is an instance of a class, e.g.
Ram is an object of type Person.
class classname {
// declare instance variables
type var1;
type var2;
// ... type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}
The classes we have used so far had only one method, main(), however not all classes specify a
main method. The main method is found in the main class of a program (starting point of program).
A Simple Class
Let’s begin our study of the class with a simple example. Here is a class called Box that defines three instance
variables: width, height, and depth. Currently, Box does not contain any methods (but some will be added soon).
class Box {
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 48
double width;
double height;
double depth;
As stated, a class defines a new type of data. In this case, the new data type is called Box. You will use this
name to declare objects of type Box. It is important to remember that a class declaration only creates a template;
it does not create an actual object. Thus, the preceding code does not cause any objects of type Box to come into
existence.
To create an object of the class we use new keyword as shown below syntaxt
After this statement executes, mybox will be an instance of Box. Thus, it will have “physical” reality. For the
moment, don’t worry about the details of this statement.
As mentioned earlier, each time you create an instance of a class, you are creating an object that contains its
own copy of each instance variable defined by the class. Thus, every Box object will contain its own copies of
the instance variables width, height, and depth. To access these variables, you will use the dot (.) operator. The
dot operator links the name of the object with the name of an instance variable.
object.member=value;
For example, to assign the width variable of mybox the value 100, you would use the following statement:
mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within the mybox object the
value of 100. In general, you use the dot operator to access both the instance variables and the methods within an
object.
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box {
double width;
double height;
double depth;
class BoxDemo {
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
Output:
Volume is 3000