0% found this document useful (0 votes)
19 views25 pages

Ca 1

The document outlines key features of Java, including its compiled and interpreted nature, platform independence, object-oriented structure, robustness, security, and support for multithreading. It also discusses various types of operators in Java, such as arithmetic, relational, logical, and conditional operators, along with their usage. Additionally, it explains the Java Virtual Machine (JVM) and different types of if statements for decision-making in Java programming.

Uploaded by

avanti.ias
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)
19 views25 pages

Ca 1

The document outlines key features of Java, including its compiled and interpreted nature, platform independence, object-oriented structure, robustness, security, and support for multithreading. It also discusses various types of operators in Java, such as arithmetic, relational, logical, and conditional operators, along with their usage. Additionally, it explains the Java Virtual Machine (JVM) and different types of if statements for decision-making in Java programming.

Uploaded by

avanti.ias
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/ 25

Obje ct Orie nted Prog ramm ing

Usin g Java
Unit- 1 Impo rtant Que stion s
With Answ ers
SUBSCRIBE ~ Share
\\'hat an: the features of Java? [ANU 17; AdNU 16; AU 16; BRAU 18; KU 17, 16;
AU 18, 17; SVU 17; VSU 18; YVU 16)

Sun Micro systems officially describes java with the following anributcs.
I) Compiled iln<.Iinterpreted :Usunlly a computer language_is ei_thcr compiled or
interpreted. Ja\'a combines both tJ1ese approaches thus _makmg Java a two stage
s,·stem. First. ja\':l compiler translates source code into known as bytecode
i~structions. Bvtec,odes arc not machine instructions and therefore, in the second
stage. ja\'a inte~relcr generates machine code that can be directly executed by the
machine that is running the java program.
~) Platform-independent and portable : Java programs can be easily moved
from one computer system to another, anywhere and an)1ime. Changes and upgrad~
in operating systems. processors and system resources will not force any changes in
java programs.
Ja\'a ensures portability in two ways. First, java compiler generates bytecode
instructions that can be implemented on any machine. Secondly, the size of the
primitive datatypes are machine independent.
3) Object-oriented : Java is true object oriented language. All program code and
data reside with in objects and classes. Java comes with an extensive set of classes,
arranged in packages, that we can use in our programs by inheritence.
4) Robust and secure: Java is robust language. It provides much secure & rc!liable
code. It has strict compile time and runtime checking for data types. It has a garbage
collector to rectify memory management problems. It also has the concept of
exception handling.
5) Distributed : Java applications can open and access remote objects on internet.
Multiple programs can communicate from client system to the server system.
6) Fam iliar, simple and small : Java is a small and simple language. Because,
java does not use pointers, preprocessor header fi !es, goto statement and many
others. It also eliminated operator overloading and multiple inheritence.
Familiarity is another striking feature of Java, to make the language look familiar
to the existing programmers, it was modeled on C and C++ languages.
7) Multithreaded and interactive : Multithreaded means handling multiple tasks
simultaneously. Java supports multithreadcd programming.
This means that we need not wait for the application to finish one task before
beginning another. This feature greatly improves the interactive performance of
graphics applications.
8) High performance : Java performance is impressive for an interpreted language,
mainly due to the use of intem1ediate byte code. According to sun, java speed is
comparable to the native CIC++.
an d I.angc or all integer data types .
.
Table below show s the memo ry. size
Type Size Minimum v~aluc Maximum Value
(in by~s)
byte I - 128 127
short 2 -32,768 32,767
int 4 -2, 147, 483, 648 2,147, 483,647
long 8 . -9,223,372, 036, 854, 775,808 9,223 , 372.036.854, 775,80".'
We can make iniegers long by appending the letter Lor I at the end
of th"·
number.
Example : 123Lor 1231.
2) Floating point Type s: Floating point type to hold numbers co~ta
ining fra~ti?nal
parts such as 12.34 and - 1.34. There are two kinds of floating pomt st0
rage m Java
as shown in figure below.
--- --- ,
Floating Point

