0% found this document useful (0 votes)
2 views24 pages

Java Module 1

The document provides an overview of Java programming, covering its object-oriented principles such as abstraction, encapsulation, inheritance, and polymorphism. It details the structure of Java programs, including the main method, control statements, and data types, emphasizing Java's strong typing and the classification of data types into primitive and non-primitive. Additionally, it includes simple program examples and explanations of key concepts like variables, control flow, and lexical issues in Java.

Uploaded by

thrineshthrishu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Java Module 1

The document provides an overview of Java programming, covering its object-oriented principles such as abstraction, encapsulation, inheritance, and polymorphism. It details the structure of Java programs, including the main method, control statements, and data types, emphasizing Java's strong typing and the classification of data types into primitive and non-primitive. Additionally, it includes simple program examples and explanations of key concepts like variables, control flow, and lexical issues in Java.

Uploaded by

thrineshthrishu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basics of JAVA programming [BPLCK205C]

MODULE 1
[

An Overview of Java: Object-Oriented Programming, A First Simple Program, A Second


Short Program, Two Control Statements, Using Blocks of Code, Lexical Issues. Data Types,
Variables, and Arrays: Java Is a Strongly Typed Language, The Primitive Types, Integers,
Floating-Point Types, Characters, Booleans, Variables, Type Conversion and Casting,
Automatic Type Promotion in Expressions, Arrays.

Object-Oriented Programming
Java is a general-purpose object-oriented programming language developed at sun
Microsystems of USA by James Gosling and team in the year 1991. The language was initially
called “Oak”, but was renamed as “JAVA” in 1995. Object-oriented programming (OOP) is at
the core of Java. In fact, all Java programs are to at least some extent object-oriented. OOP
is so integral to Java that it is best to understand its basic principles before you begin writing
even simple Java programs.

Object-oriented Programming Principles

1. Abstraction
An essential element of object-oriented programming is abstraction. Abstraction refers to,
providing only essential information to the outside word and hiding their background details
ie. to represent the needed information in program without presenting the details.
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.
2. Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse.

Dept. of CSE, VVCE, Mysuru. Page 1


Basics of JAVA programming [BPLCK205C]

Example: Capsule encapsulates several combinations of medicine. If combinations of


medicine are variables and methods then the capsule will act as a class and the whole
process is called Encapsulation as shown in the below figure.

Figure: Encapsulation
3. Inheritance
Inheritance is the process by which one object acquires the properties of another object.
This is important because it supports the concept of hierarchical classification and facilitates
reusability. Inheritance interacts with encapsulation as well.
Example: Automobiles inherits all of the attributes from Vehicles since Automobile is simply
more precisely specified vehicle. A deeply inherited subclass inherits all of the attributes
from each of its ancestors in the class hierarchy.

Figure: Inheritance
4. Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions or “The ability to use a method/function in different
ways in other words giving different meaning for method/ functions is called
polymorphism”.

Dept. of CSE, VVCE, Mysuru. Page 2


Basics of JAVA programming [BPLCK205C]

Example: The Same method area() can perform different operations in different scenarios.

Figure: Polymorphism

Java Program structure

Java program structure contains six stages. They are:


1) Documentation section: The documentation section contains a set of comment lines
describing about the program.

2) Package statement: The first statement allowed in a Java file is a package statement.
This statement declares a package name and informs the compiler that the class defined
here belong to the package.

3) Import statements: Import statements instruct the compiler to load the specific class
belongs to the mentioned package.

4) Interface statements: An interface is like a class but includes a group of method


deceleration. This is an optional statement.

5) Class definition: A Java program may contain multiple class definition. The class are used
to map the real world object.

6) Main method class: The main method creates objects of various classes and establishes
communication between them. On reaching to the end of main the program terminates
and the control goes back to operating system.

Dept. of CSE, VVCE, Mysuru. Page 3


Basics of JAVA programming [BPLCK205C]

A First Simple Program of JAVA


// This is a simple Java program. Call this file "[Link]".

class Example
{
public static void main(String args[])
{
[Link]("This is a simple Java Program.");
}
}
Output: This is a Simple Java Program.

Description

Class declaration: “class Example” declares a class, which is an object-oriented construct.


