0% found this document useful (0 votes)
0 views35 pages

UnitII-Java Notes (New Syllabus)

The document provides detailed notes on programming with Java, covering key topics such as constants, variables, data types, operators, decision making, and arrays. It explains the definitions and rules for constants and variables, the different data types available in Java, and the various operators used for manipulation. Additionally, it discusses expressions, their evaluation, and the precedence of arithmetic operators in Java programming.

Uploaded by

jananippriya18
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)
0 views35 pages

UnitII-Java Notes (New Syllabus)

The document provides detailed notes on programming with Java, covering key topics such as constants, variables, data types, operators, decision making, and arrays. It explains the definitions and rules for constants and variables, the different data types available in Java, and the various operators used for manipulation. Additionally, it discusses expressions, their evaluation, and the precedence of arithmetic operators in Java programming.

Uploaded by

jananippriya18
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
You are on page 1/ 35

PROGRAMMING WITH JAVA

UNIT II NOTES

1. ELEMENTS
1.1) Constants
1.2) Variables
1.3) Scope of Variables
1.4) Data types
1.5) Symbolic Constants
1.6) Type Casting
2. OPERATORS
2.1) Operators
2.2) Expressions
2.3) Evaluation of Expressions
3. DECISION MAKING & BRANCHING
3.1) Branching or Selection or conditional statement
4. DECISION MAKING & LOOPING
4.1) Iterative or looping statement
4.2) Jumps in loops
4.3) Difference between while & do-while loop
4.4) Additional features of for loop
5. ARRAYS
5.1) Arrays
5.1.1) One Dimensional Array
5.1.2) Multi Dimensional Array
5.2) Vectors
5.3) Array List in Java
5.4) Advantages of Array List over Array
5.5) Wrapper classes
1
JAVA NOTES UNIT - II

1. ELEMENTS
1.1) Constants:
Constant means fixed value. When constant values are used in the program we cannot
change the value during execution.
Types of constants:
1) Integer Constants.
2) Real Constants.
3) Single Character Constants.
4) String Constants.
5) Backslash Character Constants.
1) Integer Constants:
Integer Constants refers to a Sequence of digits which includes only negative or positive
values .
 An integer constant must have at least one digit.
 It must not have a decimal value.
 It could be either positive or negative.
 If no sign is specified then it should be treated as positive.
 Eg. 123,-34

2) Real Constants:
 A real constant must have at least one digit.
 It must have a decimal value.
 It could be either positive or negative.
 If no sign is specified then it should be treated as positive.
 Eg. 234.89
In The Exponential Form of Representation, the Real Constant is Represented in the two
Parts. The part before appearing e is called mantissa whereas the part following e is called
Exponent.
 In Real Constant The Mantissa and Exponent Part should be Separated by letter e.
 The Mantissa Part have may have either positive or negative Sign.
 Default Sign is Positive.
3) Single Character Constants:
A character is a single alphabet or a single digit or a single symbol that is enclosed within
2
JAVA NOTES UNIT - II

single inverted commas.


Eg. 'S' ,'1'
4) String Constants:
String is a Sequence of characters enclosed between double Quotes.
Eg. "Hello" , "1234"

5) Backslash Character Constants:


Java supports Backslash Constants that are used in output methods. These are also called as
escape Sequence or backslash character Constants
Eg.
\n new line Character
\t For Tab ( Five Spaces in one Time )
\b Back Space etc.

1.2) Variables:
A variable is used for storing a value and may take different values during the execution of
the program. It is usually defined by the user. It uses letters, underscores, or a dollar sign as
the first character.

Rules to declare variables are:


o The first letter of an variable must be a letter, underscore or a dollar sign.
o It cannot start with digits but may contain digits.
o The white space cannot be included in the variable.
o Variables are case sensitive.
o Variable names can be of any length.

Some valid variable names are:


PRICE
radius
a1
$circumference

1.3) Scope of Variables:


The scope of a variable defines the section of the code in which the variable is visible.
As a general rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it is destroyed.
Instance Variables:
The Variables those are declared in a class are known as instance variables When
object of Class is Created then instance Variables are Created So they always Related With
Class Object .Only one memory location is created for one instance variable.
3
JAVA NOTES UNIT - II