Double ·
The float type values are single-precision numbers while the double types
represent
double precision numbers. Table below gives the size and range of these
two types.
'I)'pe Size (in bytes) Mini mum Value Maxi mum Valu e
Float 4 3.4e - 038 3.4e + 038
Double 8 l.7e- 308 l.7e + 308
Floating point data types suppo11 a special value known as Not-a-Num
ber (NaN) is
used to represent the result of operations such as dividing zero by
zero, where an
actual number is not produced.
3) Char acter Type : Java provides a character data type called
char. The char
type assumes a size of 2 bytes but, basically, it can hold only a single
character.
4) Boolean Type : Boolean type is used when we want to test a partic
ular 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 boole
an and uses
only one bit of storage.
·
Explain th~ various 1ypcs of opcralors used in Java? (ANU 18; AdNU 17;
BRAU 18,17,16; KU 18,17,16; RU 17,16: SKU 18,17; SVU 18,17; YVU 18,17,16)
Operators are used in programs to manipulate dala and variables. They usu~lly f?nn
a part of malhematical or logical expressions. Java operators can be classified 11110
a number of related categories as below :
i) Arithmetic operators
iij Relational operators
iiQ Logical operators
iv) Assignment operators
v) Increment and decrement operators
vi) Conditional operators
vii)Bitwise operators
viii) Special operators
Q ARITHMETIC OPERATORS : Java provides all the basic arithmetic
operators to construct mathematical expression. The operators+, -. • and I all work
the same way as they do in other languages.
Arithmetic operators
Operator Meaning
+ Addition
\
- Subtraction
\
• Multiplication
I Division
% Modulo division
Arithmetic operation are used as shown below :
a-b a+ b . a%b
a •b aI b -a • b
Here a and b may be variables or constants and are known as operands.
a) Integer Arithmetic: When both tht operands in a single arithmetic expression
such as a+b are integers, the expression is called an integer expression and the
operation is called integer arithmetic.
b) Real Arithmetic: An arithmetic operation involving only real operands is called
real arithmetic. A real operand may assume values either in decimal or exponential
notation. Unlike C and c-+, modulus operator% can bt= applied to the floating point
data as well.
c) Mixed-mode Arithmetic : When one of the operands is real and the other is
integer, the expression is called a mixed-mode arithmetic expression.
ii) RELATIONAL OPERATORS : We often compare two quantities and
depending on their relation, take certain decisions. These comparisons can be done
with the help of relational operators. Java supports six relational operators These
operators and their meanings are shown below. '
0 crator Mcanin
< is lessthan
<= is less than or equal to
> is grcntcrlhan
>= is grcnlcr than or equal to
is cqunl tu
!= · is not cqunl to

iii) LOGICAL OPERATORS : An expression which combines two or more


relational expressions is termed as a logical expression or a compound relational
expression. The logical operators && and II are used when we want to fonn compound
conditions by combining two or more relations. The logical operator are shown below.
Operator Menning
&& logical AND
11 logical OR
! logical NOT

Truth table:
Value or expression
OP-1 OP-2 OP- l&&OP-2 OP-1 II OP- 2
true true ~
_J
true true
~

true false ---- I)


,........ false true
false true false true
false false false false

iv) ASSIGNMENT OPERATOR : Assignment operators are used to assign the


value of an expression to a variable. The usual assignment operator is'='.
Syntax : Variable= expression;
In addition, Java has a set of'shorthand' assignment operators which are used in the
V OP= exp;
where Vis a variable, exp is an expression and OP is a Java binary operator.
E.g. x + = 3;

v) INCREMENT AND DECREMENT OPERATORS : Java has two very


useful operators those are increment and decrement operators.
++ and - -
The operator+ + adds I to the operand while - - subtracts 1. Both are unary operators
and are use in the following fonn.
++m; or m++;
--m; or m--;
++m; is equivalentto m = m+l; (or m + = l);
--m; is equivalent to m = m-1; ( or m - = 1);
While ++m and m++ mean the same thing when they form statements
independently, the behave differently ,11 hen they are used in expressions on the right
hand side of an assignment statement.
vi) CONDITIONAL OPERATOR: The character pair ? and : is a ternary operator
available in Java. This opermor is used to construct condition:il expressions at the
fonn
exp I ? exp2 : exp3
where exp 1, exp2 and exp) are expressions.
The operator?: works as follows :. exp I is evaluated frisl. If it is true, then the
expression exp2 is evaluated. If exp 1 is false, exp) is evaluated and its value becomes
the value of the conditional expression.
Vtl) BITWISE OPERATORS : Java has a distinction of supporting special
operators known as bitwise operators for manipulating data at values of bit level.The
bitwise operator are shown below.
Operator Meaning
& biwiseAND
I bitwise OR
bitwise exclusive OR
one's complement
<< shift left
>> shift right
>>> -shift right with zero till
Viii) SPECIAL OPERATORS : Java suppors some special operators such as
instanceof and member selection operator(.)
a) Iostance,o f: The inslanceof is an object reference operator and returns true if
the object on the left hand·side is the instance of the class given on the the right-hand
side.
E.g. Person instance of student is true if the object person belongs to the class
student; otherwise it is false.
b) Dot operator: The dot operator(.) is used to access the variables and methods
of class objects.
E.g. Personal .age;
Personal .salary();
) Write short notes on JVM?

