PJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdf

projectfora2 30 views 90 slides Oct 18, 2024
Slide 1
Slide 1 of 90
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90

About This Presentation

java unit 1


Slide Content

Introduction to
Object Oriented
Programming using
Java
Chapter 1.1

ToprovidestudentswiththebasicsofObject
OrientedProgrammingusingJava..
Aim

After completing this chapter, you should be able to:
•Explain the Object Oriented features in Java
•Describe the role of JVM
•Illustrate keywords, variables and data types in Java
•Demonstrate common lexical issues in Java
•Illustrate Java type conversion and casting
•Describe arrays in Java
Instructional Objectives

LearningOutcomes
Attheendofthischapter,youareexpectedto:
•DifferentiatebetweenthefeaturesofC++andJava.
•Applyvariousdatatypes,keywordsandvariablesinasimpleJava
program.
•DemonstratecommonlexicalissuesbycreatingaprograminJavato
countthenumberofspaces,identifiersandcomments.
•Describethetypesoftypeconversionwithexamples.
•Createaprogramtoillustratetheconceptofpassinganarraytomethod.
•Demonstratetheapplicationsofmultidimensionalarraywithan
example.

Introduction to Object Oriented
Programming in Java

I.ObjectOrientedProgramminginJava
Introduction
Oneofthemostimportantconceptsof
programminglanguageisitsreliability.Object
OrientedProgrammingconcepthelpskeepinga
programminglanguagetoutmostreliableand
dependable.Let’slookdownuponhistoryofJavaand
howdoesitcometoexistenceasaprogramming
languageafterCandC++.

ObjectOrientedProgramminginJava
EvolutionofJava
Researcherswerethinkingofaprogramminglanguagewhichcouldbesecurable,
reusableandsupportallplatformsandalsoactsasaclass-based,object-oriented
withspecificallydesigneddependenciestofixthedrawbacksofexistinglanguages
likeCandC++.WhereCisnotsecured,andC++doesnothavetheadvanced
characteristic.
Itintendedtodevelopanapplicationprogramwhichcanbe"writeonceandrun
anywhere"(WORA),whichmeansthecompiledJavacodecanrunonallplatforms
thatsupportJava.

ObjectOrientedProgramminginJava
HistoryofJava
ThemostpopularprogramminglanguagesareC,C++,C#,andJava.WhereJavaisanadvanced
programminglanguageandfacilitatesadvancedtechnicalfeatureswhencomparedwitheach
other.
Arevolutionarytasktodevelopaprogramfordigitaldevicessuchassettopboxesandtelevision
wasaninterestingfactwhichmadeJavaprogrammingtocomeintoexistence.Itwasanadvance
conceptatthattimeforGreenteammembers(developersofJavaprogrammers)butitsatisfied
thedemandsofinternetprogramming.Later,NetscapeincorporatedJavaprogramming.
Javaisapropertiedlanguagewhichhasitsbestelementstoinheritandcombinewithany
innovativeconceptwhichcanbuilditsownuniquemission.Javaisatechnicallyblendedlanguage
whichhasarichelementsthatcanaddressanychangingexpectationsandtechnicalinnovations.
Atpresent,Javaisoneofthemostpopularprogramminginuse,particularlyinclient-server
architecture,internetprogramming,mobiledevices,games,e-businesssolutionsetc.

ObjectOrientedProgramminginJava
Object Oriented Programming Concepts
JavaisanObjectOrientedlanguage.ItprovidesthefeaturetoimplementanObject
Orientedmodel,whereitisorganisedaroundobjectsandlogicratherthandata.It
isusedinthebeginningofsoftwarelifecycleandalsousedtodevelopother
applications.
ObjectOrientedProgrammingisatechniqueinwhichprogramsarewrittenonthe
basisofobjectse.g.(Java)whereitadoptsaconceptthatviewseverythingasan
objectandimplementsalogicinrelationtoit.Let’sseetheconceptsofObject
OrientedProgrammingindetailwithanrealtimeexample.