Argument variables:
These are the variables that are defined in the header oaf constructor or a method. The
scope of these variables is the method or constructor in which they are defined. The lifetime
is limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.
Local Variables:
The Variables those are declared in Method of class are known as Local Variables
They are Called Local because they are not used from outside the method The Accessibility
of Variables Through out the program is called is Known as the Scope of Variables.

Class Variables:
The Variables that are declared inside a class are called as Class variables or also
called as data members of the class .They are friendly by default means they are accessible to
main Method or any other Class Which inherits.

1.4) Data Types in Java:


Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:

Class
Interface

1)Primitive data types:


1.1. 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.
4
JAVA NOTES UNIT - II

1.2 Floating Point types:

Floating-point numbers, also known as real numbers, are used when evaluating expressions
that require fractional precision. For example, calculations such as square root, sine and
cosine, result in a value whose precision requires a floating-point type. Java supports two
types of floating point data types namely float and double. Float type data specifies a single
precision value. Double type data specifies a double precision value.

1.3 Characters:
Char is the data type used to store characters in java. The size of character type data is 2
bytes. Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages.

1.4 Boolean:
Boolean type is used when we want to test a particular condition during the execution of the
program. There are only two values that a Boolean type can take; true or false. Boolean type
is denoted by the keyword boolean and uses only one bit of storage

2)Non Primitive data types:


2.1 Strings:
String is a sequence of characters. But in Java, a string is an object that represents a sequence
of characters. The java.lang.String class is used to create a string object.

2.2 Arrays:
Arrays in Java are homogeneous data structures implemented in Java as objects. Arrays store
one or more values of a specific data type and provide indexed access to store the same. A
specific element in an array is accessed by its index.

2.3 Classes:
A class in Java is a blueprint which includes all your data. A class contains fields(variables)
and methods to describe the behaviour of an object.

2.4 Interface:
Like a class, an interface can have methods and variables, but the methods declared in
interface are by default abstract (only method signature, no body).
5
JAVA NOTES UNIT - II

1.5) Symbolic constants:


Symbolic constants in Java are named constants. We use the final keyword so they cannot be
reassigned a new value after being declared as final. They are symbolic because they are
named.

Syntax :
final type symbolic_name= value;

Eg final float PI =3.14159;


final int STRENGTH =100;

Rules :

 Symbolic names take the same form as variable names, but they are written in
capitals letters.

 After declaration of symbolic constants they shouldn’t be assigned any other


value with in the program by using an assignment statement.
For eg:- STRENGTH = 200 is illegal

 They can’t be declared inside a method. They should be used only as class data
members in the beginning of the class.

1.6) Type Casting:


We often encounter situations where there is a need to store a value of one data type into a
variable of another data type. In such situations, we must cast the value to be stored by
preceding it with the type name in parentheses.
The process of converting one data type to another is called casting.
Syntax:

type variable1 = (type) variable2;

Examples:
int m=5;
byte n= (byte)m;
long count=(long)m;

Four integer types can be cast to any other type except Boolean. Casting into a smaller type
may result in a loss of data.
6
JAVA NOTES UNIT - II

Type casts those results in no loss of information:

From To
byte Short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int Long, float, double
long float, double
float double

Automatic Conversion:
It is possible to assign a value of one data type to a variable of a different data type without a
cast. Java does the conversion of the assigned value automatically. This is known as
automatic type conversion. Automatic type conversion is possible only if the destination type
has enough memory space to store the source value. For example, int is large enough to hold
a byte value.
Therefore,
byte b = 75;
int a = b;
are valid statements.

The process of assigning a smaller data type to a larger data type is known as widening or
promotion and that of assigning a larger data type to a smaller data type is known as
narrowing. Note that narrowing may result in loss of information

Program:
class typewrap
{
public static void main(String args[])
{
char c = ‘x’;
byte b = 50;
short s = 1996;
int i = 123456789;
short s1= (short) b;
short s2= (short) i; // Produces incorrect result
System.out.println(“ (short) b = ” + s1);
System.out.println(“ (short) i = ” + s2);
}
}
Output of Program:
(short)b = 50
(short)i = -13035
7
JAVA NOTES UNIT - II

2. OpEraTOrS
2.1) Operators:
Operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.

Types of operators:
i. Arithmetic operators.
ii. Relational operators.
iii. Logical operators.
iv. Assignment operators.
v. Increment and decrement operators.
vi. Conditional operators.
vii. Bitwise operators.
viii. Special operators.

