You are on page 1of 32

UNIT-11

UNIT- I
Object Oriented System Development: Understanding Object Oriented Development, Understanding Object
Concepts, Benefits of Object Oriented Development.
Java Programming Fundamentals: Introduction, Overview of Java, Data types, Variables and Arrays, Operators,
Control statements, Classes, Methods, Inheritance, Packages and Interfaces.

Object Oriented System Development


1. HISTORY OF OBJECT-ORIENTED SYSTEM DEVELOPMENT
 Object-oriented programming is today what structured programming was in the 1970’s
 The Object and object attribute idea first conceived in the 1950’s for A.I. ( Artificial Intelligence )
 The real movement began in 1966 with the introduction of the Simula language
 Palo Alto Research Center (PARC) developed Smalltalk in the early 1970’s
o Smalltalk is considered the first truly object-oriented language
 Led other languages to support object-oriented programming
 examples: Objective-C, C++, Self, Eiffel, and Flavors
 In 1980 Grady Booch pioneered the concept of object-oriented design (OOD)

2. MOTIVATION FOR THE DEVELOPMENT OF OBJECT-ORIENTED SYSTEM

 Direct mapping of concepts in the problem domain to software units and their interfaces
 Viewing the world as objects is more natural since it is closer to the way humans think
 Objects are more stable than functions…
 Supports information hiding, data abstraction, and encapsulation
 Easily modified, extended, and maintained

3. OBJECT-ORIENTED MODEL

 The fundamental idea behind object-oriented languages is to combine into a single program entity
both data and the functions that operate on that data. Such an entity is called an object.
 An object's functions, called member functions in C++ (because they belong to a particular class of
objects), typically provide the only way to access its data.
 If you want to read a data item in an object, you call a member function in the object. It will read the
item and return the value to you.
 You can't access the data directly.
 The data is hidden, so it is safe from accidental alteration.
 Data and its functions are said to be encapsulated into a single entity.
 Encapsulation and data hiding are key terms in the description of object-oriented languages.

Java Programming Fundamentals


UNIT-12

1. Reason behind origin of JAVA:


 In 1990, Sun Microsystems (US) had initiated a project to develop a software for consumer electronic
devices which can be controlled by a remote.( Now-a-days we are able to control TV,AC etc., using
remote. The concept was similar to this.). This project of developing the software was given a name as
STEALTH PROJECT. Later it was named as GREEN PROJECT.
 In 1991, several computer experts like JAMES GOSLING, MIKE SHERADIN, PATRICK NAUGHTON, BILLY JOY
etc., started working on this project.
 James Gosling thought that C/C++ would be enough to develop this project. But the problem was, both C
and C++ were system dependent languages.
 So Gosling started to develop a totally new programming language, that was system independent. That
language was initially named as OAK. Since that name was already registered by some other company, the
name was changed to JAVA.

2. History of JAVA:
 In 1995, Sun Microsystems officially announced the first version of java programming language and also
Hot Java ( Web-Runner) the firs web-browser to run java applications.
 Later several companies like Netscape INC., Microsoft have developed their own web-browsers which
would support java. Some of the web-browsers were Netscape Navigator, Internet Explorer etc.,. Now-a-
days, many other browsers like Google Chrome, Mozilla etc. are also being used.
 On 23rd January 1995, first version of Java i.e., jdk1.0 was released.
‘” jdk “ stands for “ java development toolkit “. After jdk1.0 we have jdk1.1, jdk1.2,…….jdk1.6 versions

3. Why this programming language has got the name JAVA?


 James gosling and his team members were consuming lots of coffee, while working on this language.
 They felt that they were able to develop language in a better way, because of the good quality of coffee
they consumed.
 At that time period, coffee powder was exported to entire world from a place called as JAVA ISLAND.
 Hence, they fixed the name of the language as JAVA. Symbol for java language is coffee cup & saucer

4. Why C and C++ are called as System Dependent Languages?


UNIT-13

• Consider a program written in C-language. It will be saved with .c extension.


