Module1 New
Module1 New
Module1 New
INTRODUCTION TO JAVA
Overview Of Java
Java is a OOPS based programming language.Java was designed to be easy for the professional programmer to learn
and use effectively.If you already understand the basic concepts of OOPS, learning Java will be even easier. The
ability to create robust programs was given high priority in the design of Java.In a well written Java program, all
run-time errors can and should be managed by your program. Java enables the creation of cross-platform programs
by compiling into an intermediate representation called Java bytecode. This code can be interpreted on any system
that provides a Java Virtual Machine.
1
Module1 java programming BCA
The data of an object can be accessed only by the functions associated with that object.Functions of one
object can access the functions of another objects.
Characteristics of Object-Oriented Programming
When a program is executed, the objects interact by sending messages to one another.
2
Module1 java programming BCA
If fruit has been defined as a class, then the statement
fruit mango;
will create an object mango belonging to the class fruit.
Once a class has been defined, we can create any number of objects belonging to that class.
o Abstraction refers to the act of representing essential features without including the background
details or explanations
o Since the classes use the concept of data abstraction, they are known as Abstracted Data Types
(ADT).
o The wrapping up of data and functions into a single unit is known as encapsulation.
o The data is not accessible to the outside world, and only those functions which are wrapped in the
class can access it.
o Eg:
o Request is made for the data and data is handed over by the members of the requested department.
o This insulation of the data from direct access by the program is called data hiding or information
hiding.
Inheritance
o Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
3
Module1 java programming BCA
o Each derived class shares common characteristics with the class from which it is derived
o We can add additional features to an existing class without modifying it. By deriving new class from
existing one. The new class will have the combined features of both the classes.
Polymorphism
The behavior depends upon the types of data used in the operation.
For e.g., consider the operation of addition of two numbers,the operation will generate a sum. If the
operands are strings,then the operation would produce a third string by concatenation.
add( 3, 5) gives 8
Using a single method name to perform different types of tasks is known as method overloading
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding ( late binding ) means that the code associated with a given procedure call is not known
until the time of the call at run-time.
It is associated with polymorphism and inheritance.
Message Passing
o It is a process of invoking an operation on an object.in response to a message the corresponding
method is executed in the object
o An oop consists of a set of objects that communicate with each other.
o Oop involves the following steps:
o Creating classes that define objects and their behaviour.
o Creating objects from class definitions.
o Establishing communication among objects.
o Objects communicate with one another by sending and receiving information.
o A message for an object is a request for execution of a procedure.
o The receiving object will invoke a function and generates results.
o Message passing involves specifying:
o The name of the Object.
o The name of the method.
4
Module1 java programming BCA
o The information to be send.
5
Module1 java programming BCA
anywhere on the network ,Java compiler generates an architecture-neutral object file format, which makes the
compiled code to be executable on many processors, with the presence of Java runtime system.The Java compiler
does this by generating bytecode instructions which is not depend on any particular computer architecture. Rather,
they are designed to be both easy to interpret on any machine and easily translated into native machine code. Their
goal while developing java was write once; run anywhere, anytime, forever.
Platform independent and portable: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte
code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
Being architectural-neutral and having no implementation dependent aspects of the specification makes Java
portable.
Secure: With Java's secure feature, it enables to develop virus-free, tamper-free systems. Absence of pointers in java
ensures that program cannot gain access to memory locations without proper authorization.
Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish
this, Java supports multithreaded programming, which allows you to write programs that do many things
simultaneously. This means that we need not wait for the application to finish one task before beginning another.
The Java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that
enables you to construct smoothly running interactive systems.
InterpretedandHighPerformance
Usually computer languages are either compiled or interpreted.Java enables the creation of cross-platform programs
by compiling into an intermediate representation called Java bytecode. This code can be interpreted on any system
that provides a Java Virtual Machine. 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. Java run-time systems
that provide this feature lose none of the benefits of the platform-independent code.
Distributed
Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact,
accessing a resource using a URL is not much different from accessing a file. The original version of Java (Oak)
included features for intra address- space messaging. This allowed objects on two different computers to execute
procedures remotely.
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. Java programs support functions written in other languages such as c and c++.this
functions are known as native methods.native methods link dynamically at runtime.
6
Module1 java programming BCA
everything from simple animated graphics to complex games and utilities. An applet is downloaded on demand
without further interaction with user .If the user clicks on a link that contains applet, the applet will be automatically
downloaded and run in browser. An applet is actually a tiny java program, dynamically downloaded across the
network, just like an image, sound file, or video clip.
Bytecode
The output of a java compiler is a not executable code
Java compiler compile the source code and convert it in to an intermediate code which is highly optimized
set of instructions known as Bytecode for a machine that does not exist. This machine is called Java Virtual Machine.
This JVM exist only inside the computer memory. This Bytecode is interpreted by the java interpreter and produce
the machine code.
JVM - interpreter for Bytecode
The details of JVM will differ from platform to platform, but all understand the same java Bytecode.
Makes a java program secure and no side effects.
7
Module1 java programming BCA
I.javacis java compiler.this compiles the java source code ,convert source code to byte code that
interpreter can understand.if we write java program called sample.java and compile it we get the
class file sample.class
II.java is the interpreter that executes the class file.
III.Jdb is thejava debugger ,enables us to debug our java programs.debugger is a commandline
debugger.
IV.javapis the java disassembler can be used to convert compiled source code to source code
V.javahis theHeaderfile generator-this enables the user to use native c or c++ code with in the java
class
VI.Javadoc enables us to generate easily documentation in the form of html files
VII.Applet viewer-whenever we write an applet we need to test it.applet viewer program is available in
jdk to help testing an applet.
First create the source code using any text editor.source code compiled using java compiler javac and
executed using java interpreter java.to find any errors java debugger jdb .compiled source code can
converted to source code using java disassemble javap.if we want to extract html documentation from
source codemjavadoc is used.if we want to use any header files for use with native methods then javah is
used.
Simple program
Class example
{
/* this is a multi
Line comment*/
Public static void main(String args[])
{system.out.println(This is a simple java program);
8
Module1 java programming BCA
}
}
Class declaration
By convention, class names begin with a capital letter and capitalize the first letter of each word they include
(e.g., SampleClassName).
In Java, all code must reside inside a class.
the name of that class should match the name of the file that holds the program.
Comments
Java has 3 types of comment statements
Single line comments
Multiline comments
Documentation comments
/* this is a multi
Line comment*/
//single line comments
Java provides comments of a third type, Javadoc comments. These are delimited by /** and */
The contents of a comment are ignored by the compiler.
A comment describes or explains the operation of the program to anyone who is reading its
source code
Main line
Public static void main(String args[])
All Java applications begin execution by calling main( ).
The public keyword is an access specifier, which allows the programmer to control the
visibility of class members.
When a class member is preceded by public, then that member may be accessed by code outside the class in
which it is declared.
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 method is special,it allows main( ) to be called without first creating an object of the
class in which the method is declared
This is necessary since main( ) is called by the Java Virtual Machine before any objects are made.
The keyword void simply tells the compiler that main( ) does not return a value.
String args[] - declares a parameter named args which is an array of instances of class string.
Objects of type string store character strings.
arg receives any command line arguments present when the program is executed
Output line
system.out.println(This is a simple java program);
This line outputs the string This is a simple Java program. followed by a new line on the
9
Module1 java programming BCA
screen.
This issimilartoprintfincandcoutincandc++
Output is actually accomplished by the built-in println( ) method.
Println method is a member of the out object,which is static member of system class
The System.out object is known as the standard output object. It allows a Java applications to display
information in the command window from which it executes
System is a predefined class that provides access to thesystem, and out is the output stream that is
connected to the console.
Compiling
The Java compiler requires that a source file. use the .java filenameextension.
-c:\>javac example.java
Creates example.class- bytecode
To run c:>java example
Documentation section
This section contains set of comment lines
Package statement
This statement declares package name and informs the compiler that classes defined here belongs to this
package.
Import statement
Similar to #include
Example
Import student.test
10
Module1 java programming BCA
Instruct interpreter to load test class contained in package student
Interface statement
It is like a class but includes a group of method declarations.
If we want to implement multiple inheritance, interface is used
Class definitions
Classes are essential element of a java pgm.
No. of classes depends on complexity of a program
Main method class
Every standalone programs requires main method as its starting point
Simple java pgm contain only this part
Main method creates objects and establish communication between them
Keywords
There are 49 reserved keywords currently defined in the Java language .
These keywords cannot be used as names for a variable, class, or method.
11
Module1 java programming BCA
Data types
Floating-point types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision .
For example, calculations such as square root.
There are two kinds of floating-point types, float and double, which represents single and double-precision
numbers, respectively.
Float-single- when need a fractional component
12
Module1 java programming BCA
Double- double precision-math functions, iterative calculations.
characters
This data type is used for storing characters
char in java is not the same as char in c or c++. In c/c++ char is 8 bits wide.This is not in the case of java.
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.
java char is a 16-bit type.The range of a character is 0 to 65,536
Booleans
Java has a primitive type , called Boolean, for logical values.It can have only one of two possible values, true
or false
Type returned by relational operators
Used in conditional expressions in control structures
The declaration is below:
boolean b;
B=true;
If(b) or if(b==true)
Reference Data Types:
Reference variables are created using defined constructors of the classes. They are used to access objects.
These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc.
Class objects and various types of array variables come under reference data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");
13
Module1 java programming BCA
variables
The variables is the basic unit of storage in a java pgm.
A variable is defined by the combination of an identifier, a type, and an optional initializer.
In addition, all variables have a scope, which defines their visibility, and a lifetime.
Declaring a variable
The basic form of a variable declaration is below:
type identifier [ = value][,identifier[ = value].];
The identifier is the name of the variable;
You can initialize the variable by specifying an equal sign and a value
Int a, b,c;
Int d=3;.
Identifiers
Identifiers are used for class names, method names, and variable names.
14
Module1 java programming BCA
An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers or the
underscore and dollar sign characters.
They must not begin with a number
java is case-sensitive, so VALUE is a different identifier the Value
valid identifiers are
AvgTemp ,count,a5
Invalid identifiers include: 2count ,high temp.
Rules for identifiers
Refer notebook
Literals
A constant value in Java is created by using a literal representation of it.
For example, here are some literals:
100 98.6 X This is a test
the first literal specifies an integer, the next is a floating-point value, the third is a character
constant, and the last is a string.
A literal can be used anywhere a value of its type is allowed.
Integer Literals
.Any whole number value is an integer literal.
eg:1,4,43.
These all are decimal values, that means they are describing base 10 number.
There are other two bases which can be used in integer literals.
They are hexadecimal and octal.
An octal digit ranges from 0-7, while a hexadecimal digit ranges from 0-15A through F are
substituted for 10 through 15.
An octal value is represented with a leading 0.
Hexadecimal digit is represented by leading 0x.
Floating Point Literals
Floating point numbers represent a decimal value with a fractional component.
They can be expressed in either scientific or standard notation .
15
Module1 java programming BCA
Standard notation has a whole number component followed by a decimal point followed by a fractional
component
eg:3.5788S
scientific notation uses a standard floating point number plus a suffix that specifies a power of 10 by which
the number is to be multiplied.
The exponent is indicated by an E or e followed by a decimal number which can be positive or negative.
Eg:65760.23E-2.
Floating Point Literals in java default to double precision. To specify a float literal F or f should be
appended to the constant.
Toexplicitly specify a double literal append D or d.
Boolean Literals
The values true and false are also treated as literals in Java programming.
When we assign a value to a boolean variable, we can only use these two values.
Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in
Java. We have to use the values true and false to represent a Boolean value.
Eg:boolean chosen = true;
Character Literals
Characters in Java corresponds to Unicode character set.
They are 16-bit values that can be converted into integers and manipulated with the integer
operators such as addition and subtraction.
We can specify a character literal as a single character in a pair of single quote characters such as
'a', '#', and '3'.
For characters that are impossible to enter directly there are several escape sequence ,which allows
you to enter the character you need.
Escape sequence (seperators)
Certain nonprinting characters as well as the backslash(\) and apostrophe(),can be expressed in
terms of escape sequences.
An escape sequence always begins with a backward slash and is followed by one or more special
characters.
Escape Meaning
\n New line
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\\ Backslash
16
Module1 java programming BCA
17
Module1 java programming BCA
% Modulus Divides left hand B % A will give 0
operand by right hand operand
and returns remainder
Increment & Decrement Operator
The ++ and _ _ operators are increment and decrement operators.
The increment operator increases its operand by one, The decrement operator decrement its operand by
one,
a = a + 1; a++; or ++a;
a = a - 1; a--; or --a;
In prefix operator precede the operand or post fix operator follow the operand.
In prefix operand incremented or decremented before the value is obtained for the use in expression
In postfix operand the previous value is obtained for the use in expression and then the operand is modified.
Bitwise Operator
Assume integer variable A holds 60 and variable B holds 13, then:
Truth table
A B A|B A&B A^B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
The Left Shift
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times. It has this
general form:
value << num
18
Module1 java programming BCA
Here, num specifies the number of positions to left-shift the value in value. That is, the << moves all of the bits in the
specified value to the left by the number of bit positions specified by num
The Right Shift (arithmetic shift)
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.
Eg: 00100011 35
>> 2
00001000 8
When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with 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
Eg: 11111000 8
>>1
11111100 4
Relational Operators
Let a=10 and b=20
19
Module1 java programming BCA
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is true
right operand, if yes then condition becomes true.
Output
.a == b =false
a != b =true
a >b =false
a <b =true
b >= a =true
b <= a =false
Logical Operators
binary logical operators combine two boolean values to form a resultant boolean value.
Operator Result
|| OR
&& AND
! Logical unary NOT
The following table shows the effect of each logical operation:
A B A | |B A && BA ^ B !A
False False False False False True
True False True False True False
False True True False True True
20
Module1 java programming BCA
True True True True False False
Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator works in Java much as
it does in any other computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression it allows you to create a chain of assignments.
Eg: int x, y, z;
x = y = z = 100;
This fragment sets the variables x, y, and z to 100 using a single statement. This works because the =
is an operator that yields the value of the right-hand expression. Thus, the value of z = 100 is 100, which is then
assigned to y, which in turn is assigned to x.
Shorthand assignment operators
21
Module1 java programming BCA
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements. This
operator is the ?, and it works in Java much like it does in C, C++. The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true,
then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the
expression evaluated. Both expression2 and expression3 are required to return the same type, which cant be void.
Eg: ratio = denom == 0 ? 0 : num / denom;
22
Module1 java programming BCA
Separators
In Java, there are a few characters that are used as separators. The most commonly used separator in Java is
the semicolon. As you have seen, it is used to terminate statements. The separators are shown in the following
table:
23
Module1 java programming BCA
Scanner class
Scanner is a popular class used to get input from keyboard. This class has different methods to read
different types of data. Below are the frequently used methods of the Scanner class.
-next() reads a string value. If the string value value contains white spaces, only the first part of the string is
read.
-nextLine() reads a string value.
-nextInt() reads an integer number.
-nextFloat() reads a float number.
-nextDouble() reads a double number.
-nextBool() reads a boolean value.
-nextByte() reads a byte number.
Example:
import java.util.Scanner;
public class ScannerInput {
public static void main(String[] args) {
int qty;
float price;
float amount;
Scanner sc=new Scanner(System.in);
System.out.println("Enter quantity:");
qty=sc.nextInt();
System.out.println("Enter unit price:");
price=sc.nextFloat();
amount=qty*price;
System.out.println("The total sale is "+amount);
sc.close();
}
}
Reading using data input stream class
readLine() is a method which is invoked by using object of the input stream class which read input as a string which is
then converted to corresponding data type by using data type wrapper classes
24
Module1 java programming BCA
Read an integer
Import java.io.DataInputStream;
Class Reading
25
Module1 java programming BCA
CONTROL STATEMENTS
Control statements cause the flow of execution to advance and branch based on changes to the state of a
program. Javas program 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.
Selection Statements
Java supports two selection statements: if and switch. These statements allow you to
control the flow of your programs execution based upon conditions known only during run time.
if statement
The if statement is Javas conditional branch statement. It can be used to route program execution through
two different paths. Here is the general form of the if statement:
if (condition) statement1
[Elsestatement2;]
Here, each statement may be a single statement or a compound statement enclosed incurly braces (that is, a
block). The condition is any expression that returns a boolean value. The else clause is optional. Here 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:
eg: if(a >b)
system.out.println(a is grater) ;
else
system.out.println(b is grater) ;
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.
Nested ifs
A nested 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.
eg: if(a>b) {
if(a>c) system.out.println(a is grater) ;
}
Else if(b>c) system.out.println(b is grater) ;
Else
system.out.println(c is grater) ;
The if-else-if Ladder
26
Module1 java programming BCA
A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
General Format is:
if(condition1)
statementblock1;
else if(condition2)
statementblock2;
else if(condition3)
statementblock3;
...
else
statementn;
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. If none of the
conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if
all other conditional tests fail, then the last else statement is performed. If there is no final else and all other
conditions are false, then no action will take place.
if (avg>90)
System.out.println("a+");
else
if ((avg>80)&&(avg<=90))
System.out.println("a");
elseif((avg>70)&&(avg<=80))
System.out.println("b");
elseif((avg>60)&&(avg<=70))
System.out.println("c");
elseif((avg>50)&&(avg<=60))
System.out.println("d");
else
System.out.println("failed");
}
switch statement
The switch statement in Java provides a convenient method for branching a program based on a
number of conditions. As such, it often provides a better alternative than a large series of if-else-if statements. Here
is the general form of a switch statement:
switch (expression) {
case value1:
statement sequence1
break;
27
Module1 java programming BCA
case value2:
statement sequence2
break;
...
case valueN:
statement sequenceN
break;
default:
default 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. In switch the value of the expression is
compared with each of the literal values in the case statements. If a match is found, the code sequence following
that case statement is executed. If none of the constants matches the value of the expression, then the default
statement is executed. However, the default statement is optional. If no case matches and no default is present,
then no further action is taken. 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.
Eg: switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
There are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of
28
Module1 java programming BCA
Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its
case constants.
No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an
outer switch can have case constants in common.
A switch statement is usually more efficient than a set of nested ifs.
Iteration Statements
Javas iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of instructions until a
termination condition is met. Java has a loop to fit any programming need.
elements required to perform iteration loops, which requires
1. a control variable (or loop counter)
2. the initial value of the control variable
3. the increment (or decrement) by which the control variable is modified each time through the loop (also known
as each iteration of the loop)
4. the loop-continuation condition that determines if looping should continue.
while statement
The while loop is Javas most fundamental looping 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.
eg :
import java.util.Scanner;
class digit
{
public static void main(String args[ ])
{
Scanner input = new Scanner( System.in );
int r=0,num=0,s=0;
try
{
System.out.println("enter an integer");
num= input.nextInt();
}catch(Exception e){ }
29
Module1 java programming BCA
while(num>0)
{
r=num%10;
s=s+r;
num=num/10;
}
System.out.println("s="+s);
}
}
do-while statement
If the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed
at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional
expression is false to begin with. 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. Fortunately, Java supplies a loop that does just that:
the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the
bottom of the loop. Its general form is:
do
{
// body of loop
}
while (condition);
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. As with all of
Javas loops, condition must be a Boolean expression.
Example
public class DoWhileTest {
public static void main( String[] args )
{
int i = 1;
do {
System.out.printf( "%d ", i);
++i;
} while ( i <= 10 );
}
}
output:
1 2 3 4 5 6 7 8 9 10
30
Module1 java programming BCA
forstatement
The general form of the for statement is:
for(initialization; condition; iteration)
{
// body
}
If only one statement is being repeated, there is no need for the curly braces. In for loop, 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. The initialization expression is executed
only 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.
public class Forex {
public static void main( String[] args )
{
for ( int i = 1; i <= 10; i++ )
System.out.println( i );
}
}
o/p
1 2 3 4 5 6 7 8 9 10
Declaring Loop Control Variables Inside the for Loop
Often the variable that controls a for loop is only needed for the purposes of the loop
and is not used elsewhere. In that case, it is possible to declare the variable inside the
initialization portion of the for statement.
When you declare a variable inside a for loop the scope of that variable is limited to the for loop
Outside the for loop, the variable will cease to exist. If you need to use the loop control variable elsewhere in your
program, you need to declare it outside the for loop.
Some for Loop Variations
There will be times when you will want to include more than one statement in the initialization and iteration
portions of the for loop
Eg: for(a=1, b=4; a<b; a++, b--)
In this example, the initialization portion sets the values of both a and b. The two comma- separated
statements in the iteration portion are executed each time the loop repeats.
31
Module1 java programming BCA
The condition controlling the for can be any Boolean expression. For example, consider the
following fragment:
Eg: boolean done = false;
for(int i=1; !done; i++)
In this example, the for loop continues to run until the boolean variable done is set to true. It does not
test the value of i.
Either the initialization or the iteration expression or both may be absent.
Eg: for( ; !done; )
In the above example the initialization and iteration expressions have been moved out of the for.
You can intentionally create an infinite loop(a loop that never terminates) if you leave all three parts
of the for empty.
Eg: for( ; ; )
{
// ...
}
This loop will run forever, because there is no condition under which it will terminate.
Nested Loops
Like all other programming languages, Java allows loops to be nested. The placing of one loop inside the body of
another loop is called nesting. When you "nest" twoloops, the outer loop takes control of the number of complete
repetitions of the inner loop.
Eg: for (int i=1; i<=9; i++)
{
System.out.println();
for (int j=1; j<=i; j++)
{
System.out.print(j);
}
}
For each
A second form of for that implements a for-each style loop.
Aforeachstyleloopisdesignedtocyclethroughacollectionofobjects,suchasanarray,instrictly sequential fashion,
from start to finish.
General form
For(type itr-var : collection)statement block
Type specifies the type and
itr-var specifies name of an iteration variable that will receive the elements from a collection one at a time
beginning to end.
With each iteration, the next element in the collection is retrieved and stored in itr-var
32
Module1 java programming BCA
Repeats for all elements in the collection
Type must be same.
Class ForEach {
public static void main(String args[]) {
int nums[]={1,2,3,4,5,6,7.8.9.10};
int sum=0;
//use of for each style for to display & sum of values
for(int x:nums) {
System.out,println(value is+x);
sum+=x;}
system.out.prinln(summation:+sum);} }
With each pass through the loop.x is automatically given a value equal to the next element in nums
Jump Statements
Java supports three jump statements: break, continue, and return. These statements transfer control to
another part of your program.
break statement
In Java, the break statement has three uses. First, it terminates a statement sequence in a switch statement.
Second, it can be used to exit a loop.
Using break to Exit a Loop
By using break, you can force immediate termination of a loop, bypassing the conditional expression and
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.
Eg: for(int i=0; i<100; i++)
{
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
Here although the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when
i equals 10.When used inside a set of nested loops, the break statement will only break out of their
innermost loop.
continue statement
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. This is, in effect, a goto
just past the body of the loop, to the loops end. 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.
33
Module1 java programming BCA
Eg:
public class ContinueTest
{ public static void main( String[] args )
{
for ( int count = 1; count <= 10; count++ )
{ if ( count == 5 ) continue;
System.out.println(count );
}
System.out.println( "\nUsed continue to skip printing 5" );
}
}
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
return statement
The last control statement is 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.
Arrays
An array is group of like typed variable that are referred to by common name.
Arrays offer a convenient means of grouping related information.
Arrays of any type can be created and may have oneormoredimensions.
Aspecificelementinanarray is accessed by its index.
The first element in every array has index zero and is sometimes called the zeroth element. Thus, the
elements of array c are c[0], c[1], c[2] and so on.
An index must be a nonnegative integer. A program can use an expression as an index.
Creating arrays
There are different ways to create a single dimensional array.
We can declare one-dimensional array and directly store elements at the time of declaration by enclose
the elements of the array inside braces, separated by commas.
eg: int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
Here each of the elements inside the braces must be of the same type as the variable that holds that array. An array
whose size is equal to the number of elements you've included will be automatically created for you.
Another way of creating one-dimensional array is by declaring the array first and then allocating memory
by using new operator.
General form:
type var-name[ ] ;
34
Module1 java programming BCA
false for boolean, '\0' for character arrays, and null for objects). You can then assign actual values or
objects to the slots in that array.
To store elements in array we can use statements like these in program.
marks[0]=50;
marks[1]=60;
marks[2]=50;
marks[3]=60;
Or, we can pass values from keyboard to the array by using a loop
for(int i=0;i<5;i++)
marks[i]=Integer.parseInt(br.readLine());
Java strictly checks to make sure you do not accidentally try to store or reference values outside of the
range of the array. The Java run-time system will check to be sure that all array indexes are in the correct
range.
Accessing Array Elements
Once you have allocated an array, you can access a specific element in the array by specifying its index within
square brackets. All array indexes start at zero.
Processing an arry
Processing an entire array in single operation is not possible .each elements in an array must accessed separately.for
this we are using loops.
class lararray
{
public static void main(String args[ ])
{
int a[ ]={1,2,3,4,5};
int big,i;
big=a[0];
35
Module1 java programming BCA
for(i=1;i<a.length;i++)
{
if(big<a[i])
big=a[i];
}
System.out.println("big="+big);
}
}
Multidimensional Arrays
Multidimensional arrays with two dimensions are often used to represent tables of values consisting of information
arranged in rows and columns. To identify a particular table element, we must specify two indices. By convention,
the first identifies the elements row and the second its column. Arrays that require two indices to identify a
particular element are called two-dimensional arrays. (Multidimensional arrays can have more than two
dimensions.)
To declare a multidimensional array variable, specify each additional index using another set of square brackets
int twoDarr[][] = new int[4][5];will allocate a 4 by 5 array and assigns it to twoDarr
Every element in 2d array a is identified by an array-access expression of the form a[row][column]; a is the name of
the array, and row and column are the indices that uniquely identify each element in array a by row and column
number. The names of the elements in row 0 all have a first index of 0, and the names of the elements in column 3
all have a second index of 3.
Column 0 Column 1 Column 2 Column 3
A[0][0] A[0][1] A[0][2] A[0][3]
Column index
A[1][0] A[1][1] A[1][2] A[1][3]
Row index
A[2][0] A[2][1] A[2][2] A[2][3]
Example program
import java.io.*;
class matrix
{
public static void main(String args[ ])throws IOException
{
int m,n;
int a[ ][ ]=new int[5][5];
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter the size of matrix");
m=Integer .parseInt(in.readLine());
n=Integer .parseInt(in.readLine());
System.out.println("enter elmnts");
36
Module1 java programming BCA
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(in.readLine());
}
}
for(int i=0;i<m;i++)
{
System.out.print("\n");
for(int j=0;j<n;j++)
{
System.out.print(" "+a[i][j]);
}
}
}}
When you allocate dimensions manually, you do not need to allocate the same number of
elements for each dimension. As stated earlier, since multidimensional arrays are actually arrays of arrays, the
length of each array is under your control.
Eg: int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
It is possible to initialize multidimensional arrays. To do so, simply enclose each dimensions
initializer within its own set of curly braces.
Eg:double m[]4[] = {
{ 0,1, 2, 3 },
{ 4, 5, 6, 7 },
37