i) Arithmetic operators:
An operator that performs an arithmetic operation is called arithmetic operator. Arithmetic
operation requires two or more operands. Therefore these operators are called binary
operators.

ii) Relational operators:


The relational operators are used to test the relation between two values. All relational
operators are binary operators and therefore require two operands. A relational expression
returns zero when the relation is false and a nonzero when it is true.

iii) Logical operators:


The logical operators && and || are used to evaluate two expressions, to obtain a single
relational result.
8
JAVA NOTES UNIT - II

Operator Meaning Example Answer

&& Logical AND (5==5) && (7>3) True

|| Logical OR (4<2) || (3>5) False

! Logical NOT !(2==5) True

iv) Assignment Operator:


The assignment expression evaluates the operand on the right side of the operator (=) and
places its value in the variable on the left.
Eg: a=5; a=a+1; a=b+1;
Eg: a+=1; it is equivalent to a=a+1;

v) Increment (++) And Decrement (--) Operators:


The operator ++ adds one to its operand where as the operator - - subtracts one from its
operand. These operators are unary operators.

Operator Meaning Example Answer

++a Pre-increment a=4; b=++a a=5; b=5

a++ Post-increment a=5; b=a++ a=6; b=5

--a Pre-decrement X=4; y=--x X=3; y=3

a-- Post-decrement x=4; y=x-- x=3; y=4

vi) Conditional operator or ternary operator:


Syntax:

If expression1 is true then expression2 is executed, otherwise expression3 is executed.


Eg. 10>5?10:5;
Output: 10

vii) Bitwise Operators:


Bitwise operators are used to modify the bits of the binary pattern of the variables.

Operator Meaning Example Answer

& Bitwise AND 1011 & 1010 1010


9
JAVA NOTES UNIT - II

| Bitwise OR 1011 | 1010 1011

<< Left shift 0010<<1 times 0100

>> Right shift 0010>>1 times 0001

~ One's complement ~1001 0110

viii) Special Operators:


Java supports some special operators such as instanceof operator and member
selection operator (.).

Instanceof Operator:
The instanceof is an object reference operator and returns true if the object on the left-hand
side is an instance of the class given on the right-hand side. This operator allows us to
determine whether the object belongs to a particular class or not.
Example:
person instanceof student
Returns true if the object person belongs to the class student; otherwise it is false.

Dot Operator:
The dot operator (.) is used to access the instance variables and methods of class objects.
Example:
person.age
person.salary()

2.2) Expressions:
An expression is a combination of operators, constants and variables. An expression is
a sequence of operands and operators that produces a value.

Types of Expressions:
i) Constant expressions:
Constant expressions consists of only constant values. A constant value is one that doesn’t
change.
Examples:
10 + 5 / 6.0
'x’
10
JAVA NOTES UNIT - II

ii) Integral expressions:


Integral expressions are those which produce integer results after implementing all the
automatic and explicit type conversions.
Examples:
x*y
x + int( 5.0)
where x and y are integer variables.

iii) Floating expressions:


Float expressions are those which produce floating point results after implementing all the
automatic and explicit type conversions.
Examples:
x+y
10.75 * 2.3
where x and y are floating point variables.

iv) Relational expressions:


Relational expressions will give results of type boolean, which takes a value true or false.
When arithmetic expressions are used on either side of a relational operator, they will be
evaluated first and then the results compared. Relational expressions are also known as
Boolean expressions.
Examples:
x <= y
x+y>2

v) Logical expressions:
Logical Expressions combine two or more relational expressions and produces boolean type
results.
Examples:
x > y && x == 10
x == 10 || y == 5

vi) Bitwise expressions:


Bitwise expressions are used to manipulate data at bit level. They are basically used for
testing or shifting bits.
Examples:
x << 3
//shifts three bit position to left
y >> 1
//shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.

2.3) Evaluation of Expressions:

Expressions are evaluated using an assignment statement of the form


variable = expressions;
11
JAVA NOTES UNIT - II

variable is any valid Java variable name. When the statement is encountered, the expression
is evaluated first and the result then replaces the previous value of the variable on the left-
hand side. All variables used in the expression must be assigned value before evaluation is
attempted.

Examples of evaluation statements are