Example is a Java identifier that specifies the name of the class to be defined.

Opening braces: Every class definition of Java starts with opening braces and ends with
matching one.

The main line: The line “public static void main(String args[])” defines a method name main.
Java application program must include this main. This is the starting point of the interpreter
from where it starts executing. A Java program can have any number of classes but only one
class will have the main method.

Public: This key word is an access specifier that declares the main method as unprotected
and therefore making it accessible to the all other classes.

Static: Static keyword defines the method as one that belongs to the entire class and not for
a particular object of the class. The main must always be declared as static.

Void: the type modifier void specifies that the method main does not return any value.

The println: It is a method of the object out of system class. It is similar to the printf or cout
of c or c++.

Dept. of CSE, VVCE, Mysuru. Page 4


Basics of JAVA programming [BPLCK205C]

A Second Short Program


// Here is another short example. Call this file "[Link]".

class Example2
{
public static void main(String args[])
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
Output: This is num: 100
The value of num * 2 is 200

Description

Int num; declares an integer variable called num. Java (like most other languages) requires
that variables be declared before they are used. The keyword int specifies an integer type.
The general form of a variable declaration is type var-name;

num = 100; assigns to num the value 100. In Java, the assignment operator is a single equal
sign.

[Link]("This is num: " + num); In this statement, the plus sign causes the value
of num to be appended to the string that precedes it, and then the resulting string is output.
Using the + operator, you can join together as many items as you want within a single
println( ) statement.

print( ) is used to display the string “The value of num * 2 is ”. This string is not followed by a
newline. This means that when the next output is generated, it will start on the same line.
The print( ) method is just like println( ), except that it does not output a newline character
after each call.

Dept. of CSE, VVCE, Mysuru. Page 5


Basics of JAVA programming [BPLCK205C]

Two Control Statements


1) The if Statement
The Java if statement works much like the IF statement in any other language. Further, it is
syntactically identical to the if statements of other programming language.
The simplest form of if statement is: if(condition) statement;
Here, condition is a Boolean expression. If condition is true, then the statement is executed.
If condition is false, then the statement is bypassed.
Example : // Demonstrate the [Link] this file "[Link]".

class IfTest
{
public static void main(String args[])
{
int x, y;
x = 10;
y = 20;

if(x < y) [Link]("x is less than y");


x = x * 2;

if(x == y) [Link]("x now equal to y");


x = x * 2;

if(x > y) [Link]("x now greater than y");


}
}
Output:
x is less than y
x now equal to y
x now greater than y

2) The for Loop


One of the most versatile loop statement is the for loop. Loop statements are used to
execute the same set of instructions until the termination condition is met.
The simplest form of the for loop is: for(initialization; condition; iteration) statement;
The initialization portions 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.

Dept. of CSE, VVCE, Mysuru. Page 6


Basics of JAVA programming [BPLCK205C]

Example: // Demonstrate the for loop. Call this file "[Link]".

class ForTest
{
public static void main(String args[])
{
int x;
for(x = 0; x<10; x = x+1)
[Link]("This is x: " + x);
}
}
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

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.
Example:
if(x < y)
{ // begin a block
x = y;
y = 0;
} // end of block
Here, if x is less than y, then both statements inside the block will be executed. Thus, the
two statements inside the block form a logical unit, and one statement cannot execute
without the other also executing. The key point here is that whenever you need to logically
link two or more statements, you do so by creating a block.

Dept. of CSE, VVCE, Mysuru. Page 7


Basics of JAVA programming [BPLCK205C]

Lexical Issues

Java programs are a collection of whitespace, identifiers, literals, comments, operators,