Object Oriented Programming
Concepts

Object Oriented Programming Concepts
Object
Anobjectisnothingbutamatterofthing
whatwefindineverydaylife.Technically,
Javaisasoftwarebundleofrelatedstateand
behaviour.
Example:Car,box,mountain,computeretc.

Object Oriented Programming Concepts
Object and its components

Object Oriented Programming Concepts
Object with Its Attributes

Object Oriented Programming Concepts
Class
InJavaprogramming,classisdefinedas
ablueprintfromwhichobjectsare
created.Itmodelsanddescribesthe
stateandbehaviourofanobject.
Example:Consideracarwithseveral
propertieslikeclutch,steering,break,
etc.

Object Oriented Programming Concepts
Inheritance
Inheritanceisapropertybywhichstateand
behaviourofoneclass(superclass)canbe
inheritedtoitssub-class.Itisapowerful
andanaturalmechanismfororganisingand
structuringasoftware.
Example:Humanheredity

Object Oriented Programming Concepts
Abstraction
Hidingtheimplementationdetailsfromtheuseriscalledasabstraction.Here,
onlythefunctionalitywillbeprovided.InJava,abstractioncanbeachievedby
abstractclass,andInterface.
Aclasswithanabstractkeywordiscalledasabstraction.
Interface–blueprintofaclass.Fullabstractioncanbeachievedusingthis
mechanism.
Example:Inventionofflightisbasedontheflyingmechanismlearntfrom
birds.Soflightsarederivedformbaseclassbirds.

Object Oriented Programming Concepts
Encapsulation
EncapsulationisoneofthefundamentalconceptofOOP.
Mechanismofbindingthedataandfunctiontogetherinasingle
unitiscalledasencapsulation.

Object Oriented Programming Concepts
Polymorphism
Polymorphismisanabilityofanobjecttotakemanyforms.Itreacts
differentlyindifferentsituation.InJava,polymorphismisusedtoreduce
codecomplexities.Methodsorfunctionofaclassimpliesthebehaviourof
polymorphism.InJava,allJavaobjectsarepolymorphic.

Components of Java

Components of Java
JavaCompiler
Compilerisusedtosystemizetheprogramandcheckagainstlanguagesyntax
rules.Itconvertsthesourcecodetobytecodeandthencompilesthem.TheJava
compilergeneratesanarchitecture-neutralobjectfileformat(thecompiledcode–
sourcecodeandbytecode)tobeexecutableonmanyprocessors.
Sourcecode-collectionofcomputerinstructionswritteninhumanreadableformat.
Writestheoutputinjavafile
Bytecode-computerobjectcode,alsocalledasinstructionsetofJavaVirtualMachine.
Writestheoutputinclassfile

Java Virtual Machine (JVM)
JavaVirtualMachine–enablesthecomputertorunJavaprogram.Itreadsandinterprets
classfilesandexecutestheprogram’sinstructionintonativehardwareplatform.
JVMisplatformindependent(obtainableformanyhardwareandsoftwareplatforms).In
theJavavirtualmachinespecification,thebehaviourofavirtualmachineinstanceis
describedintermsofsubsystems,memoryareas,datatypes,andinstructions.These
componentsdescribeanabstractinnerarchitecturefortheabstractJavavirtualmachine.
Thepurposeofthesecomponentsisnotsomuchtodictateaninnerarchitecturefor
implementations.Itismoretoprovideawaytostrictlydefinetheexternalbehaviourof
implementations.ThespecificationdefinestherequiredbehaviourofanyJavavirtual
machineimplementationintermsoftheseabstractcomponentsandtheirinteractions.

Java Virtual Machine (JVM)
Let’sdiscusswhatdoesJVMperforms?
Itisusedtoloadthecode
ItVerifiesandexecutesthecode
Anditprovidesruntimeenvironment

Java Virtual Machine (JVM)