x = a*b–c;
y = b/c*a;
z = a–b/c+d;

When these statements are used in program, the variables a,b,c and d must be defined before
they are used in the expressions.

2.3.1) Precedence of Arithmetic Operators:

An arithmetic expression without any parentheses will be evaluated from left to right
using the rules of precedence of operators. There are two distinct priority levels of arithmetic
operators in Java:
The basic evaluation procedure includes two left-to-right passed through the
expression. During the first pass, the high priority operators (if any) are applied as they are
encountered.

High priority * / %
Low priority + –

During the second pass, the low priority operators (if any) are applied as they are
encountered. Consider the following evaluation statement:
x = a–b/3 + c*2–1

When a = 9, b = 12, and c = 3, the statement becomes


x = 9–12/3+3*2–1
and is evaluated as follows:
First pass
Step1: x = 9–4+3*2–1 (12/3 evaluated)
Step2: x = 9–4+6–1 (3*2 evaluated)

Second pass
Step3: x = 5+6–1 (9–4 evaluated)
Step4: x = 11–1 (5+6 evaluated)
Step5: x = 10 (11–1 evaluated)

However, the order of evaluation can be changed by introducing parentheses into an


expression.
Consider the same expression with parentheses as shown below:
9–12/(3+3)*(2–1)

Whenever the parentheses are used, the expressions within parentheses assume highest
12
JAVA NOTES UNIT - II

priority. If two or more sets of parentheses appear one after another as shown above, the
expression contained in the left-most set is evaluated first and the right-most in the last.

Given below are the new steps.


First pass
Step1: 9–12/6*(2–1)
Step2: 9–12/6*1

Second pass
Step3: 9–2*1
Step4: 9–2

Third pass
Step5: 7

This time, the procedure consists of three left-to-right passes. However, the number of
evaluation steps remain the same as 5

3. DECISION MaKING aND BraNCHING

3.1) Branching or Selection or conditional statement:


i. Simple if
ii. if else
iii. nested if else
iv. if else ladder
v. Switch

i) if statement:
Syntax:
if (expression)
{
Statements;
}

Explanation:
If the condition is true, statement is executed. If it is false, statement is not executed and the
program continues after this conditional structure.

Example:
if (a<b)
System.out.println(”a is less than b”);
13
JAVA NOTES UNIT - II

ii) if-else statement:


Syntax:
if (test expression)
{
statement block1;
}
else
{
statement block2;
}

Explanation:
If test expression is true then block1 statements are executed otherwise block2 statements are
executed.
Example:
if (a>b)
System.out.println(“A is greater than B”);
else
System.out.println (“B is greater than A”);

iii) Nesting of if-else statements:


Syntax:
if (test expression-1)
{
if (test expression-2)
//statements
else
//statements
}
else
{
if (test expression-3)
//statements
else
//statements
}

Explanation:
If the test expression-1 condition is true, then its corresponding test expression-2 statements
are executed, otherwise it is skipped and next else test expression-3 statements are evaluated.

Example:
if (a>b)
{
if(a>c)
System.out.println("A is largest among three numbers");
14
JAVA NOTES UNIT - II

else
System.out.println("C is largest among three numbers");
}
else
{
if(b>c)
System.out.println("B ia largest among three numbers");
else
System.out.println("C ia largest among three numbers");
}

iv) if else ladder:


Syntax:

if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement 3;
else
default statement.
statement-x;

Explanation:
The condition is evaluated from top to bottom. If a condition is true then the statement
associated with it is executed. When all the conditions become false then final else part
containing default statements will be executed.

Example:
if (percentage>=80)
System.out.println(”Distinction”);
else if (percentage>=60)
System.out.println(”First class”);
else if (percentage>=50)
System.out.println(”Second class”);
else if (percentage>=40)
System.out.println(”Third class”);
else
System.out.println(”Fail”);
}
15
JAVA NOTES UNIT - II

v) Switch statement:
Syntax:
switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
--------
--------
default:
default block;
}

Explanation:
Here, expression is the condition that is being evaluated. If the case 1 condition is true,
block-1 statements are executed. otherwise case 2 condition is checked and so on....If none
of case expressions is true then the statements of default case body is executed.

Example:
switch(power)
{
case 0:
System.out.println(”Power is off”);
break;
case 1:
System.out.println(”Power is on”);
break;
default:
System.out.println(”Give the power value as either 0 or 1”);
}