separators, and keywords. These are the atomic elements of Java.
Whitespace
Java is a free-form language. This means that you do not need to follow any special
indentation rules. For instance, the Example program could have been written all on one
line or in any other strange way you felt like typing it, as long as there was at least one
whitespace character between each token that was not already delineated by an operator
or separator. In Java, whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may
be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters. They must not begin with a number, lest they be
confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a different
identifier than Value. Examples of valid identifiers are: AvgTemp, count, a4, $test,
this_is_ok. Examples of Invalid identifiers are: 2count, high-temp, Not/ok.
Literals
A constant value in Java is created by using a literal representation of it. For Example: 100,
98.66, ‘x’, “This is a test”. Left to right, the first literal specifies an integer, the next is a
floating-point value, the third is a character constant, and the last is a string. A literal can be
used anywhere a value of its type is allowed.
Comments
There are three types of comments defined by Java. single-line, multiline and the third type
is called a documentation comment. Single-line comment is two forward slash ( // ).
Multiline comment begins with /* and ends with */. The documentation comment begins
with a /** and ends with a */, this type of comment is used to produce an HTML file that
documents your program.
Separators
In Java, there are a few characters that are used as separators. The most commonly used
Separator in Java is the semicolon. As you have seen, it is used to terminate statements.
The separators are shown in the following table:

Dept. of CSE, VVCE, Mysuru. Page 8


Basics of JAVA programming [BPLCK205C]

The Java Keywords


There are 50 keywords currently defined in the Java language as shown in the below table.
These keywords, 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 keywords const and goto are reserved but not used. In the early days of Java, several
other keywords were reserved for possible future use. However, the current specification
for Java only defines the keywords as shown in the table. 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.

Dept. of CSE, VVCE, Mysuru. Page 9


Basics of JAVA programming [BPLCK205C]

DATA TYPES
Java Is a Strongly Typed Language: It is important to state at the outset that Java is a
strongly typed language. Indeed, part of Java’s safety and robustness comes from this fact.
Every variable has a type, every expression has a type, and every type is strictly defined. All
assignments, whether explicit or via parameter passing in method calls, are checked for type
compatibility.

In java, data types are classified into two categories


1. Primitive Data type – Example: int, long, double, char
2. Non-Primitive Data type – Example: String, Array

The Primitive Types

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types. These can be
put in four groups:
 Integers: This group includes byte, short, int, and long, which are for whole-valued
signed numbers.
 Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
 Characters: This group includes char, which represents symbols in a character set,
like letters and numbers.
 Boolean: This group includes boolean, which is a special type for representing
true/false values.

Integers
The width and ranges of these integer types vary widely, as shown in the table

Dept. of CSE, VVCE, Mysuru. Page 10


Basics of JAVA programming [BPLCK205C]

1. byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from –
128 to 127. Bytes are useful for working with stream or data from a network or file. They
are also useful for working with raw binary data. A byte variable is declared with the
keyword “byte”.
Example: byte b, c;
2. short: Short is a signed 16-bit type. It has a range from –32767 to 32767. This data type
is most rarely used specially used in 16 bit computers. Short variables are declared using
the keyword short.
Example: short a, b;
3. int: The most commonly used Integer type is int. It is signed 32 bit type has a range from
–2147483648 to 2147483648.
Example: int a, b, c;
4. long: Long is a 64 bit type and useful in all those occasions where Int is not enough. The
range of long is (–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) very large.
Example: long a, b;
/* Programming Example for integer to computes the number of miles that light will travel
in a specified number of days */

class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days = 1000;
seconds = days * 24 * 60 * 60;
distance = lightspeed * seconds;
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
}
}
Output: In 1000 days light will travel about 16070400000000 miles.

Dept. of CSE, VVCE, Mysuru. Page 11


Basics of JAVA programming [BPLCK205C]

Floating-point numbers
The width and ranges of float and double is as shown in the table

1. float: The float type specifies a single precision value that uses 32-bit storage. Float
keyword is used to declare a floating point variable.
Example: float a, b;
2. double: Double DataTips is declared with double keyword and uses 64-bit value.
Example: double r, a;
// Programming Example for float and double to compute the area of a circle.

class Area
{
public static void main(String args[])
{
double pi, a; float r = 10.8f;
pi = 3.1416;
a = pi * r * r;
[Link]("Area of circle is " + a);
}
}
Output: Area of circle is 366.4362369429933

Characters
The Java data type to store characters is char. char data type of Java uses Unicode to
represent characters. Unicode defines a fully international character set that can have all
the characters of human language. Java char is 16-bit type (2 byte). The range is 0 to 65536.
Example: char d, p;
// programming Example to demonstrates char variables

class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X

Dept. of CSE, VVCE, Mysuru. Page 12


Basics of JAVA programming [BPLCK205C]

ch2 = 'Y';
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}
}
Output: ch1 and ch2: X Y

