Professional Documents
Culture Documents
Oop PPT-1-1
Oop PPT-1-1
Using Java
a computer.
I. Structured Programing
3
of code/data Compiled By Sahile.T
A procedural program is divided into functions, and (ideally, at least) each function
has a clearly defined purpose & a clearly defined interface to the other functions in
the program.
2. Real-World Modeling
Unrelated functions and data, the basics of the procedural paradigm, provide a poor
model of the real world.
• Methods that operate on the data of an object are tied together in the data structure
• Data is hidden and can’t be accessed by external functions
• Objects may communicate with each other through methods
• New data and methods can be easily added whenever necessary
• Follows bottom-up approach in program design
• First, the individual base elements of a program are specified (Objects with their data structures and
methods)
• Then they are linked together to form larger subsystems (using algorithm)
• Structured approach is top-down (algorithm comes first, then the data structure)
6 Compiled By Sahile.T
Basic concepts of OOP
Objects and Classes
A. Object: is a software package that has State and Behavior and it occupies
memory
Example: dogs have states (name, color, hungry, breed) and behaviors (bark, fetch,
and wag tail).
• Software Objects are often used to model real-world objects.
B. Class: is the template or blueprint that defines the states and the behaviors
common to all objects of a certain kind.
• It is a collection of objects of similar type.
• Classes are user-defined data types & behave like the built-in types of programming
language.
7 Compiled By Sahile.T
Message
Software objects interact and communicate with each other by
sending messages to each other.
The process of programming in object-oriented language, therefore,
involves the following three basic steps:
i. Creating classes that define objects and their behavior.
9
I. Data Abstraction & Encapsulation
The wrapping up of data and methods into a single unit (called
class) is known as encapsulation.
This insulation of the data from direct access by the program is
called data hiding.
Abstraction refers to the set of representing essential features
without including the background details or explanations
Classes use the concept of data abstraction, and they are known as
Abstract Data Types (ADT)
They hide the private data structure details and communicate with the
10 outside using public methods which act as interfaces
II. Inheritance
• Is the process by which objects of one class acquire the properties of objects of
another class.
• It provides the idea of reusability
III. Polymorphism
• Is the ability to take more than one form.
• Plays an important role in allowing objects having different internal structures
to share the same external interface.
Three types of polymorphism:
1. Overloading methods
13 Compiled By Sahile.T
Java Overview
Java is a general purpose, object-oriented programming language
developed by Sun Microsystems of USA in 1991.
The Java foundation class libraries provide for windowing and graphical
user interface programming, network communications, and Multimedia
facilities. Together, they demonstrate the practical and productive work
done in Java.
14 Compiled By Sahile.T
Java Editions: SE, EE and ME
Java Editions: SE, EE and ME
The Java Enterprise Edition (Java EE) is geared toward developing large-
scale, distributed networking applications and web-based applications.
Today’s applications can be written with the aim of communicating among the
world’s computers via the Internet and the web.
The Java Micro Edition (Java ME) is geared toward developing applications
for small, memory-constrained devices, such as BlackBerry smart phones.
Google’s Android operating system—used on numerous smartphones,
tablets (small, lightweight mobile computers with touch screens), e-readers and
other devices—uses a customized version of Java not based on Java ME.
15
Java Features
I. Compiled and Interpreted
Java combines both these approaches thus makes it a two-stage
system.
Java compiler translates the source code into bytecode
instructions.
Java interpreter generates the machine code that can be directly
executed by the machine that is running the java program.
16 Compiled By Sahile.T
How it Works?
Compile-time Environment Run-time Environment
Class
Loader Java
Class
Bytecode Libraries
Java Verifier
Source
(.java)
Just in
Java Java
Time
Bytecodes Interpreter Java
Compiler
move locally Virtual
or through machine
Java network
Compiler
Runtime System
Java
Bytecod Operating System
e
(.class )
Hardware
17
Compiled By Sahile.T
Java Virtual Machine (JVM)
Java compiler produces an intermediate code known as bytecode for
a machine that does not exist. This machine is known as Java
Virtual Machine (JVM) & it exists only inside computer memory.
19
ii. The size of the primitive data types are machine-independent.
Compiled By Sahile.T
III. Object-oriented
23 Compiled By Sahile.T
Differences Between Java and C++
Java does not support operator overloading.
Java does not have template classes as in C++.
Java does not support multiple inheritance.
• This is accomplished using a new feature called “interface”
Java does not support global variables.
• Every variable and method is declared within a class and
forms part of that class.
Java does not use pointers
Java has replaced the destructor function with a finalize()
function
There are not header files in Java.
24 Compiled By Sahile.T
Java Environment
Java environment includes a large number of development tools and
hundreds of classes and Methods.
The development tools are part of the system known as Java
Development Kit (JDK) and the classes and methods are part of the
Java Standard Library (JSL), also known as Application
Programming Interface (API).
JDK comes with a collection of tools that are used for developing and
running java programs:
appleviewer (for viewing java applets )
javac (java compiler)
java (java interpreter)
javap (java disassembler)
javah (for C header files)
javadoc (for creating HTML documents)
25 jdb (Java debugger)
Compiled By Sahile.T
Java API
It includes hundreds of classes and methods grouped into several
functional packages.
Most commonly used packages are:
Language Support Package: a collection of classes and methods required
for implementing basic features of java.
Utilities Package: a collection of classes to provide utility functions such as
date and time functions.
Input/output Package: a collection of classes required for input/output
manipulation.
Networking Package: a collection of classes for communicating with other
computers via Internet.
AWT Package (Abstract Window Tool kit package): contains classes that
implements platform-independent graphical user interface.
Applet Package: includes set of classes that allows us to create java applets.
26
Compiled By Sahile.T
Section III
Overview of Java Programming
Language
27 Compiled By Sahile.T
Introduction
Java is a general-purpose, object-oriented programming
language.
We can develop two types of Java programs namely:
Stand-alone application
Web applets
Executing stand-alone Java program involves two steps:
• Compiling source code into byte code javac compiler.
• Executing the bytecode program using java interpreter.
Applets are small programs developed for Internet applications.
An applet located on a distant computer (server) can be
downloaded via Internet and executed on a local computer
(client) using a Java-capable browser.
28 Compiled By Sahile.T
Compiler
30 Compiled By Sahile.T
Let us discuss the program line by line:
• Class Declaration: the first line class Sample declares a class,
which is an object constructor. Class is keyword and declares a
new class definition and Sample is a java identifier that specifies
the name of the class to be defined.
• Opening Brace “{“: Every class definition in java begins with an
opening brace and ends with a closing brace “}”.
• The main line: the third line public static void main(String
args[]) defines a method named as main.
• Is the starting point for the interpreter to begin the execution
31 of the program.
Note:
A java program can have any number of classes but only one of
them must include the main method to initiate the execution.
Java applets will not use the main method at all.
The third line uses a number of keywords: public, static and
void
public: is an access specifier that declares the main method as
“unprotected” and therefore making it accessible to all other
classes.
static: declares that this method as one that belongs to the entire
class and not a part of any objects of the class.
Main must always be declared as static since the interpreter
uses this method before any objects are created.
void : states that the main method does not return any value (but
33 Compiled By Sahile.T
Java Program Structure
Documentation
Documentation Section
Section Suggested
Suggested
Optional
Optional
Package
Package Statement
Statement
Optional
Optional
Import
Import Statements
Statements
Optional
Optional
Interface
Interface Statements
Statements
Class
Class Definitions
Definitions Optional
Optional
Main
Main Method
Method class
class
{{ Essential
Essential
Main
Main Method
Method Definition
Definition
}}
34 Compiled By Sahile.T
Documentation Section
comprises a set of comment lines giving the name of the
program, the author and other details, which the programmer
would like to refer at a later stage.
Java supports three types of comments:
i. Single line comment //
ii. Multiple line comment /*………………
………………*/
iii. Documentation comment /**….*/
• This form of comment is used for generating
documentation automatically.
35 Compiled By Sahile.T
Package Statements
Is the first statement in Java file and is optional.
It declares a package name and informs the compiler that the
classes defined here belong to this package.
Example: package student;
Import Statements
Next to package statements (but before any class definitions) a
number of import statements may exist. This is similar to #include
statements in C or C++.
Using import statements we can have access to classes that are part
of other named packages.
Example: import java.lang.Math;
36 Compiled By Sahile.T
Interface Statements
An interface is like a class but includes a group of method
declarations.
is also an optional section.
is used only when we wish to implement the multiple inheritance
features in the program
Class Definitions
A Java program may contain multiple class definitions.
Classes are the primary and essential elements of a Java program.
These classes are used to map objects of real-world problems.
The number of classes depends on the complexity of the problem.
37 Compiled By Sahile.T
Main Method Class
Since every Java stand-alone program requires a main method as
its starting point, this class is the essential part of a Java program.
A simple Java program may contain only this part.
The main method creates objects of various classes and establishes
communications between them.
On reaching the end of main, the program terminates and control
passes back to the operating system.
38 Compiled By Sahile.T
Section IV
Java Tokens
39 Compiled By Sahile.T
Introduction
A class in java is defined by a set of declaration statements and
methods containing executable statements.
Most statements contain expressions, which describe the actions
carried out on data.
Smallest individual units in a program are known as tokens.
In simplest terms, a java program is a collection of tokens,
comments, and white spaces.
Java has five types of tokens: Reserved Keywords, Identifiers,
Literals, Separators and Operators .
40 Compiled By Sahile.T
1. Keywords
Are essential part of a language definition and can not be used as
names for variables, classes, methods and so on.
Java language has reserved 60 words as keywords.
41 Compiled By Sahile.T
2. Identifiers
Are programmer-designed tokens.
Are used for naming classes, methods, variables, objects,
labels, packages and interfaces in a program.
Java identifiers follow the following rules:
They can have alphabets, digits, and the underscore and
dollar sign characters.
They must not begin with a digit
Uppercase and lowercase letters are distinct.
They can be of any length.
42 Compiled By Sahile.T
POP QUIZ
1) $amount 5) score
2) 6tally 6) first Name
3) my*Name 7) total#
4) salary 8) cast
43 Compiled By Sahile.T
3. Literals
Literals in Java are a sequence of characters(digits, letters and
other characters) that represent constant values to be stored in
variables.
Five major types of literals in Java:
I. Integer Literals: refers to a sequence of digits (decimal integer, octal
integer and hexadecimal integer)
V. Boolean Literals
44 Compiled By Sahile.T
4. Separators
Are symbols used to indicate where groups of code are divided
and arranged.
They basically define the shape and functions of our code.
Java separators include:
45 Compiled By Sahile.T
Contd.
III. Brackets [ ] :- are used to declare array types and for
dereferencing array values.
47 Compiled By Sahile.T
Java Operators
There are 8 different groups of operators in Java:
Arithmetic operators
Relational operators
Logical operators
Assignment operator
Increment/Decrement operators
Conditional operators
Bitwise operators
Special operators
48 Compiled By Sahile.T
A. Arithmetic Operators
Java has five basic arithmetic operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
int x = 3;
int y = 5;
boolean result;
3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
51 Compiled By Sahile.T
C. Logical Operators
Symbol Name
&& Logical AND
|| Logical OR
! Logical NOT
(x || y) evaluates to true
(true && x) evaluates to true
count = count - 1;
can be written as:
--count; or count--;
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
58 Compiled By Sahile.T
7. Special Operators
Java supports some special operators of interest such as instanceof
operator and member selection operator(.).
int a=110;
float b=23.5;
(type-name)expression;
where type-name is one of the standard data types.
Example :
a=(int)21.3/(int)3.5; a will be 7
61 Compiled By Sahile.T
Operator Precedence and Associativity.
Operator Description Associativity Rank
. Member Selection
() Function call
Left to right 1
[] Array elements reference
- Unary Minus
++ Increment
-- Decrement
Right to left 2
! Logical negation
~ One’s complement
(type) Casting
* Multiplication
Left to right 3
/ Division
% Modulus
62 Compiled By Sahile.T
Contd.
Operator Description Associativity Rank
+ Addition
Left to right 4
- Subtraction
<< Left Shift
Left to right 5
>> Right Shift
>>> Right shift with zero fill
< Less than
<= Less than or equal to
> Greater than Left to right 6
>= Greater than or equal to
instanceof Type comparison
== Equality
Left to right 7
!= Inequality
63 Compiled By Sahile.T
Operator Precedence and Associativity.
Operator Description Associativity Rank
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
64 Compiled By Sahile.T
//Demonstration of Java Expressions
public class DemoExpress
{
public static void main(String[] args)
{
System.out.println("===== BEGINNING OF THE PROGRAM
=====\n");
//Declaration and Initialization
int a=10,b=5,c=8,d=2;
float x=6.4f,y=3.0f;
//Order of Evaluation
int answer1=a*b+c/++d;
int answer2=--a*(b+++c)/d++;
//Type Conversion
float answer3=a/c;
float answer4=(float)a/c;
float answer5=a/y;
65 Compiled By Sahile.T
//Modulo Operations
int answer6=a%c;
float answer7=x%y;
//Logical Operations
boolean bool1=a>b && c>d;
boolean bool2=a<b && c>d;
boolean bool3=a<b || c>d;
boolean bool4=!(a-b==c);
System.out.println("Order of Evaluation");
System.out.println("a*b+c/++d + "+answer1);
System.out.println("--a*(b+++c)/d++ = " +answer2);
System.out.println("================");
System.out.println("Type Conversion");
System.out.println(" a/c = "+answer3);
System.out.println("(float)a/c = " + answer4);
System.out.println(" a/y = " + answer5);
66 Compiled By Sahile.T
System.out.println("================");
System.out.println("Modulo Operations");
System.out.println(" a%c = "+answer6);
System.out.println(" x%y = "+answer7);
System.out.println("================");
System.out.println("Logical Operations");
System.out.println(" a>b && c>d = "+bool1);
System.out.println(" a<b && c>d = "+bool2);
System.out.println(" a<b || c>d = "+bool3);
System.out.println(" !(a-b==c) = "+bool4);
System.out.println("================");
System.out.println("Bitwise Operations");
67 Compiled By Sahile.T
//Shift Operators
int l=8, m=-8,n=2;
System.out.println(" n & 2= "+(n&2));
System.out.println(" l | n= "+(l|n));
System.out.println(" m | n= "+(m|n));
System.out.println(" l >> 2= "+(l>>2));
System.out.println(" l >>> 1= "+(l>>>1));
System.out.println(" l << 1= "+(l<<1));
System.out.println(" m >> 2= "+(m>>2));
System.out.println(" m >>> 1= "+(m>>>1));
System.out.println("\n===== END OF THE PROGRAM =====");
68 Compiled By Sahile.T
Section V
Variables and Primitive Data
Types
69 Compiled By Sahile.T
Variables
A variable is an identifier that denotes a storage location used to
store a data value.
Unlike constants, that remain unchanged during the execution
of a program, a variable may take different values at different
times during the execution of the program.
It is good practice to select variable names that give a good
indication of the sort of data they hold:
For example, if you want to record the size of a hat,
hatSize is a good choice for a name whereas qqq would
be a bad choice.
70
Compiled By Sahile.T
Contd.
Variable names may consist of alphabets, digits, the
underscore (_) and dollar ($) characters, subject to the
following conditions:
1. They should not begin with a digit.
2. Keywords should not be used as a variable name.
3. White spaces are not allowed.
4. Uppercase and lowercase are distinct. i.e. A rose is not a
Rose is not a ROSE.
5.71 Variable names can be of Compiled
any length.
By Sahile.T
Data Types
Every variable in Java has a data type.
Data types specify the size and type of values that can be stored.
Java is language is rich in the data types.
Java data types are of two type:
Primitive Data Types (also called intrinsic or built-in data
types)
Non-Primitive data Types (also known as Derived or
reference types)
72 Compiled By Sahile.T
Data Types in Java
Primitive Non-Primitive
(Intrinsic) (Derived)
Interfaces
Integer Floating-Point Character Boolean
74 Compiled By Sahile.T
A. Integer Data types
There are four data types that can be used to store integers.
The one you choose to use depends on the size of the number that
we want to store.
75 Compiled By Sahile.T
B. Floating-Point Types
Integer types can hold only whole numbers and therefore we need
another type known as floating point type to hold numbers
containing fractional parts.
There are two data types that can be used to store decimal values
(real numbers).
76 Compiled By Sahile.T
C. Character Type
Is used to store character constants in memory.
Java provides a character data type called char
The char data type assumes a size of 2 bytes but, basically, it
can hold only a single character.
There are only two values that a Boolean can take: true or
false.
3. The place of declaration (in the program) declares the scope of the variable.
Example:
int count, x,y; //Declaration
char firstLetterOfName = 'e' ; // Declaration & initialization
79 Compiled By Sahile.T
Assigning Values to Variables
A variable must be given a value after it has been declared but
before it is used in an expression in two ways :
By using an assignment statement
82 Compiled By Sahile.T
Scope of Variables
1. Instance Variables: are declared in a class, but outside a method,
constructor or any block.
• are created when an object is created with the use of the key word 'new' and destroyed
when the object is destroyed.
2. Class Variables: are also known as static variables, are declared with
the static keyword in a class, but outside a method, constructor or a block.
• Are global to a class and belong to the entire set of objects that class creates.
84 Compiled By Sahile.T
Introduction
The statements inside your source files are generally executed
from top to bottom, in the order that they appear.
• if Statements
• switch Statements
86 Compiled By Sahile.T
Decision Making with if Statement
The if statement is a powerful decision making statement.
Test False
expression
?
True
When all the conditions become false, then the final else
containing the default statement will be executed.
The syntax of an if …. else if statement is:
90 Compiled By Sahile.T
if (expression 1)
{
statement(s)-1;
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default-statement;
rest_of_program;
91 Compiled By Sahile.T
4. Nested if … else Statement
if…else statements can be put inside other if…else
statements. such statements are called nested if … else
statements.
Is used whenever we need to make decisions after
checking a given decision.
The syntax of a nested if…else statement is shown in the
next slide.
.
92 Compiled By Sahile.T
if (expression 1)
{
statement(s)-1;
if (expression 1.1)
}
{
True-block Statement 1.1
} Nested if statement
else
{
Falsse-block Statement 1.1
}
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default-statement;
rest_of_program;
93 Compiled By Sahile.T
Switch statement
We can design a program with multiple alternatives using if
statements to control the selection.
The break statement at the end of each block signals the end of a
particular case and causes an exit from the switch statement.
97 Compiled By Sahile.T
The ?: (Conditional)Operator
Is useful for making a two-way decisions.
This operator is a combination of ? and : and takes three operands.
General formula:
conditional expression ? Expression1:expression2;
98 Compiled By Sahile.T
Exercise
1. Find out Errors in the following program and discuss ways for correction.
a) //Errors.java
public Class Errors{
public void main(String [] args){
int i, j = 32768;
short s = j;
double m = 5.3f, n = 2.1f;
float x = 5.3, y = 2.1;
byte z = 128;
System.out.println("x % y = "+x % y);
boolean b = 1 ;
if (b) System.out.println(“b is true”);
else System.out.println(“b is false”);
}
}
99 Compiled By Sahile.T
2. Write a Java application program that asks the user to enter two numbers obtains the
numbers from the user and prints the sum, product, difference and quotient of the
numbers?
3. Write a Java application program that asks the user to enter two integers, obtains the
numbers from the user and displays the larger number followed by the words “is
larger than “ the smaller number in the screen. If the numbers are equal, print the
message “These numbers are equal.”
4. Write four different Java statements that each add 1 to integer variable x.
5. Rewrite each of the following without using compound relations:
a) if(grade<=59 && grade>=50)
second+=1; 6. Write a Java application program
b) if(num>100 || num<0) that reads the coefficients of a
System.out.prinln(“Out of Range”); quadratic equation (ax2+bx+c=0),
else generates and display the roots.
Note:
sum+=num;
An appropriate message should be
c) If((M>60 && N>60)||T>200) generated when the user types an
y=1; invalid input to the equation.
else
y=0;
100 Compiled By Sahile.T
Chapter II Section II
Decision Making and Looping
The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
On reaching the do statement, the program proceeds to evaluate the body of loop
first.
At the end of the loop, the test condition in the while statement is evaluated. If it is
true, the program continues to evaluate the body of the loop once again.
107 Compiled By Sahile.T
Contd.
When the condition becomes false, the loop will be terminated and
the control goes to the statement that appears immediately after the
while statement.
The while loop is an exit-controlled loop statement.
Example:
int sum=0,n=1;
do
{
sum+=n;
n++;
} while(n<=100);
System.out.println(“Sum=“+sum;
108 Compiled By Sahile.T
3. The for loop
Is another entry-controlled loop that provides a more concise loop controlled
structure.
Syntax for the for loop is:
for(initialization; test condition; increment)
{
Body of the loop;
}
We use the for loop if we know in advance for how many times the body of the
loop is going to be executed.
But use do…. while loop if you know the body of the loop is going to be executed
at least once.
109 Compiled By Sahile.T
Contd.
The execution of the for loop statement is as follows:
1. Initialization of the control variable(s) is done first, using
assignment statement.
Example:
for(sum=0, i=1; i<20 && sum<100; ++i)
{
sum=sum+i;
}
D. You do not have to fill all three control sections, one or more
sections can be omitted but you must still have two
semicolons.
Example:
int n = 0;
for(; n != 100;) {
System.out.println(++n);
}
113 Compiled By Sahile.T
Nesting of for loops
You can nest loops of any kind one inside another to any depth.
Example:
for(int i = 10; i > 0; i--)
{
while (i > 3)
{
if(i == 5){
Inner Outer
break; Loop Loop
}
System.out.println(i);
i--;
}
System.out.println(i*2);
}
114 Compiled By Sahile.T
Jumps in Loops
Jump statements are used to unconditionally transfer the program
control to another part of the program.
Java has three jump statements: break, continue, and return.
1. The break statement
A break statement is used to abort the execution of a loop. The
general form of the break statement is given below:
break label;
It may be used with or without a label.
When it is used without a label, it aborts the execution of the
innermost switch, for, do, or while statement enclosing the break
statement. When used with a label, the break statement aborts the
execution of any enclosing statement matching the label.
A label is an identifier that uniquely identifies a block of code.
115 Compiled By Sahile.T
Examples:
1) Outer: for( int k=1; k< 10; k++){
int i=k;
while ( i < 5) {
if(i%5==0) break Outer; // jump out of both loops
System.out.print(“ “+i);
i++;
}
Syetem.out.println(“Outer Loop”);
}
2) int i=1;
while ( i < 10) {
if(i%2==0) break;
System.out.println(“ “+i);
}
System.out.println(“Out of the while loop”);
116
2. The continue statement
is used to alter the execution of the for, do, and while statements.
The general form of the continue statement is:
continue label;
It may be used with or without a label. When used without a label,
it causes the statement block of the innermost for, do, or while
statement to terminate and the loop’s boolean expression to be re-
evaluated to determine whether the next loop repetition should take
place.
Example:
int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}
What is the value of sum?
1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
118 Compiled By Sahile.T
3. The return Statement
A return statement is used to transfer the program control to the
caller of a method.
The general form of the return statement is given below:
return expression;
If the method is declared to return a value, the expression used
after the return statement must evaluate to the return type of that
method. Otherwise, the expression is omitted.
a) c) 5
$ $ $ $ $ 454
$ $ $ $ 34543
$ $ $ 2345432
$ $ 123454321
$
b) 1
d) 1 2 3 4 5 4 3 2 1
1 2
1234321
1 2 3 12321
1 2 3 4 121
1 2 3 4 5 1
122 Compiled By Sahile.T
Chapter II Section III
Arrays and Strings
Array indexing starts from 0 and ends at n-1, where n is the size
of the array.
index values
Creating an Array
Like any other variables, arrays must be declared and created
in the computer memory before they are used.
Array creation involves three steps:
1. Declare an array Variable
2. Create Memory Locations
3. Put values into the memory locations.
126 Compiled By Sahile.T
1. Declaration of Arrays
Arrays in java can be declared in two ways:
i. type arrayname [ ];
ii. type[ ]arrayname;
Example:
int number[];
float slaray[];
float[] marks;
The Java interpreter checks array indices to ensure that they are
valid during execution.
Array Length
In Java, all arrays store the allocated size in a variable named
length.
We can access the length of the array array1using array1.length.
Example:
int size = array1.length;
131 Compiled By Sahile.T
//sorting of a list of Numbers if (num[i] < num [j])
class Sorting {
{ //Interchange Values
public static void main(String [ ]args) int temp = num[i];
{ num [i] = num [j];
int num[ ]= {55, 40, 80, 12, 65, 77}; num [j] = temp;
int size = num.length; }
System.out.print(“Given List: “); }
for (int i=0; i<size; i++) }
{ System.out.print("SORTED LIST" );
System.out.print(" " + num[ i ] ); for (int i=0; i<size; i++)
} {
System.out.print("\n"); System.out.print(" " " + num [i]);
//Sorting Begins }
for (int i=0; i<size; i++) System.out.println(" ");
{ }
for (int j=i+1; j<size; j++) }
{
132 Compiled By Sahile.T
Two-Dimensional Arrays
A 2-dimensional array can be thought of as a grid (or matrix) of
values.
Each element of the 2-D array is accessed by providing two
indexes: a row index and a column index
A 2-D array is actually just an array of arrays.
A multidimensional array with the same number of columns in
every row can be created with an array creation expression:
Example:
int myarray[][]= int [3][4];
133 Compiled By Sahile.T
Contd.
Like the one-dimensional arrays, two-dimensional arrays may be
initialized by following their declaration with a list of initial values
enclosed in braces. For example,
int myarray[2][3]= {0,0,0,1,1,1};
or
int myarray[][]= {{0,0,0},{1,1,1}};
We can refer to a value stored in a two-dimensional array by using
indexes for both the column and row of the corresponding
element. For Example,
int value = myarray[1][2];
134 Compiled By Sahile.T
//Application of two-dimensional Array
class MulTable{
final static int ROWS=12;
final static int COLUMNS=12;
public static void main(String [ ]args) {
int pro [ ] [ ]= new int [ROWS][COLUMNS];
int i=0,j=0;
System.out.print("MULTIPLICATION TABLE");
System.out.println(" ");
for (i=1; i<ROWS; i++)
{
for (j=1; j<COLUMNS; j++)
{
pro [i][j]= i * j;
System.out.print(" "+ pro [i][j]);
}
System.out.println(" " );
}
}
}
135 Compiled By Sahile.T
Variable Size Arrays
Java treats multidimensional array as “array of arrays”.
It is possible to declare a two-dimensional array as follows:
int x[][]= new int[3][];
x[0] = new int[2];
x[1] = new int[4];
x[2] = new int[3];
This statement creates a two-dimensional array having different
length for each row as shown below:
x[0][1]
X[0]
X[1]
X[2] x[1][3]
x[2][1]
136 Compiled By Sahile.T
Chapter II
3. Write a program which reads the values for two matrices and
displays their product.
151