4. DECISION MaKING aND LOOpING

4.1) Iterative or looping statement:


Looping statement is used to repeat a set of instructions until certain condition is fulfilled.
i. while loop statement
ii. do while loop statement
iii. for loop statement
16
JAVA NOTES UNIT - II

i) while loop statement:


Syntax:
while(test condition)
{
body of the loop
}

Explanation:
It is an entry controlled loop. The condition is evaluated and if it is true then body of loop is
executed. After execution of body the condition is once again evaluated and if is true the
body is executed once again. This goes on until the test condition becomes false.

Example:
import java.io.*;
class num
{
public static void main(String args[]) throws IOException
{
int n;
DataInputStream d = new DataInputStream(System.in);
System.out.println("Enter the number");
n=Integer.parseInt(d.readLine());
while (n>0)
{
System.out.println(n);
n--;
}
}
}

ii) do while loop statement:


Syntax:
do
{
body
}
while(test condition);

Explanation:
The do…while is an exit controlled loop and its body is executed at least once. It evaluates
its test – expression at the bottom of the loop after executing its loop-body statement.

Example:
import java.io.*;
17
JAVA NOTES UNIT - II

class num
{
public static void main(String args[]) throws IOException
{
int n;
DataInputStream d = new DataInputStream(System.in);
do
{
System.out.println("Enter any number (type 0 to exit)");
n=Integer.parseInt(d.readLine());
System.out.println( "You entered"+n);
}
while (n != 0);
}
}

iii) for loop statement:


Syntax:
for (initialization; condition; increment/decrement)
{
statements;
}

Explanation:
 Initialization expression is used to initialize the variables
 If the condition is true, then the program control flow goes inside the loop and
executes the block of statements associated with it .If test expression is false, loop
terminates.
 Increment/decrement expression consists of increment or decrement operator. This
process continues until the test condition satisfies.

Example:
import java.io.*;
class num
{
public static void main(String args[]) throws IOException
{
for (int n=10; n>0; n--)
{
System.out.println( n) ;
}
}
}
18
JAVA NOTES UNIT - II

4.2) Jumps in Loops:

Statements that transfers control from one part of the program to another part of the program
unconditionally.
i. break
ii. continue
iii. Labeled Loops

i) break statement:
The break statement is used to terminate the execution of the loop program. It terminates the
loop in which it is written and transfers the control to the immediate next statement outside
the loop. The break statement is normally used in the switch conditional statement.

Example:
for (n=5; n>0; n--)
{
System.out.print( n +", ");
if (n==3)
{
System.out.println("countdown aborted!");
break;
}
}
Output: 5, 4, 3, countdown aborted!
19
JAVA NOTES UNIT - II

ii) Continue:
It is used to continue the iteration of the loop statement by skipping the statements after the
continue statement. It causes the control to go directly to the test condition and then to
continue the loop.

Example:
for (int n=5; n>0; n--)
{
if (n==3)
continue;
System.out.print( n +", ");
}
System.out.println("FIRE!");
Output: 5, 4, 2, 1, FIRE!

iii) Labeled Loops


The labeled loops is used to transfer control to some other parts of the program. It is
used to alter the execution sequence of the program.
20
JAVA NOTES UNIT - II

Example:
//A Java program to demonstrate the use of labeled for loop
import java.io.*;
class labelloop
{
public static void main(String args[])
{
outer:
for(int i=1;i<=3;i++)
{
inner:
for(int j=1;j<=3;j++)
{
if(i==2 && j==2)
{
break outer;
}
System.out.println(i+" "+j);
}
}
}
}

Output:
1 1
1 2
1 3
2 1
21
JAVA NOTES UNIT - II

4.4) Difference Between While and do-while loops:

while Do-while
It is a looping construct that will execute It is a looping construct that will execute
only if the test condition is true. atleast once even if the test condition is
false.
It is an entry-controlled loop It is an exit-controlled loop.
It is generally used for implementing It is used for implementing menu-based
common looping solutions. programs.

4.5) Additional Features Of For Loop

1) More than one variable can be initialized at a time in the for statement
Eg. for(n=1, m=5; n<=m; n++,m--)

2) One or more sections in the for loop can be omitted