// char variables behave like integers.

class CharDemo2
{
public static void main(String args[])
{
char ch1;
ch1 = 'X';
[Link]("ch1 contains " + ch1);
ch1++; // increment ch1
[Link]("ch1 is now " + ch1);
}
}
Output: ch1 contains X
ch1 is now Y

Booleans

Java has a simple type called boolean for logical values. It can have only one of two possible
values. They are true or false. This is the type returned by all relational operators, as in the
case of a < b. boolean is also the type required by the conditional expressions that govern
the control statements such as if and for.
Example: boolean b;
// Programming example to demonstrate boolean values.

class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
if(b) [Link]("This is executed.");
b = false;

Dept. of CSE, VVCE, Mysuru. Page 13


Basics of JAVA programming [BPLCK205C]

if(b) [Link]("This is not executed.");


[Link]("10 > 9 is " + (10 > 9));
}
}
Output: b is false
b is true
This is executed.
10 > 9 is true

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
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. The identifier is
the name of the variable. You can initialize the variable by specifying an equal sign and a
value. To declare more than one variable of the specified type, use a comma separated list.
Example: int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, j, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
// Programming example to demonstrate dynamic initialization.

class DynInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
double c = (a+b); // c is dynamically initialized
[Link]("Sum is " + c);
}
}
Output: Sum is 7.0

Dept. of CSE, VVCE, Mysuru. Page 14


Basics of JAVA programming [BPLCK205C]

The Scope and Lifetime of Variables


Java allows variables to be declared within any block. a block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start
a new block, you are creating a new scope. A scope determines what objects are visible to
other parts of your program. It also determines the lifetime of those objects. In Java, the
two major scopes are those defined by a class and those defined by a method. 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.
// Programming Example to 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.
[Link]("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
[Link]("x is " + x);
}
}
Output: x and y: 10 20
x is 40

Dept. of CSE, VVCE, Mysuru. Page 15


Basics of JAVA programming [BPLCK205C]

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. If a variable declaration includes an initializer,
then that variable will be reinitialized each time the block in which it is declared is entered.
//Programming Example to demonstrate lifetime of a variable.
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
[Link]("y is: " + y); // this always prints -1
y = 100;
[Link]("y is now: " + y);
}
}
}
Output: y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Although blocks can be nested, you cannot declare a variable to have the same name as one
in an outer scope.

//Programming Example to demonstrate variables having same name

class ScopeErr
{
public static void main(String args[])
{
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

Dept. of CSE, VVCE, Mysuru. Page 16


Basics of JAVA programming [BPLCK205C]

Type Conversion and Casting

It is often necessary to store a value of one type into the variable of another type. In these
situations the value that to be stored should be casted to destination type. Assigning a value
of one type to a variable of another type is known as Type Casting.
Type casting can be done in two ways.
1. Widening Casting (Implicit)

Automatic Type Conversion/casting take place when.


1. The two types are compatible
2. The target type is larger than the source type
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows:
3. All byte, short, and char values are promoted to int, as just described.
4. If one operand is a long, the whole expression is promoted to long.
5. If one operand is a float, the entire expression is promoted to float.
6. If any of the operands is double, the result is double.
// Programming Example to demonstrate promotion
class Promote
{
public static void main(String args[])
{
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
[Link]("result = " + result);
}
}
Output: result = 626.7784146484375

Dept. of CSE, VVCE, Mysuru. Page 17


Basics of JAVA programming [BPLCK205C]

2. Narrowing Casting (Explicitly done)

To create a conversion between two incompatible types, you must use a cast. A cast is
simply an explicit type conversion.
General form of cast is: (target-type) value. Here, target-type specifies the desired type to
convert the specified value to.
// Programming Example to demonstrate casts.
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;

[Link]("\nConversion of int to byte.");


b = (byte) i;
[Link]("i and b " + i + " " + b);

[Link]("\nConversion of double to int.");


i = (int) d;
[Link]("d and i " + d + " " + i);

[Link]("\nConversion of double to byte.");


b = (byte) d;
[Link]("d and b " + d + " " + b);
}
}
Output: Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

Dept. of CSE, VVCE, Mysuru. Page 18


Basics of JAVA programming [BPLCK205C]