Java Virtual Machine (JVM)
Components of JVM:
Following are the components of JVM:
•Stack
•Heap
•Constant Pool
•Code segment
•Program counter

Components Of JVM
1.Stack
Temporaryvaluesarestoredinframesofa
stack.
ItcontainsthestateofJavamethodinvocation.
Whileinvokingamethod,JVMpushesanew
frameontothatthread’sJavastack.
Aftercompletionofasinglemethod,thevirtual
machinepopsanddiscardstheframeforthat
method.

Components Of JVM
Heap
Heap consists of objects. The JVM has a
heapthat is the runtime data area from which
memory for all class instances and arrays are
allocated.
It is created at the JVM start-up.
•Heap Memory –store Java objects
•Non-heap memory –Store Meta data and
other loaded classes.

Components Of JVM
Constant Pool
Constant pool consist of all constant data.
They comprise of
•Numbers
•Strings
•Symbolic names of classes, interfaces
and fields

Components Of JVM
Program Counter
Tracking of current instruction execution at any
moment is done by Program Counter (PC) register.
It is similar to that of pointer which keeps in track of
current instruction in sequence.
Every time a new thread is created, a PC register is
also created simultaneously.
PC keeps a pointer to the current statement that is
being executed in its thread.

29
Simple Java Program
•Javaisageneral-purposeprogramminglanguage.Likeanyprogramming
language,Javaalsohasitsownsyntax,structureandprogrammingparadigmto
buildarobust,reusableandmaintainableapplicationsprograms.
•JavaprogramsareexecutedinitsdevelopmentenvironmentsuchasJava
DevelopmentKit(JDK)andEclipseIDE.
•Programmatically,JavaisaderivativeofC++language.SyntaxofJavalookssimilar
likeC.Codeblocksaremodularisedintomethodsanddelimitedbybraces({})
andvariablesaredeclaredbeforetheyareused.
•Javaprogramstartswithapackagewherethepackagecanbedefinedasa
namespacemechanism.Ithelpstomaintainthehierarchicalfilesystem,manage
filesystemandclasssystem.

Hierarchy of Java Program Components

Java Program
Example : A simple java program is illustrated below :
public class FirstProgram
{
Public static void main (string [ ]args)
{
Sytem.out.println(“ First Java Program”);
} //end of main
} //end of First Program class

Self –Assessment Questions
1)Java is an architectural dependent programming language.
a)True b) False
2) ______________ is an instance of class.
a)Package b) Object
c)Class d) None of these
3) By default, all Java Objects are Polymorphic.
a) True b) False

Data types, Keywords and Variables

II. Data Types, Keyword and Variables
Variablesarememorylocationstostorevalues.
Whenausercreatesavariable,amemoryspaceisreservedforthatthevariable.
Basedonthetypeofthevariable,theoperatingsystemallocatesmemoryand
decideswhatcanbestoredinthatreservedspace.
Ausercanstoreintegers,decimals,character,etc.byassigningdifferentdata
typestothevariables.
Datatypeisakeywordusedtoallocatesufficientmemoryspaceforthedata.
Pictorialrepresentationofdatatypesanditsclassificationsaregivenbelow:

Classification of Data types

Classification of Data types
Let’sseethelistofdatatypesanditsdescriptioninthefollowing.Thetypes
are:
•Integer
•Floatingpoint
•Character
•Boolean
•TypeconversionandCasting
•AutomaticTypepromotioninexpression

Integers

Integers
Java defines four integer types:
Byteshort
int long
Allofthesearesigned,positiveandnegativevalues.
Javadoesnotsupportunsigneddatatypes.Whereas
signedandunsignedintegersaresupportedbymany
othercomputerlanguages.
Javadesignersfeltthatunsignedintegersare
unnecessarybecausetheyaremostlyusedtospecify
behaviorofthehigherorderbit,whichdefinesthe
signofanintegervalue.Thewidthofanintegertype
shouldnotbethoughtofastheamountofstorageit
consumes,butratherasthebehavioritdefinesfor
variablesandexpressionsofthattype.TheJavarun-
timeenvironmentisfreetousewhateversizeitwants,
aslongasthetypesbehaveasyoudeclaredthem.

