You are on page 1of 42

Module1

java programming

bsc cs

INTRODUCTION TO JAVA
1.1 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 crossplatform programs by compiling into an intermediate representation called Java bytecode.
This code can be interpreted on any system that provides a Jav a Virtual Machine.

1.2 Brief history of Java


Java was developed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike
Sheridant Sun Microsystems in 1991.It took 18 months to develop first working version.
This language was initially called Oak but was renamed as Java in 1995.The primary
motivation for the development of Java was the need for a platform independent
language that can be used to create software to be embedded in various electronic
devices (eg: remote controllers).Many different types of CPUs are used as controllers. The
trouble with C and C++ is that they are System dependent. An executable file created
in C and C++ on a particular processor and operating system can be executed only on that
processor and OS. If either the processor or OS is changed it is not possible to execute code.
So efforts were started to create a platform independent, portable language that could be
used to produce programs that would run on a variety of CPUs under different environments.
This effort ultimately led to the creation of Java. Another factor that made java inevitable
was the emergence of World Wide Web. Internet is a global network of computers. So there
will be different types of computers with different processors and different operating systems
existing on internet. Even though many platforms are attached to internet, user should be
able to run a program on all of them. So if software is developed using C/C++ languages, that
software can be distributed on internet and people can download the .exe files. But they
cannot run those files because of system dependency. Again the need for a platform
independent language was necessary which will allow to run a program on any system was
needed .Java enhances and refines the object oriented paradigm used by C++.Many of the
features of java are inherited from its predecessors like C and C++. From C java
derives its syntax. Many of javas object oriented features were influenced by 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.

1.3 Features of java(characteristics of java)


1

Module1
I.
II.
III.
IV.
V.
VI.
VII.
VIII.
IX.
X.
XI.

java programming

bsc cs

Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic

Simple
Java is a simple programming Language .Java was designed to be easy for the professional
programmer to learn and use effectively. Java inherits the C/C++ syntax and many of the
object-oriented features of C++.So most programmers have little trouble learning java. Also,
some of the more confusing concepts from C++ (like pointers, multiple inheritance) are either
left out of java or implemented in a cleaner, more approachable manner. Automatic garbage
collection has been added.
Object-Oriented
Java is a true object oriented language. The object-oriented facilities of Java are essentially
those of C++.Almost everything in java is an object. All program code and data reside within
objects and classes. Java comes with an extensive set of classes, arranged in packages that
we can use in our program by inheritance. The object model in java is simple and easy to
extend. The object model in Java is simple and easy to extend.
Robust
Java is a robust anguage.it provides many safeguards to ensure reliable code. java is a strictly
typed language, it checks your code at compile time. However, it also checks your code at run
time. It also incorporates the concepts of exception handling which captures runtime errors
and eliminates any risk of crashing system
Architecture Neutral
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 byte code 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-

Module1

java programming

bsc cs

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.

Interpreted and High Performance


Usually computer languages are either compiled or interpreted .Java enables the
creation of cross-platform programs by compiling into an intermediate representation
called Java byte code. This code can be interpreted on any system that provides a
Java Virtual Machine. the Java byte code 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 addressspace 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.

Types of java programs


3

Module1

java programming

bsc cs

Java can be used to create two types of programs: applications and applets. An
application is a program that runs on your computer, under the operating system of
that computer. Applets are small programs developed for internet applications. An
applet located on a distance computer(server) can be downloaded via internet and executed
on a local computer(client) using java compatible web browser. We can develop applets for
doing 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.

Module1

java programming

Source Code: .java file

Byte Code: Intermediate code generated after compilation ( .class file )

Object Code: Ready to execute program

bsc cs

Java Development Kit


Software component needed for developi g and executing jva programs is called java
developers kit(JDK).there are eight components of JDK.they are
I.

Compiler-javac.exe is java compiler.this compiles the java sourse code


and creates the class file.if we write java program called sample.java and

II.
III.

compile it we get the class file sample.class


Interpreter-java interpreter java.exe executes the class file.
Debugger-java debugger jdb.exe enables us to debug our java

IV.

programs.debugger is a commandline debugger.


Disassemble-java disassemble javap.exe can be used to convert

V.

compiled sourse code to sourse code


Headerfile generator-this enables the user to use native c or c++ code

with in the java class


VI.
Documentation-this 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
VIII.

viewer program is available in jdk to help testing an applet.


Class libraries-jdk has a sub directory c:\java\lib.this has a primary file
called classes.zip.this file contains all the classes of java library.important

packages of java are