Eg. int m=1;
for( ; m!=10; )
m++;

3) The compiler will not give an error message if we place a semicolon at the
end of the for statement. The semicolon will be considered as an empty
statement and the program may produce some nonsense.
Eg. for(i=1;i<=5;i++);

4) Nesting of for loops


Eg. import java.io.*;
class LabeledForExample
{
public static void main(String args[])
{
for(i=1;i<3;i++)
for(j=1;j<3;j++)
System.out.println(i+” “+j);
}
}

Output
22
JAVA NOTES UNIT - II

1 1
1 2
2 1
2 2

5) for each Loops


JDK 1.5 introduced a new for loop known as for each loop or enhanced for loop,
which enables you to traverse the complete array sequentially without using an index
variable.

Example
The following code displays all the elements in the array myList −

class TestArray {

public static void main(String args[])


{
double myList[] = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList)
{
System.out.println(element);
}
}
}

Output
1.9
2.9
3.4
3.5

5. arraYS
5.1) Arrays:

An array is a group of similar data typed variables that shares a common name. The
elements of the array are accessed by the array index. The array index should be a positive
integer value.
23
JAVA NOTES UNIT - II

Types:
1.One dimensional array
2. Two dimensional array or Multi dimensional array

5.1.1) One dimensional array:

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[] arrayname;
or
dataType arrayname[];

Creating Arrays
You can create an array by using the new operator with the following syntax:

arrayname = new dataType[arraySize];

The above statement does two things:


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

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 arrayname[] = new dataType[arraySize];


Example:
int a[ ] = new int[10 ];
double n[ ] = new double[5];
String s[ ] = new String[7];

In the above example a is an integer array of size 10, n is a double type array of size 5 and s
is a String array of size 7.

Alternatively you can create arrays as follows:

dataType arrayname[] = {value0, value1, ..., valuek};

Example:
int a[ ] = { 10, 34,22,56,21};
In the above example the integer values are assigned as a[0]=10, a[1]=34, a[2]=22, a[3]=56
and a[4]=21.
String s[ ] = { “Anand”, “Bala”, “Jhon Samuel”, “Hayes”};
In the above example the String objects are assigned as s[0]=”Anand”; s[1]=”Bala”,
s[2]=”Jhon Samuel”, s[3]=”Hayes”
24
JAVA NOTES UNIT - II

Accessing Array Elements


The array elements are accessed through the index. Array indices start from 0 to
arrayname.length-1.

Example
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList:

double myList[] = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.

Example: Java program to sort the numbers in ascending order.


import java.io.*;
class asc
{
public static void main(String args[]) throws IOException
{
DataInputStream d = new DataInputStream(System.in);
int a[]=new int[20];
int i,j,temp,n;
System.out.println("Enter the total number of elements");
n=Integer.parseInt(d.readLine());
System.out.println("Enter the elements");
for(i=1;i<=n;i++)
a[i]= Integer.parseInt(d.readLine());
System.out.println("Sorted Numbers");
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
25
JAVA NOTES UNIT - II

System.out.println(a[i]);
}
}
}

Output:
Enter the total number of elements
5
Enter the elements
30
23
56
12
65
Sorted Numbers
12
23
30
56
65

5.1.2) Multi-Dimensional Arrays :


A multidimensional array is a list of array of arrays. It may be a two-dimensional array
or three-dimensional array. The example for two-dimensional array is a matrix. A two
dimensional array can be accessed by its row index and its column index.

Declaration:
type array-name[ ][ ] = new type[ rowsize][columnsize];

Example:
int m[ ][ ] = new int[3 ] [4];
double d[ ][ ] = new double[2] [3];
String name[ ][ ]= new String[3][20];

In the above example m is an integer type matrix of 3 rows and 4 columns, d is a double type
matrix of 2 rows and 3 columns and name is a String array of size 3 rows and 20 columns.

Input:
The matrix elements can be assigned directly along with the declaration. This is called
initialization of arrays. The values can also be assigned during execution by the user.

Example:
int a[ ][ ]= { {1,2,3},{4,5,6},{7,8,9}};
In the above example the integer values are assigned as a[0][0]=1, a[0][1]=2,
a[0][2]=3, a[1][2]=4 ….a[2][2]=9.
26
JAVA NOTES UNIT - II

Output:
The elements of the matrix can be printed in the matrix format array index and two loop
statements.