Integers
Integers and its types
Name Width Range
Long
64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Int
32 -2,147,483,648 to 2,147,483,647
Short
16 -32,768 to 32,768
Byte
8 -128 to 127

Bytes
•Thesmallestintegertypeisbyte.
•Thisisasigned8-bittypethathasarangefrom-128to127.
•Variablesoftypebyteareespeciallyusefulwhenyou’reworkingwitha
streamofdatafromanetworkorfile.
Itcanberepresentedas:
Byteb,c;

Short
•Shortisasigned16-bittype.
•Ithasarangefrom–32,768to32,767.
•Itisprobablytheleast-usedJavatype.
Herearesomeexamplesofshortvariabledeclarations:
short s;
short t;

Int
•Themostcommonlyusedintegertypeisint.
•Itisasigned32-bittypethathasarangefrom–2,147,483,648to
2,147,483,647.
•Inadditiontootheruses,variablesoftypeintarecommonlyemployedto
controlloopsandtoindexarrays.

Long
•Longisasigned64-bittypeandisusefulforthoseoccasionswhereanint
typeisnotlargeenoughtoholdthedesiredvalue.
•Therangeofalongisquitelarge.Thismakesitusefulwhenbig,whole
numbersareneeded.

Floating –Point
•Floating-pointnumbers,alsoknownasrealnumbers
•Therearetwokindsoffloating-pointtypes:
Float
Double
which represent single-and double-precision numbers, respectively.

Floating Point

Floating –Point types
Their Width and ranges are shown below :
Name Width Approximate Range
double 64 4.9e-324 to 1.8e+308
float 32 1.4e-0.45 to 3.4e+0.38

Floating –Point types
Float
•Floatisspecifiedasasingle-precisionvaluethatuses32bitsofstorage.
•Singleprecisionisfasterandtakeshalfasmuchspaceasdoubleprecision,,but
willbecomeimprecisewhenthevaluesareeitherverylargeorverysmall.
Here are some example float variable declarations:
float hightemp, lowtemp;

Floating –Point types
Double
•Doubleisdenotedbythekeyword‘double’whichisusedtostoreavalueof64bit.Itis
fasterthansingleprecisiononmodernprocessorthathavebeenoptimizedforhigh-
speedmathematicalcalculations.Someimportanceofdoubleare:
•Alltranscendentalmathfunctions,suchas
sin()
cos()
sqrt()
•returndoublevalues.
•Doubleisbestchoice,whenyouneedtomaintainaccuracyovermanyiterative
calculations,oraremanipulatinglarge-valuednumbers.

Example Programs

Integer
Public class DataType_int
{
inta=100;
intb=-150;
void add( )
{
Intc=a + b;
Sysytem.out.println(“The int
value is:” +c);
}
}
Class Demo
{
public static void main(String
args[ ] )
{
Datatype_Intobj=new
DataType_Int( );
Obj.add();
}
}
Output:
The intvalue is -50

Double Integer
//Computetheareaofacircle.
classArea{
publicstaticvoidmain(Stringargs[])
{doublepi,r,a;
r=10.8;//radiusofcircle
pi=3.1416;//pi,approximately
a=pi*r*r;//computearea
System.out.println("Areaofcircleis"+a);
}
}
Output:
Area of circle is 366.435

Characters

Characters
•charinJavaisnotthesameascharinCorC++.
•JavausesUnicodetorepresentcharacters.
•Unicodedefinesafullyinternationalcharactersetthatcanrepresentallofthe
charactersfoundinallhumanlanguages.
•Itisaunificationofdozensofcharactersets,suchas
Latin
Greek
Arabic
Cyrillic
Hebrew