Java.lang java language functionality classes
Java.applet base classes for applets
Java.awt abstract window toolkit
Java.io input output
Java.net network operations
Java.util utility classes
Important executable files of the directory
C:\java\bin
Javac.exe
Java.exe
Javadoc.exe
Jdb.exe
Appletviewer.exe
Jdk has another directory c:\java\demo that contains group of demo applets.the
directory c:\java\include contains set of c and interface java classes to the c and c+
+ languages.

Simple program
Class example
5

Module1

java programming

bsc cs

{
/* this is a multi
Line comment*/
Public static void main(String args[])
{system.out.println(This is a simple java program);
}
}
Class declaration

By convention, class names begin with a capital letter and capitalize the first letter of each

word they include (e.g., SampleClassName).


source file name must be example.java
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

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.

method is special,it allows main( ) to be called without first creating an

Module1

java programming

bsc cs

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
screen.

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 the system, and out is the output stream
that is connected to the console.

Compiling
The Java compiler requires that a source file. use the .java filename extension.
-c:\>javac example.java
Creates example.class- bytecode
To run c:>java example

Java Program structure

Java program contains many classes of which only one class defines main

method

Classes contain data members and methods.

Methods contain datatype declarations and executable statements

Java program may contain one or more sections

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

Module1

java programming

bsc cs

Import statement
Similar to #include
Example
Import student.test
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

Elements of java language


Java tokens

Java program is a collection of classes


Smallest individual units in a program is known as tokens
Five types of tokens are
Keywords
Identifiers
Literals
Operators
seperators

java character set

smallest units of java language are the characters


characters are defined by Unicode character set
Unicode is a 16 bit character coding system

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.
abstrat

continue

if

private

throw

goto

Package

Synchronized

assert

default

this

Boolean

Implements

do

protected

break

Double

Import

Instanceof

return

byte

public

throws

else

Case

Transient

try

extends

switch

int

short

Finally

Strictfp

catch

volatile

final

static

void

Char

Interface

long

native

class

float

super

While

Const

for

new

Module1

java programming

bsc cs

Data types

Java defines eight primitive types of data:


byte, short, int, long , char, float, double, and Boolean.
The primitive types are also commonly referred to as simple types. They are

Integers : This group includes byte, short, int, and long , which are for whole-valued signed
numbers.

Floating-point numbers : this group includes float and double, which represent numbers with
fractional precision.

characters : This group includes char, which represents symbols in a character set, like
letters and numbers.

Boolean : This group includes Boolean, which is a special type for representing true / false
values.
integers

Java defines 4 integer types: byte, short, int, and long. All of these are signed, positive
and negative values.

The width and ranges of these integer types vary widely, as shown in this table:

The smallest integer type is byte.


Short is signed 16 bit.it is leastly used
Int is most commonly used

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.


9

Module1

java programming

bsc cs

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


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");

Type conversion and casting

If the two types are compatible, then java will perform the conversion

automatically.

For eg, it is always possible to assign an int value to a long variable.

10

Module1

java programming

bsc cs

However, not all types are compatible, and thus, not all type conversions are

implicitly allowed. for instance, there is no automatic conversion defined from double to
byte.

To do so, you must use a cast, which performs an explicit conversion between
incompatible types.

Javas automatic conversions

When one type data is assigned to another type of variable, an automatic type

conversion will take place if the following two conditions are met:
The two types are compatible
The destination type is larger than the source type

Casting incompatible types

If you want to assign an int value to a byte variable then this conversion will not be

performed automatically, because a byte is smaller than an int.

This type of conversion is sometimes called a narrowing conversion.

To create a conversion between two incompatible types, you must use a cast.

A cast is simply an explicit type conversion.


conversion

it has this general form:


(target-type) value
Here, target-type specifies the desired type to convert the specified value to.

For example, the following fragment casts an int to a byte.

If the integer's value is larger than the range of a byte, it will be reduced modulo bytes

range.
int a;
byte b;
//
b=( byte) a;

Truncation-when a floating point value is assigned to an integer type, The

fractional component is lost.


Type promotion rules

Automatically promotes each byte, short, or char to int.

Byte, short, char promote to int.

If one operand is long-whole expression promoted to long

If one operand is double- result is double

variables

The variables is the basic unit of storage in a java pgm.


11

Module1

java programming

bsc cs

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.
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.
Identifiers or variable names in java can be any of the following types
Class names(class identifiers)-name given to a class is called a class name or class

identifier.
Instance names(object identifier)-names given to the objects are called object identifiers
Data identifiers and method identifiers-any local or global variable names that is given
for a method of a class is called method names or method identifier .names for a attribute are

