SRINIVAS UNIVERSITY
INSTITUTE OF ENGINEERING AND
TECHNOLOGY
MUKKA, MANGALURU
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
NOTES
OOP USING JAVA
SUBJECT CODE: 22SCS033
COMPILED BY:
Mrs. SWATHI R, Assistant Professor
2023-2024
MODULE 1
AN OVERVIEW OF JAVA
Object-Oriented Programming:
Object-oriented programming (OOP) is a computer programming model that organizes software design
around data, or objects, rather than functions and logic. An object can be defined as a data field that has
unique attributes and behavior.
Two Paradigms
Process-oriented/Procedural-oriented model:
This approach characterizes a program as a series of linear steps.
The process-oriented model can be thought of as code acting on data.
Produral languages such as C employ this model to considerable success
Object-oriented programming:
Object-oriented programming organizes a program around its data (that is objects) and a set of
well-defined interfaces to that data.
Object-oriented program can be characterized as data controlling access to code.
OOP USING JAVA (22SCS033) Page 1
OOP Principles
All object-oriented programming languages provide mechanisms that help you implement the object-
oriented model. They are abstraction, encapsulation, inheritance, and polymorphism
OOP USING JAVA (22SCS033) Page 2
Abstraction
An essential element of object-oriented programming is abstraction.
Humans manage complexity through abstraction.
A powerful way to manage abstraction is through the use of hierarchical classifications.
Example: For example, people do not think of a car as a set of tens of thousands of individual
parts. They think of it as a well-defined object with its own unique behavior. This abstraction
allows people to use a car to drive to the grocery store without being overwhelmed by the
complexity of the parts that form the car. They can ignore the details of how the engine,
transmission, and braking systems work. Instead, they are free to utilize the object as a whole.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. One way to think about
Encapsulation is as a protective wrapper that prevents the code and data from
being arbitrarily accessed by other code defined outside the wrapper.
Access to the code and data inside the wrapper is tightly controlled through a well-defined
interface.
i) In Java, the basis of encapsulation is the class.
ii) A class defines the structure and behaviour (data and code) that will be shared by a set of
objects.
iii) Each object of a given class contains the structure and behaviour defined by the class, as if
it were stamped out by a mould in the shape of the class.
iv) Objects are sometimes referred to as instances of a class. Thus, a class is a logical
construct; an object has physical reality.
v) Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding
the complexity of the implementation inside the class.
a) Private: Private members can only be accessed within the class.
OOP USING JAVA (22SCS033) Page 3
b) Public: Public members can access outside of the class.
Inheritance
i) Inheritance is the process by which one object acquires the properties of another object.
ii) It supports the concept of hierarchical classification.
iii) For example, a Golden Retriever is part of the classification dog, which in turn is part of
the mammal class, which is under the larger class animal.
Animal
Mammal
Golden retriever
iv) In the above example Animal Class is a Super class and Mammal and Golden retriever
classes are derived classes.
OOP USING JAVA (22SCS033) Page 4
Types of Inheritence:
Polymorphism
i) Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions.
ii) More generally, the concept of polymorphism is often expressed by the phrase “one
interface, multiple methods.” This means that it is possible to design a generic interface to a
group of related activities.
iii) An excellent real time example of polymorphism is your Smartphone. The smartphone can
act as phone, camera, music player and what not, taking different forms and hence
polymorphism.
OOP USING JAVA (22SCS033) Page 5
A First Simple Program
Let’s start by compiling and running the short sample program as shown here.
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
OOP USING JAVA (22SCS033) Page 6
}
To compile use the following command
C:\> javac Example.java
The javac compiler creates a file called Example.class that contains the byte code version of the
program.
Java bytecode is the intermediate representation of the program that contains instructions
the Java Virtual Machine will execute.
javac is not code that can be directly executed.
To actually run the program, you must use the Java application launcher, called java.
To do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
This is a simple Java program.
A Closer Look at the First Sample Program
i) The program begins with the following lines
/*
This is a simple Java program.
OOP USING JAVA (22SCS033) Page 7
Call this file "Example.java".
*/
This is a multiline comment in which it is ignored by the compiler.
ii) The next line of code in the program is shown here:
class Example {
This line uses the keyword class to declare that a new class is being defined.
Example is an identifier that is the name of the class.
The entire class definition, including all of its member will be between the opening curly
brace ({) and the closing curly brace (}).
iii) The next line in the program is the single-line comment, shown here:
// Your program begins with a call to main().
iv) The next line of code is shown here:
public static void main(String args[]) {
This line begins the main( ) method. As the comment preceding it suggests, this is the
line at which the program will begin executing. All Java applications begin execution by calling
main( ). The keyword static allows main( ) to be called without
having to instantiate a particular instance of the class. 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 the class String.
v) The next line of code is shown here. Notice that it occurs inside main( ).
System.out.println("This is a simple Java program.");
OOP USING JAVA (22SCS033) Page 8
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. In this case, println( )
displays the string which is passed to it.
A Second Short Program
/*
Here is another short example.
Call this file "Example2.java".
*/
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
When you run this program, you will see the following output:
This is num: 100
OOP USING JAVA (22SCS033) Page 9
The value of num * 2 is 200
Following is the general form of a variable declaration:
type var-name;
Here, type specifies the type of variable being declared, and var-name is the name of the
variable.
Control Statements in java
1. Selection statements
2. Iterative statements
3. Jump statements
Selection statements:
if statement in java
OOP USING JAVA (22SCS033) Page 10
In java, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then
decides the execution of a block of statements. If the condition is True, then the block of
statements is executed and if it is False, then the block of statements is ignored. The syntax and
execution flow of if the statement is as follows.
Example:
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15){
System.out.println("10 is less than 15");
}
System.out.println("Outside if-block");
// both statements will be printed
}
}
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the
given condition then decides which block of statements to be executed based on the condition
result. If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed. The syntax and execution flow of if-else
OOP USING JAVA (22SCS033) Page 11
statement is as follows.
Example:
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15){
System.out.println("10 is less than 15");
}
else{
System.out.println("Outside if-block");
}
}
}
Nested if ladder statement in java
Writing an if statement inside another if-statement is called nested if statement. The general syntax
of the nested if-statement is as follows.
Syntax:
OOP USING JAVA (22SCS033) Page 12
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
if-else if statement in java
Writing an if-statement inside else of an if statement is called if-else-if statement. The general
syntax of the an if-else-if statement is as follows.
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
switch statement in java
Using the switch statement, one can select only one option from more number of options very
easily. In the switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches the value associated with an option, the
execution starts from that option. In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
OOP USING JAVA (22SCS033) Page 13
Example:
import java.util.Scanner;
public class SwitchStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Press any digit: ");
int value = read.nextInt();
switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
OOP USING JAVA (22SCS033) Page 14
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}
Java Iterative statements:
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control
looping statement. The syntax and execution flow of while statement is as follows.
OOP USING JAVA (22SCS033) Page 15
Example:
ipublic class WhileTest {
public static void main(String[] args) {
int num = 1;
while(num <= 10) {
System.out.println(num);
num++;
}
System.out.println("Statement after while!");
Output:
10
Statement after while!
OOP USING JAVA (22SCS033) Page 16
do-while statement in java
The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as the Exit control
looping statement. The do-while statement has the following syntax.
Java Program
public class DoWhileTest {
public static void main(String[] args) {
int num = 1;
do {
System.out.println(num);
num++;
}while(num <= 10);
System.out.println("Statement after do-while!");
OOP USING JAVA (22SCS033) Page 17
}
Output:
10
Statement after do-while!
The for Loop
Syntax:
for(initialization; condition; iteration) statement;
The initialization portion of the loop sets a loop control variable to an initial value. The
condition is a Boolean expression that tests the loop control variable. If the outcome of that test
is true, the for loop continues to iterate. If it is false, the loop terminates. The iteration
expression determines how the loop control variable is changed each time the loop iterates.
Here is a short program that illustrates the for loop:
/*
Demonstrate the for loop.
Call this file "ForTest.java".
*/
OOP USING JAVA (22SCS033) Page 18
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
This program generates the output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
In this example, x is the loop control variable. It is initialized to zero in the initialization portion
of the for. At the start of each iteration (including the first one), the conditional test x < 10 is
performed. If the outcome of this test is true, the println( ) statement is executed, and then the
iteration portion of the loop is executed. This process continues until the conditional test is
false.The increment operator is ++. The increment operator increases its operand by one. By use
of the increment operator, the preceding statement can be written like this:
x++;
Thus, the for in the preceding program will usually be written like this:
for(x = 0; x<10; x++)
for-each statement in java
OOP USING JAVA (22SCS033) Page 19
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to
traverse through an array or collection in Java. The for-each statement also known as enhanced
for statement. The for-each statement executes the block of statements for each element of the
given array or collection.
The for-each statement has the following syntax and execution flow diagram.
OOP USING JAVA (22SCS033) Page 20
Java Program
public class ForEachTest {
public static void main(String[] args) {
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList) {
System.out.println("i = " + i);
}
System.out.println("Statement after for-each!");
}
Output:
Using Blocks of Code
Java allows two or more statements to be grouped into blocks of code, also called code blocks.
This is done by enclosing the statements between opening and closing curly braces. Once a
block of code has been created, it becomes a logical unit that can be used any place that a single
statement can. For example, a block can be a target for Java’s if and for statements.
Consider this if statement:
if(x < y) { // begin a block
x = y;
y = 0;
OOP USING JAVA (22SCS033) Page 21
} // end of block
Let’s look at another example. The following program uses a block of code as the target of a for
loop.
/*
Demonstrate a block of code.
Call this file "BlockTest.java"
*/
class BlockTest {
public static void main(String args[]) {
int x, y;
y = 20;
// the target of this loop is a block
for(x = 0; x<10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
The output of the program is :
This is x: 0
This is y: 20
This is x: 1
This is y: 18
OOP USING JAVA (22SCS033) Page 22
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
In this case, the target of the for loop is a block of code and not just a single statement.Thus,
each time the loop iterates, the three statements inside the block will be executed.
Lexical Issues
Whitespace
Java is a free-form language. This means that you do not need to follow any special indentation
rules. In Java whitespace is a space, tab, or newline.
Identifiers
OOP USING JAVA (22SCS033) Page 23
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, lest they be confused with a numeric
literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value.
Some examples of valid identifiers are-
AvgTemp
count
a4
$test
this_is_ok
Invalid identifier names include these:
2count
high-temp
Not/ok
Literals
A constant value in Java is created by using a literal representation of it. For example, here are
some literals:
100 –integer literal
98.6 – floating-point literal
'X' –character constant
"This is a test"-string
Comments:
Java supports three types of comments
OOP USING JAVA (22SCS033) Page 24
i) Single line comment
ii) Multiline comment
iii) Documentation comment
The third type is called a documentation comment. This type of comment is used to produce an
HTML file that documents your program. The documentation comment begins with a /** and
ends with a */.
Separators
In Java, there are a few characters that are used as separators.
Symbo Name Purpose
l
Parentheses Used to contain lists of parameters in
method definition and invocation
Also used for defining precedence in
expressions, in control statements,
and surrounding cast types
Braces Used to contain the values of
automatically initialized arrays. Also
used to define a block of code, for
classes, methods, and local scopes.
Brackets Used to declare array
types. Also used when dereferencing
array values.
Semicolon Terminates statements.
Comma Separates consecutive identifiers in a
variable declaration. Also used to
chain statements together inside a
for statement.
Period Used to separate package names
from sub packages and classes used
to separate a variable or method
OOP USING JAVA (22SCS033) Page 25
from a reference variable.
The Java Keywords
abstract continue For new switch
Assert default Goto package synchronized
Boolean do If private this
Break double Implements protected throw
Byte else Import public throws
Case enum Instaceof return Transient
Catch extends Int short try
Char final Interface static void
Class finally Long strictfp volatile
Const float Native super while
There are 50 keywords currently defined in the Java language .These keywords are
combined with the syntax of the operators and separators, form the foundation of the Java
language. These keywords cannot be used as names for a variable, class, or method.
The Java Class Libraries
The two of Java’s built-in methods: println( ) and print( ) and these methods are members of
the System class, which is a class predefined by Java that is automatically included in your
programs. In the larger view, the Java environment relies on several built-in class libraries that
OOP USING JAVA (22SCS033) Page 26
contain many built-in methods that provide support for such things as I/O, string handling,
networking, and graphics. The standard classes also provide support for windowed output.
Data Types
The Primitive Types
Java defines eight primitive types of data:
1) byte
2) short
3) int
4) long
5) char
6) float
7) double
8) boolean.
The primitive types are also commonly referred to as simple types, and both terms will be
used in this book. These can be put in four groups:
In Integer Fl floating-point Characters Boolean
byte float char boolean
short
double
long
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers.
Name Width Range
Long 64 –
9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
Int 32 –2,147,483,648 to
OOP USING JAVA (22SCS033) Page 27
2,147,483,647
Short 16 –32,768 to 32,767
Byte 8 –128 to 127
Example program:
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
OOP USING JAVA (22SCS033) Page 28
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. There are two types:
Name Width Bits Approximation
Range
Double 64 64 4.9e–324 to
1.8e+308
Float 32 1.4e–045 to 3.4e+038
Example program:
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
Characters
In Java, the data type used to store characters is char.
Here is a program that demonstrates char variables:
OOP USING JAVA (22SCS033) Page 29
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
Output:
ch1 and ch2: X Y
Boolean
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false.
Here is a program that demonstrates the boolean type:
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
OOP USING JAVA (22SCS033) Page 30
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
Output:
b is false
b is true
This is executed.
10 > 9 is true
A Closer Look at Literals
Integer Literals:
Integers are probably the most commonly used type in the typical program. Any whole number
value is an integer literal.
Floating-Point Literals:
Floating-point numbers represent decimal values with a fractional component. They can be
expressed in either standard or scientific notation. Standard notation consists of a whole number
component followed by a decimal point followed by a fractional component.
OOP USING JAVA (22SCS033) Page 31
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have,
true and false. The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only
be assigned to variables declared as boolean, or used in expressions with Boolean operators.
Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values that can
be converted into integers and manipulated with the integer operators, such as the addition
and subtraction operators.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing
a sequence of characters between a pair of double quotes. Examples of string literals are
“Hello World”
“two\nlines”
“\”This is in quotes\”“
Character Escape Sequences:
Escape Sequence Description
\ddd Octal character (ddd)
\uxxx Hexadecimal Unicode character
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New line
OOP USING JAVA (22SCS033) Page 32
\f Form feed
\t Tab
\b Backspace
Variables
The variable is the basic unit of storage in a Java program. 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
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
To declare more than one variable of the specified type, use a comma separated list.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
Example program:
OOP USING JAVA (22SCS033) Page 33
Class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
The Scope and Lifetime of Variables
In Java, the two major scopes
defined by a class
defined by a method.
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
// y = 100; // Error! y not known here
OOP USING JAVA (22SCS033) Page 34
// x is still known here.
System.out.println("x is " + x);
Type Casting in Java
In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically. The automatic conversion is done by the compiler and manual
conversion performed by the programmer.
Types of Type Casting
There are two types of type casting:
1. Widening Type Casting
2. Narrowing Type Casting
Widening Type Casting:
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see
an example.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
OOP USING JAVA (22SCS033) Page 35
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
In the above example, we have taken a variable x and converted it into a long type. After that, the
long type is converted into the float type.
Narrowing Type Casting:
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.
double -> float -> long -> int -> short -> byte
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
public static void main(String args[])
double d = 166.66;
OOP USING JAVA (22SCS033) Page 36
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Above example converts double to long type
Arrays
An array is a group of like-typed variables that are referred to by a common name. Array
element is accessed by its index. Arrays offer a convenient means of grouping related
information.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type. The general form of a one-dimensional
array declaration is
type var-name[ ];
or
OOP USING JAVA (22SCS033) Page 37
type[] var_name;
Example:
int a[];
or
int[] a;
Array allocation is done is done using new
array_var = new type[size];
Example:
a=new int[10];
Example program:
Here is an example that uses a one-dimensional array. It finds the average of a set
of numbers.
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
Multidimensional Arrays
Multidimensional arrays are arrays of arrays.
OOP USING JAVA (22SCS033) Page 38
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Declaring multidimensional array:
int[][] arr=new int[3][3];//3 row and 3 column
int twoD [] [] = new int [4] [5];
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
1 2 3
2 4 5
4 4 5
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
OOP USING JAVA (22SCS033) Page 39
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for multi-dimensional array, you need to specify the memory for the
first dimension. Remaining dimensions separately
Ex : int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
Initializing two dimensional array
Example :
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
When you run this program, you will get the following output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
OOP USING JAVA (22SCS033) Page 40
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0
Alternative array declaration syntax
type[ ] var-name;
Example:
int[] arr = new int[5];
or
int arr[] = new int[5];
Char twod1[ ] [ ] = new char [3] [4];
Char [ ] [ ] twod2 = new char [3] [4];
A Few Words About Strings
The String type is used to declare string variables. You can also declare arrays of strings.
Aquoted string constant can be assigned to a String variable. A variable of type String can
be assigned to another variable of type String. You can use an object of type String as an
argument to println( ).
Example:
String str = "this is a test";
System.out.println(str);
Here, str is an object of type String. It is assigned the string “this is a test”. This string is
displayed by the println( ) statement.
OOP USING JAVA (22SCS033) Page 41
OOP USING JAVA (22SCS033) Page 42
OOP USING JAVA (22SCS033) Page 43