Characters
•InJava,charis16bitandrangesfrom0to65,536.
•Therearenonegativechars.
•ThestandardsetofcharactersknownasASCIIstillrangesfrom0to127as
always,andtheextended8-bitcharacterset,ISO-Latin-1,rangesfrom0to255.

Characters
Example Program : Demonstrates char variables
class CharDemo{
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This program displays the following output:
ch1 and ch2: X Y

Boolean

Boolean
TheBooleanlogicaloperatorsare:
|,&,^,!,||,&&,==,!=.
•JavasuppliesaprimitivedatatypecalledBoolean,instancesofwhichcantake
thevaluetrueorfalseonly,andhavethedefaultvaluefalse.
•ThemajoruseofBooleanfacilitiesistoimplementtheexpressionswhich
controlifdecisionsandwhileloops.

Boolean
Example program:
class Boolean
{
public static void main(String args[])
{
// these are booleanvariables
booleanA = true;
booleanB = false;
System.out.println("A|B = "+(A|B));
System.out.println("A&B = "+(A&B)); // program execution using boolean
System.out.println("!A = "+(!A));
System.out.println("A^B = "+(A^B));
System.out.println("(A|B)&A = "+((A|B)&A));
}
}
Syntax:
booleanValue(); // returns the value of Boolean object

TypeCastingandConversion

Type conversion and Casting
•Typecastingisusedtoassignvalueofonetypeofavariabletoanothertype.
Castinginotherwordsisaninstructiontothecompilertoconvertonetypeto
another.
•IthelpsJavanotonlytoperformonlyarithmeticoperationsonpairsofvaluesof
sametypebutperformsoperationsonmixedtypetoo.
•Forexamplethevalueoftherightsideisautomaticallyconvertedtothetypeof
theleftsideincompatibletypes.
•InJava,Booleanandintarenotcompatible.
•Whentheabovesaidconditionsaremet,awideningconversiontakesplace.

Type conversion and Casting
Types : There are two types
Types Casting
Widening casting Narrowing Casting

Type conversion and Casting
1) Widening casting
In widening casting, the value types are not directly expressed. Here, integer and
floating are compatible with each other. Integer literal can be assigned to char.
Widening
Byte Short Int Long Float Double

Type conversion and Casting
2) Narrow casting:
In narrow casting, the value types are directly expressed.
Narrowing
Double Float Long Int Short Byte

Type conversion and Casting
Difference between Widening and Narrowing
Widening Casting Narrowing Casting
Used to access new methods of child class or
while referring super class to child class
Used to access redefined class of parent class in the child class

Type conversion and Casting
Sample Program:
Package conversion;
Public class main
{
Public Static Void main(string [ ] args)
{
intvar1=12;
double var2=15.2;
double result = var1+var2;
System.Out.Println(“The sum is” + result)
}
}

Self –Assessment Questions
1) Boolean is used to control the decisional statement in a program
a)True b) False
2) Java supplies a primitive data type called_________________.
a)Integer b) Float
c)Boolean d) Character
3) Any size of an integer is handled by Java.
a) True b) False

LexicalIssues

Lexical Issues
•Javaprogramsarethecollectionofwhitespace,identifiers,literals,comments
andseparators.
•Lexicalissuesareverycommoninprogramming,whichisusedtoanalysis,
operateandimplementtheprograminasequentialorder.

Lexical Issues
Letusseethedetaildescriptionoflexicalissuesinthefollowing.
i.Whitespace
•Aswordbyitself,awhitespaceisnothingbutaspace,tab,oranewline.
•Javaisacasesensitivefree-formlanguagewhichmeansauserneednotfollow
anyspecialrules.
•Forexample,thereisnoformattobefollowedtowriteaJavaprogram.
•Aprogramcanbewritteneveninasinglelineoranynumberoflinescanbe
used,whateveruserwishes.
•Bydefault,singlewhitespaceisrequiredbetweeneachcharacter.