called attribute identifiers


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 .
12

Module1

java programming

bsc cs

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
\n
\t
\b
\r
\f
\\

Meaning
New line
Tab
Backspace
Carriage return
Form feed
Backslash

\'

Single quotation mark

\"

Double quotation mark

\ddd

Octal(d is octal constant)


Hexadecimal(xxxx is a hexadecimal

\uxxxx

constant)

String Literals
13

Module1

java programming

bsc cs

String literals are specified by enclosing a sequence of characters between a pair of double

quotes.
Examples are HelloWorld, two\nlines.
The escape sequence and octal/hexadecimal notations that were defined for character literals

work the same way inside of string literals.


One point to remember is that java strings must begin and end on same line.

Expressions and Operators


Expressions are the simplest form of statement in Java that actually accomplishes something.
Expressions are statements that return a value.
Operators are special symbols that are commonly used in expressions.
Arithmetic and tests for equality and magnitude are common examples of expressions.
Because they return a value, you can assign that result to a variable or test that value in other
Java statements.
OPERATORS

Operators can be divided into the following groups:

Arithmetic Operators
Increment & Decrement Operators
Assignment operators
Bitwise Operators
Relational Operators
Logical Operators
Arithmetic Operators
Java has five operators for basic arithmetic
Assume integer variable A holds 10 and variable B holds 20, then:
Operator
+

description
Addition - Adds values on

example
A + B will give 30

either side of the operator


Subtraction - Subtracts right

A - B will give -10

hand operand from left


*

hand operand
Multiplication - Multiplies

A * B will give 200

values 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
14

Module1

java programming

bsc cs

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
1

0
1
1

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

Module1

java programming

bsc cs

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

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

>>1
11111100

16

Module1

java programming

bsc cs

Relational Operators
Let a=10 and b=20

<=

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^B

!A
17

Module1

java programming

False

False

False

True

False

False

True

True

True

True

True

True

False

False

False

True

True

False

False
True

bsc cs

True
False

True
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

18

Module1

java programming

bsc cs

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-thenelse 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;

precedence and associativity of operators

Precedence is used to determine the order in which different operators in a

complex expression are evaluated.

19

Module1

java programming

bsc cs

Associativity is used to determine the order in which operators with the

same precedence are evaluated in a complex expression.

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
[Else statement2;]
Here, each statement may be a single statement or a compound statement enclosed
20

Module1

java programming

bsc cs

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

21

Module1

java programming

bsc cs

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;
case value2:
statement sequence2
break;
...
case valueN:
statement sequenceN
break;
default:
default statement sequence
}

22

Module1

java programming

bsc cs

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

Module1

java programming