• Ex: demo.c
• Then the instruction is given to compile the program that is, Alt+F9.(object code)
• After compilation .obj file is generated.
• In the next stage, .exe file is generated, program is loaded into RAM and then executed.
• In .obj file, first the statement will be :- #include<stdio.h>
• When we run the program, the C compiler goes to the standard library and searches for stdio.h header
file. If the file is found, then C compiler copies entire code in stdio.h ( Machine Level Language) into the
C-program.
• Suppose, if our program contains 25 lines of code and stdio.h file contains 500 lines of code then our
program in Machine Level Language contains 525 lines of code. This file is known as .exe file. This file is
full-fledged file hat contains total program in Machine Level Language format. These instructions will be
understood by the compiler micro-processor. It executes he program and gives the output. There are
many micro processors developed by many companies. Ex: intel processor.

• Every microprocessor can recognize a set of instructions known as Instruction Set of that micro processor.
These Instruction Sets will be different for each and every micro processor. That is, if we generate an
executable file (.exe) with Pentium processor then the code in .exe file can be understood only by
Pentium processor.
• If we try to execute that .exe file using another processor then we will not be successful. Similarly, if .exe
file is generated using unix Operating System then it cannot be executed on other operating system like
DOS. (Disc Operating System).

• Reason : Every Operating system stores data and instructions in various formats.
 Ex: addition of two numbers
 Instruction format (set) in DOS : add a,b
 Instruction format (set) in Unix : a add b

• So, if we try to execute a add b instruction on DOS the it will not be executed.
• Thus it is not possible to execute same .exe file on all operating systems. That is, C/C++ programs cannot
be executed on a different configuration.
• Now, if we develop any software using C/C++ and distributes it on internet, then .exe files can be
downloaded from internet, but those files cannot run on our computer, since the configuration may not
be the same.
• Thus, in order to develop softwares for internet, we need System Independent Language and that is JAVA.

5. Why Java is System Indepndent?


• After compiling the java program a .class is generated. This .class file contains byte code. Here the size of
each instruction is 1 byte that is 8-bits. People who have developed have java specified set of instructions,
to express any operations. There will be fixed number of byte code instructions say around 200. Any
program in java can be re-written using these instructions. A file re-written with these instructions in
known as .class file that is BYTE CODE.

• Therefore, .class file contains BYTE CODE for the SOURCE CODE present in the program written by user.
UNIT-14

• But, micro processor cannot understand these instructions and cannot execute them. Infact, these
instructions are meant for JVM i.e. JAVA VIRTUAL MACHINE.

• Byte code will be understood by JVM. JVM is a program written to understand byte code instructions and
convert them into machine code.

• JVM will be freely available on internet and can be downloaded for use.

• Ex: Name of the program  demo.java ( java programs with .java extension ).
 Processor  Pentium
 After compiling  demo.class

• demo.class is given to JVM. Now JVM converts this byte code into a format that is understood by the
pentium processor. So, Pentium processor executes the program and displays output. Also, JVM
understands the type of operating system in computer and performs the instructions according to it.

• Now if we send demo.class file to another computer having different processor and OS then JVM of that
computer will convert byte code into a format that is understood by the processor in that computer.

• Thus, the same .class file can be executed on any computer, with any processor and OS, provided if JVM is
available on that computer. Byte code is system independent. It can be created on any computer by using
these 200 instructions only.

• JVM is system dependent. Since it has to interact with the processor and OS of that computer, that is, if
we have windows version of OS in our computer then we should use windows version of JVM only.

• Since, java programs can be executed on any Processor/OS combination, therefore, JAVA is said to be
SYSTEM or PLATFORM INDEPENDENT PROGRAMMING LANGUAGE.

• Therefore, if a software is developed using JAVA then .class files can be downloaded from internet and
can be executed on any computer without any problem. Thus, in order to develop software for internet,
JAVA language is suitable.

• JAVA VIRTUAL MACHINE is a interpreter of byte code. Translating java program into byte code is very
useful to run program on any OS because though details of JVM differ from OS to OS, but all will interpret
the same byte code. Usage of byte code, enables java run-time system to execute program very fast.

6. JVM Architecture:

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 plateform dependent).
UNIT-15

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider is


independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, and
instance of JVM is created.

What it does?

The JVM performs following operation:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.
UNIT-16

1) Class loader:

 Class loader is a subsystem of JVM that is used to load class files.

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.


UNIT-17

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:
 A virtual processor
 Interpreter: Read byte code stream then execute the instructions.
 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.

7. Classification of JAVA :

Sun Microsystems divided java into 3 parts:-

 JAVA Standard Edition contains basic core java concepts. This edition is used to develop applets.

 JAVA Enterprise Edition contains many concepts and classes that are beyond Java SE. it concentrates