All language compilers translate source code into machine code for a specific
computer. Java compiler also does the same thing. Java compiler produces an
inte1111cdiate code known as byte code for a machine that doesnot exist. This machine
is called the Java virtual machine and it exist only inside the computer memory.

Java programj....- - ~ Java compiler j 1


--..,,,.~ Vutual machine j
source code Byte code
Process of compilation
The virtual machine code is not machine specific. The machine specific code is
gen~i:ated by Java interpreter by acting as an intermedia between the virtual machine
and real machine.

Byte code i----~ Java interpreter i - - - - - - - t Machine code


virtual machine Real machine
Process of converting byte code into machine code

W~at is conditional operator? Give an example.


[ANU 16; AdNU 16; AU 16; KU 18, 17; RU 17; SVU 17; VSU 17; YVU 17]

The Java language has an unusual operator, useful for making two-way decisions.
This operator is a combination of? and: and takes three operands. This operator is
popularly known as the conditional operator. This is also called ternary operator.
The general form oHASe the conditional operator is as follows:
Conditional expression? expression 1 : expression 2
'
. The conditional expression is evaluated first. If the result is true, expression 1 is
evaluated and is returned as the value of the conditional expression. Otherwise,
expression2 is evaluated and its value is returned.
Example:
class ConditionalOperator .
. {
public static void main (String args0)
{

int a= 10, b = 20, bi.g;


big= (a>b)?a:b;
System.out.println("Largest value="+big);
}
}
Explain about various types of if statements with examples? [AdNU 17; AU 16;
BRAU 18, 17; KU 17, 16; RU 18; SKU 16; SVU 17, 16; VSU 17, 16; YVU 17, 18)
The if statement is a powerful decision making.statement which can handle a single
statement or group of statements. These have either true or false actions. There
are mainly 4 types of if statements used in the Java programming
0 Simple - if statement
ii) else if statement
iu) else if ladder statement
iv) nested if statement
i) Simple if statement: When only one condition occurs in a statement the simple-
if statement is used having one block.
Syntax: if (test condition)
{
Statement - block;
}
Statement-x ;

True

False
Statement- block

Statement - x

Flow chart or simple ir control


Here first of all condition will be checked. If the test condition is true, the statement
- block will be executed ; otherwise the statement- block will be skipped and the
execution will jump to the statement- x.
E.g. class Simplelf
{
public static void main (String nrgs [ l )
{
int age= 25;
if(age>= 18)
{
System.ou t.println ("you are eligible to vote");
}
System.out.println ("Thank you");
}
}
ii) else if statement : The if ... else statement is an extension of the simple if
statement. The general form is
if (test condition)
{
True-bloc k statement
}
e lse
{
False-bloc k statement
}
statement- x
If the test condition is true, then the
block statement immediately following, the
if statement, are executed; otherwise, the
false-bloc k statement are executed. In False-block
either case, either true-block or false-block Statements
will be executed. In both the cases the
control is transferred subsequently to the Statement - x
statement - x .
E.g. class IfElseTest
Flow chart of if ...else control
{
public static void main(String args[])
{
int age= 25 ;
if (age>= 18)
{
System.out.pr_intln("you are eligible to vote");

}
else
{
· System.out.println("you are not.eligible to vote");

}
System.out.println ("Thank you");
}
}
ili) Nesting of if ...else statements : When a series of decisions are involved, we
may have to use morethan one if .... else· statement is nested form as follows.
if (test condition 1)
{
if(test condition 2)
{
statement-1;
}
else
{
statement- 2;
}
}
else
{
statement - 3;
}
statement - x ;
Ifthe condition-I is false, the statement-3 will be executed : Otherwise it continues
to perfonn the second test. Ifthe condition-2 true, the statement-I will be evaluated;
otherwise the statement-2 will be evaluated and then the control is transferred to the
statement-x .
l:111ry

