Java Module 1
Java Module 1
Programming in Java
MODULE 1
Syllabus: An Overview of Java: Object-Oriented Programming, A First Simple Program, A Second Short Program,
Two Control Statements, Using Blocks of Code, Lexical Issues, The Java Class Libraries.
Data Types, Variables, and Arrays: Java Is a Strongly Typed Language, The Primitive Types, Integers, Floating-
Point Types, Characters, Booleans, A Closer Look at Literals, Variables, Type Conversion and Casting, Automatic
Type Promotion in Expressions, Arrays, A Few Words About Strings
An Overview of Java
The key features of Java are security and portability (platform-independent nature). When we download any
application from the internet, there is a chance that the downloaded code contain virus. But, downloading the Java
code assures security. Java program can run on any type of system connected to internet and thus provides
portability.
These two points make it a platform independent language. Hence, the users do not have to change the syntax of the
program according to the Operating System and do not have to compile the program again and again on different
Operating Systems. The meaning of this point can be understood as you read further.
C and C++ are platform dependent languages as the file which compiler of C,C++ forms is a
.exe(executable) file which is operating system dependent. The C/C++ program is controlled by the operating
system whereas, the execution of a Java program is controlled by JVM (Java Virtual Machine).
The JVM is the Java run-time system and is the main component of making the java a platform independent
language. For building and running a java application we need JDK(Java Development Kit) which comes bundled
with Java runtime environment(JRE) and JVM. With the help of JDK the user compiles and runs his java program.
As the compilation of java program starts the Java Byte code is created a .class file is created by JRE. Byte code is
a highly optimized set of instructions designed to be executed by JVM. Now the JVM comes into play, which is
made to read and execute this byte code. The JVM is linked with operating system and runs the byte code to execute
the code depending upon operating system. Therefore, a user can take this class file(Byte code file) formed to any
operating system which is having a JVM installed and can run his program easily without even touching the syntax
of a program and without actually having the source code. The .class file which consists of byte code is not user-
understandable and can be interpreted by JVM only to build it into the machine code.
Remember, although the details of the JVM will differ from platform to platform, all understand the same Java
bytecode. If a Java program were compiled to native code, then different versions of the same program would have
to exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the
execution of bytecode by the JVM is the easiest way to create truly portable programs. Java also has the standard
data size irrespective of operating system or the processor. These features make the java as a portable (platform-
independent) language.
2
Programming in Java
Two Paradigms
Every program consists of two elements viz. code and data. A program is constructed based on two paradigms: a
program written around what is happening (known as process-oriented model) and a program written around who
is being affected (known as object-oriented model). In process oriented model, the program is written as a series of
linear (sequential) steps and it is thought of as code acting on data. Since this model fails to focus on real-world
entities, it will create certain problems as the program grows larger.
The object-oriented model focuses on real-world data. Here, the program is organized as data and a set of well-
defined interfaces to that data. Hence, it can be thought of as data controlling access to code. This approach helps to
achieve several organizational benefits.
Abstraction
Abstraction can be thought of as hiding the implementation details from the end-user. A powerful way to manage
abstraction is through the use of hierarchical classifications. This allows us to layer the semantics of complex
systems, breaking them into more manageable pieces. For example, we consider a car as a vehicle and can be
thought of as a single object. But, from inside, car is a collection of several subsystems viz. steering, brakes, sound
system, engine etc. Again, each of these subsystems is a collection of individual parts (Ex. Sound system is a
combination of a radio and CD/tape player). As an owner of the car, we manage it as an individual entity by
achieving hierarchical abstractions.
Hierarchical abstractions of complex systems can also be applied to computer programs. The data from a traditional
process-oriented program can be transformed by abstraction into its component objects. A sequence of process steps
can become a collection of messages between these objects. Thus, each of these objects describes its own unique
behavior. You can treat these objects as concrete entities that respond to messages telling them to do something.
This is the essence of object-oriented programming.
OOPs Principles: Encapsulation, Inheritance and Polymorphism are the basic principles of any object oriented
programming language.
Encapsulation is the mechanism to bind the data and code working on that data into a single entity. It provides the
security for the data by avoiding outside manipulations. In Java, encapsulation is achieved using classes. A class is a
collection of data and code. An object is an instance of a class. That is, several objects share a common structure
(data) and behavior (code) defined by that class. A class is a logical entity (or prototype) and an object is a physical
entity. The elements inside the class are known as members. Specifically, the data or variables inside the class are
called as member variables or instance variables or data members. The code that operates on these data is referred
to as member methods or methods (In C++, we term this as member function). The method operating on data will
define the behavior and interface of a class.
Another purpose of the class is to hide the information from outside manipulation. Class uses public and private
interfaces. The members declared as private can only be accessed by the members of that class, whereas, the public
members can be accessed from outside the class.
Examples: Medicine (capsule), school bag,
Consider the below real time example: Encapsulation: As a driver you know how to start the car by pressing the start
button and internal details of the starting operations are hidden from you. So the entire starting process is hidden from
you otherwise we can tell starting operation is encapsulated from you.
3
Programming in Java
Inheritance: It is a Process by which object acquires the properties of another object.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended
class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base
class or a parent class.\
Reusability: By which facilitates you to reuse the fields and methods of the existing class when you create a new
class.
By this process one object can acquire the properties of another object. It supports the concept of hierarchical
classification. This concept can be depicted using following figure.
Vehicle
Bus Van
Car Bike
In the above example picture we have different types of vehicles. All will exhibit properties of vehicle like, engine,
seat, mirror, wheel, window , door etc. Properties of vehicle inherited to subclasses. If we apply the above concept
for programming, it can be easily understood that a code written is reusable. Thus, in this mechanism, it is possible
for one object to be a specific instance of a more general case. Using inheritance, an object need only define those
qualities that make it a unique object within its class. It can inherit its general attributes from its parent. Hence,
through inheritance, we can achieve generalization-specialization concept. The top-most parent (or base class or
super class) class is the generalized class and the bottom-most child (or derived class or subclass) class is a more
specialized class with specific characteristics.
Polymorphism can be thought of as one interface, multiple methods. It is a feature that allows one interface to be
used for a general class of actions. The specific action is determined by the exact nature of the situation. Consider
an example of performing stack operation on three different types of data viz. integer, floating-point and characters.
In a non-object oriented programming, we write functions with different names for push and pop operations though
the logic is same for all the data types. But in Java, the same function names can be used with data types of the
parameters being different.
Examples: Human, Water, Stack
4
Programming in Java
2.2
a 10
b 8 5.6
5 8.1
c 7 6.8
d
Char stack Int stack Float stack
Here we have different types of stack. But all work in the same way. So one interface , multiple methods.
Save this program as Prg1.java. A java program source code is a text file containing one or more class definitions is
called as compilation unit and the extension of this file name should be .java.
To compile above program, use the following statement in the command prompt –
javac Prg1.java
(Note: You have to store the file Prg1.java in the same location as that of javac compiler or you should set the
Environment PATH variable suitably.)
Now, the javac compiler creates a file Prg1.class containing bytecode version of the program, which can be
understandable by JVM. To run the program, we have to use Java application launcher called java. That is, use the
command –
java Prg1
Note: When java source code is compiled, each class in that file will be put into separate output file having the same
name as of the respective class and with the extension of .class. To run a java code, we need a class file containing
main() function (Though, we can write java program without main(), for the time-being you assume that we need a
main() function!!!). Hence, it is a tradition to give the name of the java source code file as the name of the class
containing main() function.
Let us have closer look at the terminologies used in the above program now –
Here, type is any built-in or user-defined data type (We will discuss various data types later in detail).
var_name is any valid name given to the variable. Consider the following example –
In the above program, we have declared an integer variable n and then assigned a value to it. Now, observe the
statement,
System.out.println(“The value of n is: “ + n);
Here, we are trying to print a string value “The value of n is:” and also value of an integer n together. For this, we
use + symbol. Truly speaking, the value of n is internally converted into string type and then concatenated with the
string “The value of n is:”. We can use + symbol as many times as we want to print several values.
The above program uses one more method System.out.print() which will keep the cursor on the same line after
displaying the output. That is, no new line is not included in it.
6
Programming in Java
if Statement: When a block of code has to be executed based on the value of a condition, if statement is used.
Syntax would be –
if(condition)
{
//do something
}
Here, condition has to be Boolean statement (unlike C/C++, where it could be integer type). If the
condition is true, the statement block will be executed, otherwise not.
To have a Boolean result from an expression, we may use relational operators like <, >, <=, == etc.
for Statement: Whenever a set of statements has to be executed multiple times, we will use for
statement. The syntax would be –
for(initialization; condition; updation)
{
//statement block
}
7
Programming in Java
Here, initialization contains declaring and/or initialization of one or more variables, that
happens only once
condition Must be some Boolean expression, that will be checked immediately after
initialization and each time when there is an updation of variables
updation Contains increment/decrement of variables, that will be executed after
executing statement block
For example, a block can be a target for Java’s if and for statements. Consider this if statement:
if(x < y)
{ // block begins
x = y;
y = 0;
} // block ends here
The main reason for the existence of blocks of code is to create logically inseparable units of code.
Whitespace : In Java, whitespace is a space, tab or newline. Usually, a space is used to separate tokens; tab and
newline are used for indentation.
Identifiers : Identifiers are used for class names, method names, and variable names. An identifier may be any
sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters.
They must not begin with a number. As Java is case-sensitive, Avg is a different identifier than avg.
Examples of valid identifiers: Avg, sum1, $x, sum_sq etc.
Examples of invalid identifiers: 2sum, sum-sq, x/y etc.
8
Programming in Java
Literals : A constant value in Java is created by using a literal representation of it. For example, 25 (an
integer literal), 4.5 (a floating point value), ‘p’ (a character constant, “Hello World” (a string value).
Comments : There are three types of comments defined by Java. Two of these are well-know viz. single-line
comment ( starting with //), multiline comment (enclosed within /* and */). The third type of
comment viz. documentation comment is used to produce an HTML filethat documents your
program. The documentation comment begins with a /** and endswith a */.
Separators : In Java, there are a few characters that are used as separators. The most commonly used separator in
Java is the semicolon which is used to terminate statements. The separators are shown in the
following table:
Abstract assert boolean break byte case catch char class const
Continue default goto do double else enum extends final finally
Float for if implements import instanceof int interface long native
New package private protected public return short static strictfp super
Switch synchronized this throw throws transient try void while
The keywords const and goto are reserved but are rarely used. In addition to the keywords, Java
reserves the following: true, false, and null. These are values defined by Java. You may not use
these words for the names of variables, classes and so on.
In other words, every variable has a type, every expression has a type, and every type is strictly defined. And, all
assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. There
are no automatic coercions or conversions of conflicting types as in some languages. The Java compiler checks all
expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be
corrected before the compiler will finish compiling the class. These features of Java make it a strongly typed
language.
These types can be used as primitive types, derived types (arrays) and as member of user-defined types(classes). All
these types have specific range of values irrespective of the platform in which the program
being run. In C and C++ the size of integer may vary (2 bytes or 4 bytes) based on the platform. Because of
platform-independent nature of Java, such variation in size of data types is not found in Java, and thus making a
Java program to perform better.
Integers
Java defines four integer types viz. byte, short, int and long. All these are signed numbers and Java does not support
unsigned numbers. The width of an integer type should not be thought of as the amount of storage it consumes, but
rather as the behaviour it defines for variables and expressions of that type. The Java run-time environment is free to
use whatever size it wants, as long as the types behave as you declared them. The width and ranges of these integer
types vary widely, as shown in this table:
Width
Name Range
(in bits)
long 64 -263 to +263 –1
byte : This is the smallest integer type. Variables of type byte are especially useful when you are working with a
stream of data from a network or file. They are also useful when you are working with raw binary data that
may not be directly compatible with Java’s other built-in types. Byte variables are declared by use of the
byte keyword. For example,
byte b, c;
short : It is probably the least-used Java type. Here are some examples of short variable declarations:short s;
short t;
10
Programming in Java
int : The most commonly used integer type is int. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays. Although you might think that using a byte or short would
be more efficient than using an int in situations in which the larger range ofan int is not needed, this may
not be the case. The reason is that when byte and short values are used in an expression they are
promoted to int when the expression is evaluated. (Type promotion is described later in this chapter.)
Therefore, int is often the best choice when an integer is needed.
long : It is useful for those occasions where an int type is not large enough to hold the desired value.
The range of a long is quite large. This makes it useful when big, whole numbers are needed.
Width
Name Range
(in bits)
double 64 4.9e–324 to 1.8e+308
float : The type float specifies a single-precision value that uses 32 bits of storage. Single precision is
faster on some processors and takes half as much space as double precision, but will become
imprecise when the values are either very large or very small. Variables of type float are useful
when you need a fractional component, but don’t require a large degree of precision. For example,
float can be useful when representing currencies, temperature etc. Here are some example float
11
Programming in Java
variable declarations:
float hightemp, lowtemp;
double : Double precision is actually faster than single precision on some modern processors that have
been optimized for high-speed mathematical calculations. All transcendental math functions, such
as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many
iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Characters
In Java, char is the data type used to store characters. In C or C++, char is of 8 bits, whereas in Java it requires 16
bits. Java uses Unicode to represent characters. Unicode is a computing industry standard for the consistent
encoding, representation and handling of text expressed in many languages of the world. Unicode has a collection of
more than 109,000 characters covering 93 different languages like Latin, Greek, Arabic, Hebrew etc. That is why, it
requires 16 bits. The range of a char is 0 to 65,536. The standard set of characters known as ASCII still ranges from
0 to 127 as always, and the extended 8 -bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed
to allow programs to be written for worldwide use, it makes sense that it would use Unicode to represent characters.
Though it seems to be wastage of memory as the languages like English, German etc. can accommodate their
character set in 8 bits, for a global usage point of view, 16-bits are necessary.
Though, char is designed to store Unicode characters, we can perform arithmetic operations on them. For example,
we can add two characters (but, not char variables!!), increment/decrement character variable etc. Consider the
following example for the demonstration of characters.
/* ch1=35;
ch2=30;
char ch3;
ch3=ch1+ch2; //Error
*/
ch2='6'+'A'; //valid
System.out.println("ch2 now contains "+ch2);
}
}
Booleans
For storing logical values (true and false), Java provides this primitive data type. Boolean is the output of any
expression involving relational operators. For control structures (like if, for, while etc.) we need to give boolean
type. In C or C++, false and true values are indicated by zero and a non-zero numbers respectively. And the output
of relational operators will be 0 or 1. But, in Java, this is not the case. Consider the following program as an
illustration.
if(b)
System.out.println("True block");
13
Programming in Java
b = false;
if(b)
System.out.println("False Block will not be executed");
b=(3<5);
System.out.println("3<5 is " +b);
}
}
The output would be –
b is false b
is true True
block3<5 is
true
NOTE: Size of a Boolean data type is JVM dependent. But, when Boolean variable appears in anexpression,
Java uses 32-bit space (as int) for Boolean to evaluate expression.
1.11 A Closer Look at Literals
A literal is the source code representation of a fixed value. In other words, by literal we mean any number, text, or
other information that represents a value. Literals are represented directly in our code without requiring
computation. Here we will discuss Java literals in detail.
Integer Literals
Integers are the most commonly used type in the typical program. Any whole number value is an integer literal. For
example, 1, 25, 33 etc. These are all decimal values, having a base 10. With integer literals we can use octal (base 8)
and hexadecimal (base 16) also. Octal values are denoted in Java by a leading zero. Normal decimal numbers cannot
have a leading zero. Thus, a value 09 will produce an error from the compiler, since 9 is outside of octal’s 0 to 7
range. Hexadecimal constants denoted with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to
15, so A through F (or a through f ) are substituted for 10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer value. It is possible to assign an integer literal to
other integer types like byte or long. When a literal value is assigned to a byte or short variable, no error is
generated if the literal value is within the range of the target type. An integer literal can always be assigned to a
long variable. However, to specify a long literal, you will need to explicitly tell the compiler that the literal value is
of type long. You do this by appending an upper- or lowercase L to the literal. For example, 0x7ffffffffffffffL or
9223372036854775807L is the largest long. An integer can also be assigned to a char as long as it is within range.
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. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation
floating-point numbers. Scientific notation uses a standard-notation, 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. Examples include 6.022E23, 314159E–05, and 2e+100.
Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the
constant. You can also explicitly specify a double literal by appending a D or d. Doing so is, of course, redundant.
The default double type consumes 64 bits of storage, while the less-accurate float type requires only 32 bits.
14
Programming in Java
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. A literal
character is represented inside a pair of single quotes. All of the visible ASCII characters can be directly entered
inside the quotes, such as ‘a’, ‘z’, and ‘@’. For characters that are impossible to enter directly, there are several
escape sequences that allow you to enter the character you need, such as ‘\’’ for the single-quote character itself and
‘\n’ for the new-line character. There is also a mechanism for directly entering the value of a character in octal or
hexadecimal. For octal notation, use the backslash followed by the three-digit number. For example, ‘\141’ is the
letter ‘a’. For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. Following table
shows the character escape sequences.
String Literals
String literals are a sequence of characters enclosed within a pair of double quotes. Examples of string literals are
“Hello World”
“two\nlines”
“\“This is in quotes\””
Java strings must begin and end on the same line. There is no line-continuation escape sequence asthere is in
some other languages. In Java, strings are actually objects and are discussed later in detail.
1.12 Variables
The variable is the basic unit of storage. 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 declarationis shown
here:
The type is any of primitive data type or class or interface. The identifier is the name of the variable. We can
initialize the variable at the time of variable declaration. To declare more than one variable of the specified type, use
a comma-separated list. Here are several examples of variable declarations of various types. Note that some
include an initialization.
int a, b=5, c;
byte z = 22;
double pi = 3.1416;
char x = '$';
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. For example,
The key point here is that the initialization expression may use any element valid at the time of the initialization,
including calls to methods, other variables, or literals.
Many languages like C/C++ have two scopes viz. global and local. But in Java, every line of code should be
embedded within a class. That is, no code is written outside the class. So, usage of the terms global and local makes
no sense. Instead, Java has two scopes viz. class level scope and method (or function) level scope. Class level scope
is discussed later and we will discuss method scope here.
The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they
too are included within the method’s scope. As a general rule, variables declared inside a scope are not visible (that
is, accessible) to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized access and/or modification. Indeed, the scope rules
provide the foundation for encapsulation. Scopes can be nested. For example, each time you create a block of code,
you are creating a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means that
objects declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true.
Objects declared within the inner scope will not be visible outside it.
Variables are created when their scope is entered, and destroyed when their scope is left. This means that a variable
will not hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold
their values between calls to that method. Also, a variable declared within a block will lose its value when the
block is left. Thus, the lifetime of a variable is confined to its scope.
for(i=0;i<3;i++)
{
int a=3; // a is local to this block
System.out.println("a is " + a);
a++;
}
}
}
Note that, variable a is declared within the scope of for loop. Hence, each time the loop gets executed, variable a is
created newly and there is no effect of a++ for next iteration.
NOTE:
In Java, same variable name cannot be used in nested scopes. That is, the following code snippet generates
error.
class Test
{
public static void main(String args[])
{
int x=3;
{
int x=5; //error!!
}
}
}
(Note that, having same variable name in nested scopes is VALID in C/C++).
When these two conditions are met, a widening conversion takes place. For example, the int type is always large
enough to hold all valid byte values, so no explicit cast statement is required. For widening conversions, the
numeric types, including integer and floating-point types, are compatible with each other. However, there are no
automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with
each other. As mentioned earlier, Java also performs an automatic type conversion when storing a literal integer
constant into variables of type byte, short, long, or char.
Here, target-type specifies the desired type to convert the specified value to. For example,
int a;
byte b;
b = (byte) a;
When a floating-point value is assigned to an integer type, the fractional component is lost. And such conversion is
called as truncation (narrowing). If the size of the whole number component is too large to fit into the target
integer type, then that value will be reduced modulo the target type’s range. Following program illustrates various
situations of explicit casting.
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
Here, when the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (the
range of a byte), which is 1 in this case. When the d is converted to an int, its fractional component is lost. When d
is converted to a byte, its fractional component is lost, and the value is reduced modulo 256, which in this case is
67.
Here, the result of operation x*y is 2000 and it exceeds the range of both the operands i.e. byte (-128 to
+127). In such a situation, Java promotes byte, short and char operands to int That is, the operation x*yis
performed using int but not byte and hence, the result 2000 is valid.
On the other hand, the automatic type conversions may cause error. For example,
byte x=10;
byte y= x *3; //causes error!!!
Here, the result of x *3 is 30, and is well within the range of byte. But, for performing this operation, the operands
are automatically converted to byte and the value 30 is treated as of int type. Thus, assigning an int to byte is not
possible, which generates an error. To avoid such problems, we should use type casting. That is,
byte x=10;
byte y=(byte) (x *3); //results 30
Let’s look closely at the type promotions that occur in this line from the program:
double result = (f * b) + (i / c) - (d * s);
In the first sub-expression, f * b, b is promoted to a float and the result of the sub-expression is float. Next, in the
sub-expression i / c, c is promoted to int, and the result is of type int. Then, in d * s, the value of s is promoted to
double, and the type of the sub-expression is double. Finally, these three intermediate values, float, int, and
double, are considered. The outcome of float plus an int is a float. Then the resultant float minus the last double is
promoted to double, which is the type for the final resultof the expression.
1.15 Arrays
Array is a collection of related items of same data type. Many items of an array share common name andare
accessed using index. Array can be one dimensional or multi-dimensional.
Arrays can be initialized at the time of declaration. An array initializer is a list of comma-separated expressions
surrounded by curly braces. The commas separate the values of the array elements. The array will automatically be
created large enough to hold the number of elements you specify in the array initializer. There is no need to use
new. For example –
20
Programming in Java
int arr[ ] ={1, 2, 3, 4};
The above statement creates an integer array of 4 elements.
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. If you try to
access elements outside the range of the array (negative numbers or numbers greater than the length of the array),
you will get a run-time error.
Multidimensional Arrays
Multidimensional arrays are arrays of arrays. Here, we will discuss two dimensional arrays in Java. The
declaration of 2-d array is as follows –
type arr_name[][]=new type [row_size][col_size];
here, row_size and col_size indicates number of rows and columns of 2-d arrays. In other words, row- size
indicates number of 1-d arrays and col_size indicates size of each of such 1-d array. Consider the following
program –
Instead of allocating memory for 2-day as shown in the above program, we can even do it in a different way. We
can first mention row_size and then using different statements, mention col_size as shown below –
int twoD[][]= new int[3][];
twoD[0]=new int[4] ;
twoD[1]=new int[4] ;
twoD[2]=new int[4] ;
21
Programming in Java
But, above type of allocation is not having any advantage unless we need uneven or irregular multidimensional
array. In Java, it is possible to have different number of columns for each row in a 2-d array. For example,
int i, j, k = 0;
Here, we have declared a 2-d array with 3 rows. But, number of columns for each row varies. The first 1-d array
has 3 elements, second 1-d array as a single element and the third 1-d array has 5 elements.
The alternative declaration form is also useful when specifying an array as a return type for a method.
QUESTION BANK:
1. Explain key attributes of Java programming language.
2. What is JVM? Why do we need it?
3. Briefly explain JRE and JDK.
4. Explain three OOPs principles.
5. What are Keywords and Identifiers? List the rules to write an identifier.
6. Discuss various data types used in Java.
7. What is type Conversion and Casting? Explain automatic type promotion in expressions with rules and a
demo program.
8. Explain scope and lifetime of variables with suitable examples.
9. "Java is a strongly typed language" - Justify this statement.
10. Write a note on
a. Java class libraries
b. Literals
11. Explain array declaration and initialization in Java with suitable examples.
12. What are multi-dimensional arrays? Explain with examples.
13. What are irregular arrays in Java? Explain with example.
14. Explain the process of compiling and running the java application with example