on providing business solutions on network.

 JAVA Micro Edition is for developers, who develop code for portable devices such as cell phones. This
code should occupy less memory and small in size.
UNIT-18

8. Features of JAVA:

1. Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important
key feature of java language that makes java as the most powerful language. Not even a single language is
idle to this feature but java is more closer to this feature. The programs written on one platform can run
on any platform provided the platform must have the JVM. 
2. Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides the
powerful exception handling and type checking mechanism as compare to other programming languages.
Compiler checks the program whether there any error and interpreter checks any run time error and
makes the system secure from crash. All of the above features makes the java language robust.
3. Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call
functions on these protocols and can get access the files from any remote machine on the internet rather
than writing codes on their local system.
4. Portable
The feature Write-once-run-anywhere  makes the java language portable provided that the system must
have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the
processor. These features makes the java as a portable language.
5. Secure
security is an important issue for a language that is used for programming on internet. Threat for several
viruses will be present always. Java programs not only verify all memory access but also ensures that
there are no viruses communicated with applet. The absence of pointers in java ensures that programs
cannot gain access to memory locations without proper authorization.
6. Dynamic
While executing the java program the user can get the required files dynamically from a local drive or
from a computer thousands of miles away from the user just by connecting with the Internet.
7. Compiled and Interpreted
A computer language is either compiled or interpreted in general. Java combines both these approaches
thus making java a two-stage system. First, java converts source code into byte code. Second java
interpreter (JVM) generates machine code that can be executed by the machine. Thus, java is both
compiled and interpreted.
8. Multi-Threaded
Multi-Threaded means handling multiple tasks simultaneously. Multi-Threaded programs are supported
by java. It means there is no need to wait for the application to finish one task before beginning the other
task.
Ex: we check our e-mails and at the same time we can run a movie clip.
This feature, greatly improves the interactive performance of graphical applications.

9. Naming Conventions in JAVA


Naming conventions in java specify the rules to be followed while declaring or writing names of packages, classes
or methods.
UNIT-19

Name Convention

class name should start with uppercase letter and be a noun e.g. String, Color, Button, System,
Thread etc.

interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote,
ActionListener etc.

method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(),
println() etc.

variable name should start with lowercase letter e.g. firstName, orderNumber etc.

package name should be in lowercase letter e.g. java, lang, sql, util etc.

constants should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.


name

10.GENERAL STRUCTURE OF A JAVA PROGRAM

Documentation section

Package statements

Import statements
optional
Interface statements

Class definition

main method class


{ essential
Definition of main method
}
UNIT-110

1. Documentation section: contains set of comment lines giving name and explanation about program. This
increases readability of the program.