Fuhc ·1rue

S1111 c 111c 111-)

Slalcmcnt•x

Flow chnrt of nested if ... else statements

E.g. class lfElseNesting


{
puhlic static void main(Str_ingargs [])
{
int a =325, b= 712, c =418;
Syslcm.out.print("Large value is :");
if(a>b)
{
if (a>c)
{
System.out.pl'intln (a);
}
else
{
System.out.println(c);
}
else
{
if (c>b)
{
System.out.println (c);
}
else
{
System.out. println (b);
}
}
}
MThe else if ladder: A multipath decision is a chain of its in which the statemen1
associated with each else is an if. It takes the following general fo~
if(condition 1)
statement- I;
else if(condition 2)
statement-2;
else if (condition 3)
statement-3

else if (condition n)
statement-n;
else default-statement ;
statement-x;
This construct is known as the else if ladder. The con~itions are evaluated from
the top to downwards. Ifthe true condition is found, the statement associated with it
is executed and the control is transferred to the statement - x.
. .

True

Statement-I

Statement-2

False
Si.tement-3

Statement-n Dl!!'ault
Statement

Statement • n

E.g. class ElseltLadder


{
public static void main (String args [])
{
int avg= 65;
if (avg>=80 & & avg < = I 00 )
System.out.println (" Honours");
else if (avg >=60 & & avg < = 79)
System.out.println ("First class");
else if (avg> = 50 & & avg<= 59)
System .out.println("second class");
else if (avg>= 40 & & avg<= 49)
System.out.println( "Third class");
else
System.out.println( "FAIL");
}
}
Write short notes on switch statement with example?
[ANU 18; AdNU 17, 18; AU 1&; BRAU 17; KU 17;
IVU 17, 18; VSU 17, 1&; YVU 17]

Java bas a built in multi way decision statement known as switch. The switch
statement tests the value of a given variable( or expression) against a list of case
values and when a match is found, a block of statements associated with that case
is executed. The general form of the switch statement is as shown below.
switch(variable)
{
case value I :
Statement block I :
break;
case value2 :
Statement block2;
break;

case valueN :
Statement blockD;
break;
}
Statement-X;
e ofthe variable given in the switch-
The switch case statement compares the valu
nt that follows . When the value of the
statement with the value of eac h case stateme
statement block of that pan icu lar case
switch and the case stah:~rnen t matches, the
is executed.
break statement must be used at
In the syntax of the switch case statement, The
tells the compiler to jum p out of the
the end of each case. The break statement
nt following the switch case construct.
switch case statement and execute the stateme
us go through the following rules :
To summarize the switch case construct, let
word switch must be inte gral type.
• The control expression that follows the key
• Case lab le must end with a colon.
d only when the value of the expression
• The default label is optional and is execute
ression .
does not match with .:? :iy labe lled constant exp

TRU I::

State ment block I


TRU E

l'Ce ---4
l
Statement block2

TRU E

~-. ._. State ment blockN FALSE

Statement blockD

- - - - - - - - - - - - J S1atc mcn1X

E.g. class SwitchExample


{
public static void main (String args [ J)
{
char c/1 = 11' •
1

'
switch (ch)
{
case 'a' :
System.out.println("lt is vowel");
break;
case 'e' :
System.out.println('_'lt is vowel~');
break;
case ';1 :
System.out.println("lt is vowel");
break;
case 'o' :
System.out.println("lt is vowel");·
break ;
case 'u':
System.out.println("lt is vowel");
break;
default :
System.out.println("lt is not vowel");
}
}
}
Output :
It is vowe l.
Explain about various types of looping statements in Java program?
[ANU 18, 16i AdNU 18, 17, 16i AU 18i BRAU 18, 17, 1&i KU 18, 16i
RU 17, 16; SKU 18, 16; SVU 18, 17; VSU 18, 17, 16; YVU 18]
(or)
Write a short notes on iterative statements that Java language supports?
When a single statement or a group of statements will be executed again and again
in a program then such type processing is called Loop(or iteration). The Java
programming language contains 3 different programming statements for program
looping
1. for Loop 2. while Loop 3. do while Loop
1. For Loop: It is a looping statement which repeat again and again till it satisfies
the define condition it is also entry control loop.
Syntax:
for(initialization statement; test expression; update statement)
{
codc/s to he executed~
lnitiolizotion
stotcmcnl
}
The initia lizati on statem ent is Updotc
stotcmcnt
executed only once at the beginn ing
of the for loop . Then the test
expre ssion is check ed ~y th_e
True Body of
progra m. (f the test expres sion ~s for loop
false, for loop is termin ated. But tf
test expres sion is true then the code/
s inside body of for loop is execu ted Exit for loop
and then updat e expre ssion is
update d. This proces s repeat s until
test expres sion is false . Statement just
below for loop
Exam ple: Progr am to displa y from
l to 10 using for loop
class ForEx ample Flowchart of for loop
{
public static void main (Strin g args[] )
{
for(int i=l ; i<IO; i++)
{
System .out.p rint(i+ " ");
}
}
}
Output:
1 234 567 891 0
2. While Loop : The while loop is best suited to repeat a statem
ent or a set of
statem ent as long as some condi tion is satisfi ed the ge_neral form
of while loop is
while ( test condi tion)
{
Body of the loop
}
The while is an entry contro lled loop statem ent. The test condi tion
1s evalua ted
and if the condi tion is true, then body of the loop is execu ted. After
execu tion of
the body, the test condi tion is once again evalua ted and if it is true,
the body is
execu ted once again. This proces s contin ues until the test- condit ion
finally becom es
false the contro l is transf erred out of the loop and the body of the
loop may have
one or more statem ents. If the test condi tion evalu ate to false at
the first time the
statem ents are never execu ted.
False
>-----< E x it while loop

True

Body of
whil e loop

~xample: Program to calculate factorial of a given number using while loop.


:lass While Example
{
public'static void main (String args[])
{
int no=S f= l ·
' '
while(no>0)
{
f=~no·
'
no - -;
}
System.out.println("factorial of the given number="+f);
}
}
Output:
factorial of the given number= 120
3. do-while Loop: The while loop makes a test of condition before the loop is
executed. Therefore the body of the loop may not be executed at all if t'1e condition
is not satisfied at the very first attempt. On some occac;ions it might be necessary
to execute the body of the loop before the test is performed such situations can be
handle with the help of the.body of the do-while statement
Syntax.: do
{
Body of the loop
}while(test condition);
In this statement first body of the loop is executed and then the condition is
checked. If condition is true then body of the loop is executed when condition
becomes false then it will exit from the loop. Note that semicolon must be at the
end of the while loop.
Flowchart :

Body of
while loop

false Exil do while loop

True

Example: Write a program to calculate the average of first N numbers.


class DoWhileExample
{
public static void main (String args[])
{
int n=l0, sum=O,i;
float av~0.0f;
i=l;
do
{
sum=sum+i;
i=i+l;
}while (i<=n);
avg=sum/n; .
System.out.println("sum of first n numbers="+sum);
System.out.println("average of first n number= "+avg);
}
}
Output
sum ,o f first n numbers= 55
average of first n numbers= 5.5
What are the jumping statements in Java? Explain.
[BRAU 16; RU 16; SKU 17; SVU 18; YVU 17)
(or)
Explain about jumps in loop in Java?
Java permits a jump one statements to the end or beginning of a loop as well as a
jump out of a loop
1) Break statement: In Java programming, break is used in terminating the loop
immediately after it is encountered. The break statement is used with conditional if
statement.
The general syntax for break statement is
Syntax : break;
The break statement can be used in tenninating all three loops for, while and do ..while
loops

True break ;

False

Flowchart of break statement

Example of break statement:


class BreakExample
{
public static void main (String args[])
{
for (int i= I; i<= 10; i++)
{
if(i = = S)
break;
System.out.print(" "+i);
}
System.out.println("End ofthe loop");
}
}
Output :
l 2 3 4 End of the loop

2) continue:- It is sometimes desirable to skip some statements inside the loop. In


such cases, continue statements are.used.
The general syntax is
Syntax:- continue;

Normal return ~-.,;,;Tr_ue__., continue


of loop

Remaining part of
loop

Flowchart of continue statement


Example of continue statement :
class ContinueStatement
{
public static void main (String args0)
{
for(int i=l; i< 10; i++)
{
if(i ==S)
continue;
System.out.print(i +" ");
}
System.out.println("End of the loop")~
}
}
Output
1 2 3 4 6 7 8 9 10 End of the loop.

Delin~ the array ,,vilh syntax?


(ANU 17; AdNU 18, 1 -✓; BRAU 16, 17; KU 18, 17; S t<U 17; V SU 18; YVU 16)

An array is a kind of variable that refers to a collection of da1:i items whidi all h.ivc
same name an<t same data type. The clements of an ;-irray c:in b,.: <l:11a1:, p-.:. Al l th.:
elements in an array must be of sam~ type. There arc two Iy p~s of mr:1ys.
1. One Dimensional arrays
2. Multi Dimensional arrays
1) One Dimensional Arrays : A List of items can be given arc variable Name
using only one subscript([]) and such ,1 variable is called a arc dimcn.,iunal /\rroy
(or) Single subscripted variable.
The general systax of declaring one dimensional array is :
rype ~rrayName [] = new type [size];
Example : int a[] = new int [3];
Here type declares the basic type of the Array, arrayName is the name of the
array size the number of elements that anay contains.
2) Multidemensional Arrays : Multidemensional arrays represent ~D, 3~ ....
arrays. A Two dimensional array is a conrbiuation of two or more (ID) the d1mens1onal
1111 -ny'i. 1111cc cli1111.·11,1111111I a,rny '"
;\ II c11mh11111t.io11 of rwu or nuu,c (21>) '""o
d1111cw,i111111I 111111) s
, ) I\, 11 I >iIII l' 1"'i111111 I II rrn ~ s ( 21> nr rn y )
/\ t\\11 tli111c11"in11nl nrrny rrpn:sc11ls scvcrnl rows 1111<1 columns of cl1111. To
ll'ptt.''it.'nl II lw,, "i111cnsi111111I 111rny, we should 11:--c rwu pain uf ' llllllrC hr:u.:"cls I I, II
11 lh-1 thl· 11n11y N11111e. ;\ two di111cnsi111111I nrray dcclurr,1 ns type nrrnyNnmc (III •
""'" rypc I110\\ -~i,c II col-si ,c J:
l•:x1111119lc : int 11 1111 ·- 11cw i11t I) I PI:
ii) Three <limc11sinn11I Arrnys : We c1111 c,111sidcr II three dimcnsionnl nrrny u a
crn11in11t11r of scvcrnl two di111cn-.i111111I nrrnys. To rcprc:--cnt a three dimcusiunal
11rrny. we shoulil use three pairs uf squnrc hrm:kcrs.
;\ three tfo11c11siu11nl nrruy dcdnrcd ll'i
type 11rrnyN11111c 111111 u ncw lsi,cl lsi1cl [sizeJ;
l•'.x111111,lc: int 11111111 • new int Pl (31 IJJ;

llril•ny uplnin 11ho11t nnc-dimcm1lnm1I nrrAys in Jav11?


[ANU 181 AdNU 111 BIIAU 111 KU 111 IKU 111 IVU 111 YIU 111 YYU 11J
/\ list of items cn11 he given one vnrinhlc name using only one subscript nnd such a
vnri:ihle is culled II si11glc suhs1.:riptcJ vnrinhlc or none dimensional arrny.
I. Ueclnl'ln~ one dlmemdonnl 11rr11y1 : I .ikc nny other vuriablc. arrnys must be
drclan.·d hcforc they nrc used su thut the compiler con allocntc space for them in
llll'II\Ory. The genernl form of a one-dimensional nrray declaration is
type nrruy _1111111cl1;
1lcrc type declares the base type of the unay. The base type detenninc the datatype
of c~tch clement tlmt comprises the nrray.
For exnmplc, the following declares an array named month_days with the type
nrrny of int
int month_days[J;
Aflcr declaration an array, we need to create it in the memory. Create arrays
using new operator only as shown below
urray_name = new type [size);
Herc type specifies the type of data being allocated, size specifies the number of
clements in the orray.
P'or example allocates a 12-elements array of integer and links them to month-days.
month_days = new int[l2];
After this statement exe~utes month_days will refer to an array of 12 integers.
It is possible to combine the two steps declaration and creation into one following
syntax: type array_name[] = new type[size];
Example: int month_days[] = new int [12];
2. Intialization of one-dimensional arrays : Arrays can be initialized when they
are declared. An array initializer is a list of values are seperated by comma'- :1nd
surrounded by curly braces. There is no need to use new operator. We can inti··· ._.
arrays automatically in _the same way as the ordinary variables when the) ar~
declared as show below
type array_nat.~::~] · {list ofvalu~s};
E.g. intmonth_days[] = {31,28,3 l,30,3 l,30,31,31,30,31,30,31 };
3. Accessingelementsoftbeone-dimensionalarray: Foraccessingan indivi,lnal I
element of the array, the array subscript must be used. The subscript index mm-• 11·
an integer value or an expression that evaluate to an integral value .
Example :
class OneDimentionalArray
{
public static void main(String args[ ])
{
int a[]={ 10,20,30,40,50};
int n = a.length;
System.out.println("Given list:");
for(int i=O; i<n;i++)
{
System.out.print(" "+a[i]);
}
}
}
Output:
Given list
10 20 30 40 50
Briefly explain about two-dimensional arrays injava?
[ANU 17, 16; AdNU 18, 17;
AU 18; BRAU 18; KU 18, 16; SKU 18; SVU 17, 16; VSU 17; YVU 171
The concept of one-dimensional array is extended to incorporate two-dimensio11,, 1
(2D) arrays. A two-dimensional array is specified using two sub scripts where r ·•::
subscript denotes row and the other denotes column. Two-dimensional array which
can be viewed as an array of array_s~
1. Declaration of two-dimensional arrays : Similar to one dimensional arr:•~·s,
two-dimensional arrays must be declared before being used. The declan11 ,,.,~
statement tells the compiler the name of the array, the datatype of each eleme11, i1 ,
the array, and the size of each dimension.
.
A two-dimensional array is declard as : ...
type array_name[] []=new type [row-size] [col-size];
.

Example : int A[][ ]=new int [3][3];


This allocates a 3 by 3 array and assigns is to A. Internally this matrix is implemented
as an array of arrays of int.
· .... -d " ensi·onal arrays: It is possible to initialize two-dimensional
2 . I n ti. a1·1z10g n, o 1m . . .. . • h· · f
-r d ·
arrays. , o o so, s1rnp y enI close each dimensions m1t1altzer wit m its own set o
curly braces.
Example : int a[ ] [ J= { {1,2,3} ,
{4,5.6},
{7,8,9}
};
3. Accessing the elements : Two-dimensional contains ~o subscripts, we w~II
use two for loops to access the elements. The first for loop w1_1l l~~p for each row m
the two-dimensional array and the second for loop will access md1v1<lual columns for
every row in the array.
Example :
class TwoDimensionalArray
{
pub Iic static void main(String args[])
{
int m[ ][ ]={
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i=O; i<J; i++)
{
for(intj=O;j<3;j++)
{
System.out.print(m[i][j]+" ");
}
System.out.println( );
}
}
}
Output :
1 2 3
4 5 6
7 8 9
Explain about three dimensional arrays in Java?
Three dimensional arrays are also called space array. In this space rows and columns
are taken. Three dimensional array will require three subscripts i.e., three pairs of
square brackets.
I . Declaration of three dimensional arrays: similar to one and two dimensional
arrays most be declared before being used. The declaration statements tells the
compiler the name of the array, the data type of each element in the array'3nd size
of each dimension. A three dimensional array is declared as : ·
tvnP n n n = new r~i7el r~i7el r~izel:
~rT:IVn~me
type arrayname OOO= new [size] [size] [size];
2. Initialization of JD array: you can initialize a three dimensional array in similar
way like a two dimensional array.
Example:
int ar [21[3][4] = {
{
{1,2, 3,4},{S,6,7,8},{9, 10, 11, 12}},
{13, 14, 15, 16}, {17, 18, 19,20}, {21 , 22,23, 24}
};
3. Accessing elements of the three-dimensional array : Three dimensional
arrays contains three subscripts, we will use three for loops to access the elements.
Example :
class ThreeD
{
public static void main(Stringargs[])
{
int a O(] (] = new int (21[2)[2], i, j, k, m = I;
for (i = 0; i < 2; i + +)
forG =O;j <2;j ++)
for (k = O; k < 2; k + +)
{
a [i] [j] [k] = m;
m++;
}
System.out.println ("Three dimensional array is:");
for (i = O; i < 2; i + +)
{
forG=O;j<2;j ++)
{
for (k = O; k < 2; k + +)
{
System.out.print(a[i] [j] [kl+" ");
}
System.out.println();
}
System.out.prinln();
}
}

You might also like