Example:
int a[ ][ ]= { {1,2,3},{4,5,6},{7,8,9}};
System.out.println(“ Matrix);
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
System.out.print(a[i][j]+” “]);
System.out.println(“ “);
}

Example: Java program to perform addition of two matrix.


import java.io.*;
class matrix
{
public static void main(String arg[]) throws IOException
{
DataInputStream d=new DataInputStream(System.in);
int row,col,i,j;
int a[][]=new int[5][5];
int b[][]=new int[5][5];
int c[][]=new int[5][5];
System.out.println("Enter the number of rows and columns");
row= Integer.parseInt(d.readLine());
col= Integer.parseInt(d.readLine());
System.out.println("Enter Matrix A elements");
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
a[i][j]=Integer.parseInt(d.readLine());
}
27
JAVA NOTES UNIT - II

}
System.out.println("Enter Matrix B elements");
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
b[i][j]=Integer.parseInt(d.readLine());
}
}
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("Addition of two matrix");
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println(" ");
}
}
}

Output:
Enter the number of rows and columns
2
2
Enter Matrix A elements
1
2
3
4
Enter Matrix B elements
2
3
4
5
Addition of two matrix
3 5
7 9
28
JAVA NOTES UNIT - II

5.2) Vectors:

A vector is an expansible array. A vector increases its capacity automatically to


ensure thatall the elements are stored. So, use a vector whenever you don’t know the
number of elements ahead of time. A vector is a standard class that resides in the
java.util package. The key difference between arrays and vectors in Java is that
vectors are dynamically-allocated.

Creation of Vectors:
Vector V = new Vector(); //declaring without size or
Vector V = new Vector(3); // declaring with size

Advantages:
 Vectors can be used to store objects.
 It can be used to store a list of objects that may vary in size.
 We can add and delete objects from the list, when required.

Disadvantages:
 It cannot directly store simple data type.
 Conversion of simple data type to objects is required. This is done by
using thewrapper classes.

Table : Vector Class and Methods:

Method Call Task Performed

addElement (item) Add the item specified to the list at the end

elementAt(n) Give the name of the nth object

size() Give the number of objects present

removeElement (item) Removes the specified item from the list

removeAllElements() Removes all the elements in the list

copyInto (array) Copies all items from list to array

insertElementAt (item, n) Inserts the item at n th position.

Program to illustrate vector class:


import java.io.*;
import java.util.*;
class vect
{
public static void main(String args[])
29
JAVA NOTES UNIT - II

{
Vector v = new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("Number Names",0);
System.out.println("Size="+v.size());
System.out.println("Element at"+v.elementAt(2));
}
}

Output:
Number Names
one
two
three
Size=4
Element at two

5.3) ArrayList in Java

An ArrayList class is a resizable array, which is present in the java.util package.


While built-in arrays have a fixed size, ArrayLists can change their size dynamically.
Elements can be added and removed from an ArrayList whenever there is a need, helping the
user with memory management.

The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed. Array lists are created with an
initial size. When this size is exceeded, the collection is automatically enlarged. When
objects are removed, the array may be shrunk.

Following is the list of the constructors provided by the ArrayList class.


Method Call Task Performed

add(value) appends value at end of list

add(index, value) inserts given value at given index

clear() removes all elements of the list


30
JAVA NOTES UNIT - II

indexOf(value) returns first index where given value is found in list (-1 if not
found)

get(index) returns the value at given index

remove(index) Removes the value at given index.

set(index, value) replaces value at given index with given value

size() returns the number of elements in list

toString() returns a string representation of the list


such as "[3, 42, -7, 15]"

Advantages:

 ArrayList is initialized by the size. However, the size is increased automatically if the
collection grows or shrinks if the objects are removed from the collection.
 Java ArrayList allows us to randomly access the list.
 ArrayList cannot be used for primitive types, like int, char, etc. We need a wrapper
class for such cases.
 ArrayList in Java is equivalent to vector in C++.

Program to illustrate ArrayList class:

import java.util.*;
class example
{
public static void main( String args[] )
{
ArrayList shapes = new ArrayList();
shapes.add("square");
shapes.add("triangle");
shapes.add("rectangle ");
shapes.add("circle");
System.out.println(shapes);
System.out.println(shapes.get(2));
shapes.remove(2);
System.out.println(shapes);
shapes.set(2,"polygon");
System.out.println(shapes);
System.out.println(shapes.size());
shapes.clear();
System.out.println(shapes);
}
}
31
JAVA NOTES UNIT - II