Automatic Type Promotion in Expressions

In an expression, the precision required of an intermediate value will sometimes exceed the
range of either operand.
For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte, short, or
char operand to int when evaluating an expression. This means that the subexpression a * b
is performed using integers—not bytes. Thus, 2,000, the result of the intermediate
expression, 50 * 40, is legal even though a and b are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable.
However, because the operands were automatically promoted to int when the expression
was evaluated, the result has also been promoted to int. Thus, the result of the expression is
now of type int, which cannot be assigned to a byte without the use of a cast. This is true
even if, as in this particular case, the value being assigned would still fit in the target type. In
cases where you understand the consequences of overflow, you should use an explicit cast,
such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows:
First, all byte, short, and char values are promoted to int, as just described. Then, if one
operand is a long, the whole expression is promoted to long. If one operand is a float, the
entire expression is promoted to float. If any of the operands is double, the result is double.

Dept. of CSE, VVCE, Mysuru. Page 19


Basics of JAVA programming [BPLCK205C]

ARRAYS
An array is a group of like-typed variables that are referred to by a common name. It is
often more useful to think of an array as a collection of variables of the same type. Arrays of
any type can be created and may have one or more dimensions. A specific element in an
array is accessed by its index. Arrays offer a convenient means of grouping related
information.

Declaring Array Variables


To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring an
array variable:
dataType[] arrayRefVar; or dataType arrayRefVar[];

Example: int[] myList; or int myList[];

Creating Arrays
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];

The above statement does two things:


1. It creates an array using new dataType[arraySize];
2. It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:


dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to [Link]-1.

Dept. of CSE, VVCE, Mysuru. Page 20


Basics of JAVA programming [BPLCK205C]

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 and allocation of memory respectively is
type var-name[ ]; Example: int month_days[];
array-var = new type[size]; Example: month_days = new int[12];
Obtaining an array is a two-step process. First, you must declare a variable of the desired
array type. Second, you must allocate the memory that will hold the array, using new, and
assign it to the array variable. Thus, in Java all arrays are dynamically allocated.

// Programming Example to demonstrate a one-dimensional array.


class Array
{
public static void main(String args[])
{
String week_days[];
week_days = new String[7];

week_days[0] = "Sunday";
week_days[1] = "Monday";
week_days[2] = "Tuesday";
week_days[3] = "Wednesday";
week_days[4] = "Thursday";
week_days[5] = "Friday";
week_days[6] = "Saturday";
[Link]("Third day is " + week_days[2]);
}
}
Output: Third day is Tuesday.
It is possible to combine the declaration of the array variable with the allocation of the array
itself, as shown here:
String week_days[] = new String[7];
Arrays can be initialized when they are declared. 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, to
store the number of days in each month, the following code creates an initialized array of
integers:

Dept. of CSE, VVCE, Mysuru. Page 21


Basics of JAVA programming [BPLCK205C]

// An improved version of the previous program.


class AutoArray
{
public static void main(String args[])
{
String week_days[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
[Link]("Third day is " + week_days[2]);}
}
Output: Third day is Tue.

Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. The length of each array is
under your control (it can be equal or unequal). To declare a multidimensional array
variable, specify each additional index using another set of square brackets.
Two-dimensional array: int twoD[][] = new int[][];

//Programming Example to 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;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}

Dept. of CSE, VVCE, Mysuru. Page 22


Basics of JAVA programming [BPLCK205C]

Output: 01234
56789
10 11 12 13 14
15 16 17 18 19

three-dimensional array: int threeD[][][] = new int[][][];


//Programming Example to demonstrate a three-dimensional array.
class ThreeDMatrix
{
public static void main(String args[])
{
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
for(k=0; k<5; k++)
[Link](threeD[i][j][k] + " ");
[Link]();
}
[Link]();
}
}
}
Output: 00000
00000
00000
00000

Dept. of CSE, VVCE, Mysuru. Page 23


Basics of JAVA programming [BPLCK205C]

00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the
same time. For example,
int[] nums, nums2, nums3; // create three arrays
creates three array variables of type int. It is the same as writing
int nums[], nums2[], nums3[]; // create three arrays

Dept. of CSE, VVCE, Mysuru. Page 24

You might also like