bsc cs

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){ }
while(num>0)
{
r=num%10;
s=s+r;
num=num/10;

24

Module1

java programming

bsc cs

}
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 dowhile. 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
for statement
The general form of the for statement is:
for(initialization; condition; iteration)
{

25

Module1

java programming

bsc cs

// 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.printf( "%d ", 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 commaseparated statements in the iteration portion are executed each time the loop repeats.

The condition controlling the for can be any Boolean expression. For example, consider
the following fragment:
26

Module1

java programming

bsc cs

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" two loops, 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
27

Module1

java programming

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

bsc cs

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.
28

Module1

java programming

bsc cs

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.
Eg:
public class ContinueTest
{ public static void main( String[] args )
{
for ( int count = 1; count <= 10; count++ )
{ if ( count == 5 ) continue;
System.out.printf( "%d ", 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 one or more dimensions .
A specific element in an array 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

29

Module1

java programming

bsc cs

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[ ] ;
var-name = new type[size];
here Type can be any base typei.e data type of each element. Size specifies number of
elements in the array.

Eg: int marks[];


marks=new int marks[5];
These two statements can also be written by combining them into a single statement
as
type var-name[] = new type[size];
Eg: int marks[]=new int[5];
This line creates a new array of integer with 5 elements and allocates memory for
storing 5 integer elements into the array. .
When you create an array object using new, all its elements are initialized for you (0
for numeric arrays, 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.

30

Module1

java programming

bsc cs

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];
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

31

Module1

java programming

A[0]

A[0][1]

A[0][2]

A[0][3]

[0]
A[1]

A[1][1]

A[1][2]

A[1][3]

[0]
A[2]

A[2][1]

A[2][2]

A[2][3]

bsc cs

Column
index
Row
index

[0]
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");
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
32

Module1
same

java programming
number

of

elements

for

each

dimension.

bsc cs
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 },

Class Fundamentals
Everything in OOP is considered as Classes and Object and

therefore Any concept

you wish to implement in a Java program must be encapsulated within a class. Classes
provide a convenient way for packing together a group of logically related data items and
functions that work on them
Prime importance is given to Data

Class is a data type

Class contain data and methods to operate data


Object is an instance of Class

Objects are created from Class

The General Form of a Class


When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data. While very simple classes may
contain only code or only data, most real-world classes contain both.

A class is declared

by use of the class keyword. The general form of a class definition is shown:
class classname {
type instance-variable1;
type instance-variable2;
...
type instance-variableN;
}
type methodname1(parameter-list)
{ `

body of method

type methodname2(parameter-list)

{
33

Module1

java programming

bsc cs

body of method
}

type methodnameN(parameter-list)

body of method }

The data, or variables, defined within a class are called instance variables. They are

called instance variables because each instance of the class (that is, each object of the class)
contains its own copy of these variables. Thus, the data for one object is separate and
unique from the data for another. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.. Collectively, the methods and variables
defined within a class are called members of the class. No method definition can put
outside class.

Sample class
class rectangle
{
int length, breadth;
void getData(int x, int y)
{
length = x;
breadth = y;
}
int rectArea()
{
int area = length * breadth;
}
}

Creating Objects

Objects are created in two steps

Declare a class type variable(only creates a template not actual object)

Allocate memory and bind with class variable

Memory is allocated dynamically by using new operator(runtime)

Class_var= new classname();

Class _var is the variable name .classname is the name of class.The followed

parenthesis specifies the constructor.


Eg: rectangle r1;

//declaring class variable

r1 = new rectangle(); //allocating memory and binding


34

Module1

java programming

bsc cs

rectangle r2= new rectangle();


rectangle();call to constructor

r1

Class members are accessed by using dot (.) operator

Eg: r1.getData(10,20);
r1.length=45;

Class is a logical construct

Object is a physical reality


Assigning object reference

Rectangle r1=new Rectangle();

Rectangle r2=r1;

r2

r2 refer to r1.any changes made by r1 also affect r2

Methods in Classes
Classes usually consist of two things: instance variables and methods.
This is the general form of a method:
type name(parameter-list)
{
// body of method
}
Here type specifies the type of data returned by the method. This can be any
valid type, including class types that you create. If the method does not return a value, its
return type must be void. The name of the method is specified by name. This can be any
legal identifier other than those already used by other items within the current scope. The
parameter-list is a sequence of type and identifier pairs separated by commas. Parameters
are essentially variables that receive the value of the arguments passed to the method
when it is called. If the method has no parameters, then the parameter list will be
empty.Methods that have a return type other than void, return a value to the calling
routine using the following form of the return statement:
return

value; where, value is the value returned.

The type of data returned by the method must be compatible with the return
type specified by the method. Also the variable receiving the value returned by a method
35

Module1
must

java programming

also

be

compatible

with

the

return

bsc cs
type

specified

for

the

method

Accessing Class members


Each object created has its own set of variables.Values should be assigned to
these variables to use them in the program. In order to access the instance variables and
methods dot operator(.) is used. The concerned object and dot operator is used as
shown below:
Objectname.variablename=value;
Objectname.methodname(parameter-list);
objectname is the name of the object, whose members we want to access.
variablename is the name of instance variable inside the object we want to access
methodname is the method we wish to call and parameter list is the list of values that
should be passed to the function definition. It should match in type and number with the
parameters in the function definition.
Eg: class Box
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
}
class BoxDemo
{
public static void main(String args[])
{
]

Box mybox1 = new Box();

36

Module1

java programming

bsc cs

Box mybox2 = new Box();


double vol;
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}This program generates the following output
Volume is 3000.0
Volume is 162.0
Here setDim() is a parameterized function used to set the dimensions of each box For
example, when mybox1.setDim(10, 20, 15); is executed, 10 is copied into parameter w, 20
is copied into h, and 15 is copied into d. Inside setDim( ) the values of w, h, and d are
thena ssigned to width, height, and depth, respectively.

constructors

Initializes object immediately upon creation.

Member functions used to initialize class data members

Constructors has the same name of Class

A class can have more than one constructor

once defined, automatically called immediately after the object is created before the

new operator completes

Matching constructor function will invoke each time when an instance is created

Constructors will not have any return value, even void

Type is the class type itself.

if is a constructor not explicitly defines for a class, a default constructor will be created.

It will automatically initializes all instance variable to zero.


Parameter Constructors

Constructors can take parameters

Parameters are passed at the time of object creation

Once parameterized constructors are there, all object creation is required to use proper

number of parameters

Default constructor is required to use, if you want to initialize object without parameter
Class Box
{double width;
double height;
37

Module1

java programming

bsc cs

Double depth;
Box()
{widt h=10;height=10;depth=10;}
Box(double w,double h, double d)
{width=w;
Height=h;
depth=d;
}
double volume()
{return width*height*depth;
}
}
Class BoxDemo
{
public static void main(String args[])
{
double vol1,vol2;
box box1=new Box();
vol1=box1.volume();
Box box2=new Box(10,20,15);
Vol2=box2.volume();
System.out.println("Volume is " + vol1);
System.out.println("Volume is " + vol2);
}
}
this Keyword

Use to refer to the object that invoked the method

Used inside any method to refer to the current object.


Box(double w, double h, double d)
{
this.width=w;
this.heigth=h;
this.depth=d;
}
Hiding instance variable

When we use formal variables or local variables having the same name of instance

variables, the local variable hides the instance variables.


38

Module1

java programming

this keyword can use to override instance variable hiding

this. INSTANCE variable-name refer to INSTANCE variable

bsc cs

Box(double width,double heigth,double depth)


{this.width=width;
this.heigth=heigth;
this.depth=depth;
}
finalize() method

Sometimes an object will need to perform some action when it is destroyed.

for eg. an object is holding some non java resource such as file handle or character

font, then we might want to make sure these resource are freed before an object is destroyed.
to handle such situations, java provides a mechanism called finalization.

To add a finalizer to a class, we need to simply define finalize() method. Inside the

finalize method we can specify those actions that must be performed before an object is
destroyed.

The finalize( ) method has this general form:


protected void finalize( )
{
finalization code here
}

It is declared as protected to prevent access to finalize() by code defined outside the

class

. Inside the finalize( ) method you will specify those actions that must be

performed before an object is destroyed. The garbage collector runs periodically,


checking for objects that are no longer referenced by any running state or indirectly
through other referenced objects. Right before an asset is freed, the Java run time calls
the finalize( ) method

on the object.

Nested and Inner Classes


It is possible to define a class within another class. Such classes are known as
nested classes. The scope of a nested class is bounded by the scope of its enclosing
class. For Example class B is defined within class A, then B is known to A, but not outside
of A. A nested class has access to the members, including private members, of the class
in which it is nested. However, the enclosing class must access the nested class variables
through an object reference..
39

Module1

java programming

bsc cs

There are two types of nested classes: static and non-static. A static nested
class is one which has the static modifier applied. Because it is static, it must access the
members of its enclosing class through an object. That is, it cannot refer to members of
its enclosing class directly.
The most important type of nested class is the inner class. An inner class is a
non-static nested class. It has access to all of the variables and methods of its outer
class and may refer to them directly in the same way that other non-static members of
the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

Why Use Nested Classes?


There are several compelling reasons for using nested classes, among them:

It is a way of logically grouping classes that are only used in one place.

It increases encapsulation.

Nested classes can lead to more readable and maintainable code.

Logical grouping of classesIf a class is useful to only one other class, then it is logical to embed it
in that class and keep the two together. Nesting such "helper classes" makes their package more
streamlined.
Increased encapsulationConsider two top-level classes, A and B, where B needs access to members
of A that would otherwise be declared private. By hiding class B within class A, A's members can be
declared private and B can access them. In addition, B itself can be hidden from the outside world.
More readable, maintainable codeNesting small classes within top-level classes places the code
closer to where it is used.
The following program illustrates a static nested class.
class Outer
{
int outer_v=10;
void test()
{
System.out.println("Outer");
}
static class Inner
{
void display()
{
40

Module1

java programming

bsc cs

Outer ot=new Outer();


ot.test();
System.out.println("v="+ot.outer_v);
}
}
}
class StaticInner
{
public static void main(String args[])
{
Outer.Inner inner=new Outer.Inner();
inner.display();
}
}
The following demonstrates non-static nested class or inner class.
class Outer
{
private int outer_v=10;
void test()
{
System.out.println("Outer");
}
class Inner
{
void display()
{
test();
System.out.println("x="+outer_v);
}
}
}
class Demo
{
public static void main(String args[])
{
Outer outerobj=new Outer();
Outer.Inner inner= outerobj.new Inner();

41

Module1

java programming

bsc cs

inner.display();
}
}
//access protected method from other
//package
System.out.println (Though I abused"+
multiple inheritance, I still use it);
}
}//end of class Inner
void deriv()
{
Inner i = new Inner();
i.showInner();
}

42

You might also like