Output
[square, triangle, rectangle, circle]
rectangle
[square, triangle, circle]
[square, triangle, polygon]
3
[]

5.4) Advantages of Array List over Array:

Property Array ArrayList


Size Array is fixed in size. Once ArrayList size can be changed after
declared, its size can’t be declaration. For example when we add or
changed. remove element in arraylist, its size
increases or decreases accordingly.
Primitives Array can contain primitive ArrayList can contain objects only. When
data types as well as objects. we try to add a primitive type element in
arraylist then the element is first converted
into its corresponding wrapper class and
then added. This process of conversion is
called auto-boxing.
Performance Array provides better ArrayList performance is less and uses
performance and uses less more memory as compared to Array.
memory. ArrayList internally uses dynamic array for
storing elements. Each time an element is
added or removed, a new array is created.
Element Type Array can contain elements ArrayList can contain elements of
of same type. different types.
Iteration We can iterate through ArralyList provides various ways for
array using loops only. iteration like loops, Iterator and ListIterator
class.
Dimension Array can be single as well ArrayList is only single dimensional.
as multi-dimensional.
Storage Array elements are stored ArrayList elements are not stored at
at contiguous memory contiguous memory locations.
locations.

5.5) Wrapper Classes :

Vectors cannot handle primitive data types like int, float, long, char and double. Primitive
data types may be converted into object types by using the wrapper classes contained in the
java.lang package.

Need for Wrapper Class:


 Wrapper Class will convert primitive data types into objects.
 The classes in java.util package handles only objects and hence wrapper classes help in
32
JAVA NOTES UNIT - II

this case also.


 Data structures in the Collection framework such as ArrayList and Vector store only the
objects (reference types) and not the primitive types.
 The object is needed to support synchronization in multithreading.

Wrapper Classes for Converting Simple Types

Simple Type Wrapper Class


boolean Boolean
char Character
double Double
float Float
int Integer
long Long

Converting Primitive number to object number using Constructor methods:-

Constructor Calling Conversion Action


Integer iv =new Integer(i); Primitive integer to Integer Object
Float fv =new Float(f); Primitive float to Float Object
Double dv =new Double(d); Primitive double to Double Object
Long lv =new Long(l); Primitive long to Long Object

Converting object number to Primitive numbers using typeValue () method:-

Method Calling Conversion Action


int i=iv.intValue(); Object to primitive integer
float f=fv.floatValue(); Object to primitive Float
double d=dv.doubleValue(); Object to primitive Double
long l=lv.longValue(); Object to primitive Long

Converting Numbers to Strings using toString () method:-

Method Calling Conversion Action


str=Integer.toString(i); Primitive integer to string
str=Float.toString(f); Primitive Float to string
str=Double.toString(d); Primitive Double to string
str=Long.toString(l); Primitive Long to string
33
JAVA NOTES UNIT - II

Converting String objects to Numeric objects using the method valueOf ():-

Method Calling Conversion Action


iv=Integer.valueOf(str) Converts string to Integer object
fv=Float.valueOf(str) Converts string to Float object
dv=Double.valueOf(str) Converts string to Double object
lv=Long.valueOf(str) Converts string to Long object

Converting Numeric Strings to Primitive Number using Parsing method:-

Method Calling Conversion Action


int i=Integer.parseInt(str); Converting String to Primitive integer
long l=Long.parseLong(str); Converting String to Primitive long

Autoboxing:
The automatic conversion of primitive data type into its corresponding wrapper class
is known as autoboxing.

Example:

import java.util.ArrayList;
class Autoboxing
{
public static void main(String args[])
{
ArrayList<Integer> arr = new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects


arr.add(25);

// printing the values from object


System.out.println(arr.get(0));
}
}

Output:
25
Unboxing:
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing.
34
JAVA NOTES UNIT - II

Example:

import java.util.ArrayList;
class Unboxing
{
public static void main(String args[])
{
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(24);

// unboxing because get method returns an Integer object


int num = arr.get(0);

// printing the values from primitive data types


System.out.println(num);
}
}

Output:
24

You might also like