Lexical Issues
Identifiers
•Anidentifiercanbedescribedasanydescriptivesequenceofuppercase,
lowercaseletters,underscoreoradollar-signcharacter.
•Identifiersareusedforspecifyingclassname,methodnameandvariablename.
SinceJavaiscase-sensitivelanguageanyletterofawordwillbedifferentfromthe
otherformofthesimilarword.
•LetussayinJava,awordmaxisdifferentfromMAX.

Lexical Issues
Literals
Literalsareusedtospecifyadefaultvalueortodeclareaconstantvalue.
Itcanbea:
•Boolean–TrueorFalse
•Numeric–floating,decimal,integerorafixedpoint
•Characterbased–singlecharacterorastring

Lexical Issues
Comments
Three types of comments are supported by Java. They are
Comment Description
/*text*/ Compiler ignores everything from /* to */
//text Compiler ignores everything from // to the end
of the line
//**documentation*/ Called as doc comment (documentation
comment) –used by automatically generated
document

Lexical Issues
Separators
Separators are characters used to terminate statements. Commonly used separators
are semicolon (;). Following are few separators used in Java programs
Symbol Name Purpose
( ) Parenthesis Control the order of operation
{ } Braces Used to group statements and
declaration
[ ] Brackets Used to declare array types and
dereferencing array values
; semicolon Terminates statement
, comma Separates consecutive identifiers in a
variable decalaration

Self –Assessment Questions
1)____________line space is required to separate each statement.
a)Single b) Double
c) More than one d) Not required
2) Java is a case-sensitive programming language.
a)True b) False
3) _______ is used to store values specified by a data type.
a) Variables b) Identifiers
c) Literals d) Separators

Arrays

Arrays
Arrayisacollectionofsimilartypesofelementsthathavecontiguousmemorylocation.
Itisacontainerobjectthatholdsvaluesofhomogeneoustype.Javaarrayiscontainerobjectthat
containselementsofsimilardatatype.
Itcanhave:Onlyfixedsetofelementswhichcanbestoredinit.
Alsohavelabelasstaticdatastructurebecauseduringthetimeofdeclarationonlythesizeofthe
arrayisspecified.Anarraycontainingnumberofvariablesanditcanevenstartfromzero–whichis
calledasanempty,insteadtheyarereferencedbyarrayaccessexpressionsthatusenon-negative
integerindexvalues.
Syntax:
datatype[]identifier;Ordatatypeidentifier;

Arrays
Initialization of an array:
[ ] -Intoperator is used to initialize an array.
Example program:
Int[] arr= new int[15]; // 15 is the size of an array

Array
Array Type :
Arraytypesareusedindeclarationsandincastexpression.Anarraytypeiswrittenasthenameof
anelementtypefollowedbysomenumberofemptypairsofsquarebrackets[].Thenumberof
bracketpairsindicatesthedepthofarraynesting.
Anarray'slengthisnotpartofitstype.Itmaybeofanytype,whetherprimitiveorreference.
•Arrayswithaninterfacetypeastheelementtypeareallowed.Anelementofsuchanarray
mayhaveasitsvalueanullreferenceoraninstanceofanytypethatimplementstheinterface.
•Anarraywithanabstractclasstypeastheelementtypeareallowed.Anelementofsuchan
arraymayhaveasitsvalueanullreferenceoraninstanceofanysubclassoftheabstractclass
thatisnotitselfabstract.

Array
Array Variable:
A variable of an array type enfolds a reference to an object. It is used to create a
variable and does not create any space to that specified variable. Some of the
variable declarations are listed below. They are:
Declaration Comment
Int[ ] Array of int
Short [ ] [ ] Array of short
Object [ ] Array of object
Collection<?> Array of collection of unknown types

Array
SingleDimensionalArray:
Aone-dimensionalarrayconsistofalistoflike-typedvariables.
Thegeneralformofaone-dimensionalarraydeclarationis
Thegeneralformofnewasitappliestoone-dimensionalarrays,appearsas
follows:
arrayRefVar=newdataType[arraySize];
type var-name[ ]; // syntax