In java comments can be written in 2 ways :

 Single-line comments (/*……….*/)


 Double line comments(// )

2. Package statement : is the 1st statement that is allowed in java program. This statement specifies or
declares that the classes defined in the program will belong to this particular package. Some of the
packages in java are :
java.lang, java.io, java.awt etc.,,,

3. Import statement : will be used in java in order to use the classes and methods of that package. Import
statement in java is similar to #include statement in c and c++.
ex: import java . io.*; now, all classes and methods of io package can be accessed in our program
Note: by default java.lang ( language) package will be imported into our java program.

Difference between #include and import statement

 #include in c/c++ copies the entire code o the header file into our program (.exe file)
 import statement makes JVM to go to standard library , execute the program there and then
substitute the result in the program.

4. Interface statement : interface is like a class which includes only method declarations but not definitions.
5. Class definition and main() method class : after importing package we have to write classes. A java
program may contain multiple class definitions. Since java is OOP language any program in java cannot be
written without using class or object.

Difference between class in c++ and class in java

 “private” is the access specifier in c++ by default.


 In java class “public” is the default access specifier.

If string args[ ] is not written in main() then we can compile the program but can’t execute it since, JVM can’t
recognize main() method as starting point of execution with out string args[]. Values passed to string args[] are
called as ARGUMENTS.

11.Sample program:
UNIT-111

Write a program to print a line of text

Aim : To print a line of text

Source Code :

/* This is my first java program. This will print 'Hello World' as the output */

class MyFirstJavaProgram
{

public static void main(String args[])


{
System.out.println("Hello World"); // prints Hello World
}
}

To save program : MyFirstJavaProgram.java

To compile program : javac MyFirstJavaProgram.java

To run the program : java MyFirstJavaProgram

12. Variables, Constants, Literals and Escape Sequences in Java

Declaring Variables

• Variables hold one value at a time, but that value can change
• Syntax is:

dataType identifier;
or
dataType identifier1, identifier2, …;

Assigning Values to Variables

•Assignment operator =
– Value on the right of the operator is assigned to the variable on the left
– Value on the right can be a literal (text representing a specific value), another variable, or an
expression (explained later)
• Syntax:
dataType variableName = initialValue;
UNIT-112

or
dataType variable1 = initialValue1, variable2 = initialValue2, …;

Types of Variable

There are three types of variables in java

 local variable
 instance variable
 static variable

Local Variable

A variable that is declared inside the method is called local variable.

Instance Variable

A variable that is declared inside the class but outside the method is called instance variable . It is not declared
as static.

Static variable

A variable that is declared as static is called static variable. It cannot be local.

Example:

class  A
{  
int data=50; //instance variable  
static  int m=100; //static variable  
void method()
{  
int n=90; //local variable  
}  
} //end of class  

Constants
UNIT-113

• Value cannot change during program execution


• Syntax:
final dataType constantIdentifier = assignedValue;

Note: assigning a value when the constant is declared is optional. But a value must be assigned before the constant
is used.

13.Data types in Java


UNIT-114

 In Java, the data type used to store characters is char.


 char in Java is not the same as char in C or C++.
 In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java.
UNIT-115

 Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set
that can represent all of the characters found in all human languages.
 It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul, and many more.
 For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536.
There are no negative chars.
 The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit
character set, ISO-Latin-1, ranges from 0 to 255.
 Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use
Unicode to represent characters.
 Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or
French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for
global portability.

String data types:

 String is collection of characters.


Ex: String s=”hello’;
 A class named String is present in java where all methods are provided to manipulate strings. Any string is
considered as an object of string class.
 In c/c++ string is defined as array of characters terminated by null character.
 But in java character and string data types separate.

Note: string is a class but we are taking it as object also since, we consider every class is a user-defined data type.

14.Operators in Java

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
 Other Operators

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:
UNIT-116

Operato
Description Example
r

+ Addition - Adds values on either A + B will give 30


side of the operator

- Subtraction - Subtracts right hand A - B will give -10


operand from left hand operand

* Multiplication - Multiplies values A * B will give 200


on either side of the operator

/ Division - Divides left hand B / A will give 2


operand by right hand operand

% Modulus - Divides left hand B % A will give 0


operand by right hand operand
and returns remainder

++ Increment - Increase the value of B++ gives 21


operand by 1

-- Decrement - Decrease the value B-- gives 19


of operand by 1

Relational Operators:

There are following relational operators supported by Java language

Operato
Description Example
r

== Checks if the value of two operands (A == B) is not true.


are equal or not, if yes then
condition becomes true.

!= Checks if the value of two operands (A != B) is true.


are equal or not, if values are not
equal then condition becomes true.

> Checks if the value of left operand (A > B) is not true.


is greater than the value of right
operand, if yes then condition
becomes true.

< Checks if the value of left operand (A < B) is true.


is less than the value of right
operand, if yes then condition
becomes true.
UNIT-117

>= Checks if the value of left operand (A >= B) is not true.


is greater than or equal to the
value of right operand, if yes then
condition becomes true.

<= Checks if the value of left operand (A <= B) is true.


is less than or equal to the value of
right operand, if yes then condition
becomes true.

Bitwise Operators:

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 perform 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

The following table lists the bitwise operators:

Operator Description Example

& Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
the result if it exists in both operands. 1100

| Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011 1101


exists in eather operand.

^ Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011 0001
it is set in one operand but not both.

~ Binary Ones Complement Operator is (~A ) will give -60 which is 1100 0011
unary and has the efect of 'flipping'
bits.

<< Binary Left Shift Operator. The left A << 2 will give 240 which is 1111
UNIT-118

operands value is moved left by the 0000


number of bits specified by the right
operand.

>> Binary Right Shift Operator. The left A >> 2 will give 15 which is 1111
operands value is moved right by the
number of bits specified by the right
operand.

>>> Shift right zero fill operator. The left A >>>2 will give 15 which is 0000
operands value is moved right by the 1111
number of bits specified by the right
operand and shifted values are filled
up with zeros.

Logical Operators:

The following table lists the logical operators:

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non zero then then condition
becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands are non zero then then condition
becomes true.

! Called Logical NOT Operator. Use to reverses !(A && B) is true.


the logical state of its operand. If a condition is
true then Logical NOT operator will make false.

Assignment Operators:

There are following assignment operators supported by Java language:

Operato
Description Example
r

= Simple assignment operator, C = A + B will assigne value of A + B into C


Assigns values from right side
operands to left side operand

+= Add AND assignment operator, It C += A is equivalent to C = C + A


adds right operand to the left
operand and assign the result to
left operand

-= Subtract AND assignment C -= A is equivalent to C = C - A


UNIT-119

operator, It subtracts right


operand from the left operand
and assign the result to left
operand

*= Multiply AND assignment C *= A is equivalent to C = C * A


operator, It multiplies right
operand with the left operand
and assign the result to left
operand

/= Divide AND assignment operator, C /= A is equivalent to C = C / A


It divides left operand with the
right operand and assign the
result to left operand

%= Modulus AND assignment C %= A is equivalent to C = C % A


operator, It takes modulus using
two operands and assign the
result to left operand

<<= Left shift AND assignment C <<= 2 is same as C = C << 2


operator

>>= Right shift AND assignment C >>= 2 is same as C = C >> 2


operator

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and C ^= 2 is same as C = C ^ 2


assignment operator

|= bitwise inclusive OR and C |= 2 is same as C = C | 2


assignment operator

Other Operators
There are few other operators supported by Java Language.

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 :

variable x = (expression) ? value if true : value if false

Following is the example:

public class Test {


public static void main(String args[]){
UNIT-120

int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This would produce following result:

Value of b is : 30
Value of b is : 20

instance Of 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 wriiten as:

( Object reference variable ) instanceOf (class/interface type)

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 the example:

String name = = 'James';


boolean result = name instanceOf String;
// This will return true since name is type of String

This operator will still return true if the object being compared is the assignment compatible with the type on the
right. Following is one more example:

class Vehicle {

public class Car extends Vehicle {


public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}

This would produce following result:

true
UNIT-121

15. Precedence of operators in Java

Category  Operator  Associativity 


Postfix  () [] . (dot operator) Left to right 
Unary  ++ - - ! ~ Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   >> >>> <<   Left to right 
Relational   > >= < <=   Left to right 
Equality   == !=  Left to right 
Bitwise AND  &  Left to right 
Bitwise XOR  ^  Left to right 
Bitwise OR  |  Left to right 
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left 
Comma  ,  Left to right 

16. Loops in Java

Java has very flexible three looping mechanisms.

 while Loop

 do...while Loop

 for Loop

APART FROM THE ABOVE 3 WE HAVE ANOTHER LOOP CALLED AS for-each loop

While Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.
UNIT-122

Syntax:

The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true then the actions inside the loop will be executed.

This will continue as long as the expression result is true.

Here key point of the while loop is that the loop might not ever run. When the expression is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be executed.

do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once
before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute
again. This process repeats until the Boolean expression is false.

for Loop: (index based retrieval)

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific
number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:
UNIT-123

The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

1. The initialization step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement past the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This
statement allows you to update any loop control variables. This statement can be left blank, as long as a
semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the
for loop terminates.

for-each loop

It repeatedly executes a group of statements for each statement of collection.

It works in jdk1.5 and above versions. (object based retrieval)

Syntax:

The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements
}

 Declaration . The newly declared block variable, which is of a type compatible with the elements of the
array you are accessing. The variable will be available within the for block and its value would be the same
as the current array element.
 Expression . This evaluate to the array you need to loop through. The expression can be an array variable
or method call that returns an array.

break Keyword:
UNIT-124

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch
statement.

The break keyword will stop the execution of the innermost loop and start executing the next line of code after the
block.

Syntax:

The syntax of a break is a single statement inside any loop:

break;

Continue Keyword:

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to
the next iteration of the loop.

 In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.
 In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:

The syntax of a continue is a single statement inside any loop:

continue;

WHY goto STATEMENTS ARE NOT AVAILABLE IN JAVA?

 Branch statements explicitly redirect the flow of program execution.


 The most infamous branch statement in the history of computing is goto.
 In Java, goto is an unimplemented keyword, so it cannot be used in Java programs. In other languages,
goto is used to redirect program execution to another line of code in the program by specifying a line
number or other type of label.
 In Java, break, continue, and label: fill the role of goto, but without many of goto's negatives.
 return is a branching statement that redirects execution out of the current method and back to the calling
method. It also returns a value to the calling method.
 This value is either a primitive, object, or void. void is used to return execution without returning a value.
 Also, whatever the return value is, its type must match the return type listed in the method declaration.

17. Selection or Decision making statements in Java


UNIT-125

if Statement:

An if statement consists of a Boolean expression followed by one or more statements.

Syntax:

The syntax of an if statement is:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

 if...else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean expression is
false.

Syntax:

The syntax of an if...else is:

if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
Else
{
//Executes when the Boolean expression is false
}

 if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to test various
conditions using single if...else if statement.

When using if , else if , else statements there are few points to keep in mind.

 An if can have zero or one else's and it must come after any else if's.

 An if can have zero to many else if's and they must come before the else.

 Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

The syntax of an if...else is:


UNIT-126

if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
//Executes when the Boolean expression 3 is true
}
else
{
//Executes when the none of the above condition is true.
}

Nested if...else Statement:

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or
else if statement.

Syntax:

The syntax for a nested if...else is as follows:

if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){

//Executes when the Boolean expression 2 is true


}
}

Switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case,
and the variable being switched on is checked for each case.

Syntax:

The syntax of enhanced for loop is:


UNIT-127

switch(expression)
{
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:

 The variable used in a switch statement can only be a byte, short, int, or char.

 You can have any number of case statements within a switch. Each case is followed by the value to be
compared to and a colon.

 The value for a case must be the same data type as the variable in the switch and it must be a constant or
a literal.
 When the variable being switched on is equal to a case, the statements following that case will execute
until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the next line
following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall throughto
subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the switch. The
default case can be used for performing a task when none of the cases is true. No break is needed in the default
case.

18. Arrays in Java

An array is a container object that holds a fixed number of values of a single type. The length of an array is
established when the array is created. After creation, its length is fixed. You've seen an example of arrays already,
in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of ten elements


UNIT-128

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the
above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index
8.

 How to declare an array ?

You can create an array by using the new operator with the following syntax:

Array_name = new dataType[Size of the array];

The above statement does two things:

 It creates an array using new dataType[Size of the array];


 It assigns the reference of the newly created array to the variable Array_name

 Declaring Array Variables:

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of
array the variable can reference. Here is the syntax for declaring an array variable:

dataType []array_name ; .

or

dataType array_name[];

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
combined in one statement, as shown below:
dataType []Array_name = new dataType[Size of the array];

Alternatively way of creating array is:

dataType[]Array_name = {value0, value1, ..., valuek};

 Length property of array:

 Java array class comes up with length() property by which you can get size of java array.

 The java array length returns ( integer value) number of total elements in an array.

 Length property of array can be used while accessing arrays using loops.

Syntax of java length method is: Array_name.length()


UNIT-129

Example of length property of array:

class Array_Length
{
public static void main(String args[])
{
// Try with a int array
int[] num={10,20,30,40,50,60,70,80,90,100};

// Print length of array


System.out.println("Length of int array in Java is: "+num.length);

// Print the array


for(int i=0;i<num.length;i++)
System.out.println(num[i]);

// Try with a char array


char[]  c={'a','b','c','d','e','f','g','h','i','j','k'};

// Print the array


for(int i=0;i<c.length;i++)
System.out.println(c[i]);

// Print length of array


System.out.println("Length of char array in Java is: "+c.length);

}
}

Output
------------------------------------

Length of int array in Java is: 10


10
20
30
40
50
60
70
80
90
100
a
b
UNIT-130

c
d
e
f
g
h
i
j
k
Length of char array in Java is: 11

 Copying Arrays

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src, int src_Pos, Object dest, int dest_Pos, int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify
the starting position in the source array, the starting position in the destination array, and the number of array
elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It
uses arraycopy to copy a subsequence of array components into a second array:

class ArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };

char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);

System.out.println(new String(copyTo));
}
}

The output from this program is:

caffein
UNIT-131

19. Command Line Arguments


Java application can accept any number of arguments directly from the command line.

The user can enter command-line arguments when invoking the application.

When running the java program from java command, the arguments are provided after the name of the class
separated by space.

Program to demonstrate command line arguments

class command
{
public static final void main(String args[])
{
for (int i=0;i<args.length;++i)
{
System.out.println( args[i] );
}
}
}

Output
UNIT-132

You might also like