Array
Theabovestatementdoestwothings:
1.ItcreatesanarrayusingnewdataType[arraySize];
2.ItassignsthereferenceofthenewlycreatedarraytothevariablearrayRefVar.
Theexamplebelowallocatesa12-elementarrayofintegersandlinksthemto
month_days.
month_days=newint[12];
Afterthisstatementexecutes,month_dayswillrefertoanarrayof12integers.
Further,allelementsinthearraywillbeinitializedtozero.

Array
Youcanaccessaspecificelementinthearray,onceafteryouallocateanarrayby
Specifyingitsindexwithinsquarebrackets.Allarrayindexesstartatzero.
Forexample,thisstatementassignsthevalue28tothesecondelementof
month_days.
month_days[1]=28;
Thenextlinedisplaysthevaluestoredatindex3.
System.out.println(month_days[3]);

Array
Puttingtogetherallthepieces,hereisaprogramthatcreatesanarrayofthe
numberofdaysineachmonth.
// Demonstrate a one-dimensional
array.
class Array {
public static void main(String
args[]) {
intmonth_days[];
month_days= new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " +
month_days[3] + " days.");
}
}

Array
Whenyourunthisprogram,itprintsthenumberofdaysinApril.Asmentioned,
Javaarrayindexesstartwithzero,sothenumberofdaysinAprilis
month_days[3]or30.
Itispossibletocombinethedeclarationofthearrayvariablewiththeallocation
ofthearrayitself,asshownhere:

Array
MultidimensionalArray
Javadoesnotsupportmultidimensionalarrays.However,youcandeclareand
createanarrayofarrays
However,asyouwillsee,thereareacoupleofsubtledifferences.Todeclarea
multidimensionalarrayvariable,specifyeachadditionalindexusinganothersetof
squarebrackets.Forexample,thefollowingdeclaresatwodimensionalarray
variablecalledtwoD.
inttwoD[][]=newint[4][5];

// Demonstrate a two-dimensional array.
class TwoDArray{
public static void main(String args[]) {
inttwoD[ ] [ ]= new int[4][5];
inti, 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++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}}}
This program generates the
following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Thefollowingprogramnumberseachelementinthearrayfromlefttoright,topto
bottom,andthendisplaysthesevalues:

Summary
JavaisanObjectOrientedProgrammingLanguage.
Javaisatechnicallyblendedlanguagewhichhasarichelementsthatcanaddressanychanging
expectations.
Javaadoptsaconceptthatviewsverythingasanobjectandplacesanextraordinarydemands
ontheprograms.
Variablesarememorylocationstostorevalues.
Aclassisdefinedasblueprintfromwhichobjectsarecreated.
Castingisaninstructiontothecompilertoconvertonetypetoanother.
Separatorsarecharactersusedtoterminatestatements.
Arrayisacollectionofsimilartypesofelementsthathavecontiguousmemorylocation.
Javadoesnotsupportmulti-dimensionalarray

SubjectiveQuestions
1.Explainvariousdatatypes,keywordsandvariableswithan
exampleJavaprogram
2.WhatisanarrayinJava?Explainitstypeswithanexample.
3.Whatarelexicalissuesandexplainhowdoesithelpin
programimplementation?

•Brief description of activity
Activity
•Do an online study and prepare a presentation of
10-15 slides which describes the evolution of Java
from C++.
•You are required to:
•Differentiate between C++ and Java and list down
the secure features of Java when compared to C++.
•Pen down the strategies used in Java to make it
reliable and robust with a real time example.
Online Activity
(30 min)

•ThecompletereferenceJava-2:HerbertSchildt-5
th
edition-McGraw
Hillprofessional
•SAMSteachyourselfJava-2-RogersCedenheadandLeuraLemay-3
rd
edition–Pearson
e-References
Tags