4
What is a Computer?
Acomputerisanelectronicdevicethattakesan
input,processitunderasetofinstructionscalled
programandproduceanoutputintheneedformat.
Ithasdifferentcomponentswhichhelpittoaccept
input,tostoretheinput,toprocesstheinputandto
displaytheoutputtotheuser.
5
Computerprograms,knownassoftware,are
instructionstothecomputer.
Youtellacomputerwhattodothroughprograms.
Withoutprograms,acomputerisanemptymachine.
Computersdonotunderstandhumanlanguages,so
youneedtousecomputerlanguagestocommunicate
withthem.
Programsarewrittenusingprogramminglanguages.
Computerprogramsareinstructionsthattella
computerwhattodo.
What is Computer Program?
6
Programminglanguagesarelanguagesthat
programmersusetowritecode/programtoinstructa
computer.
Theyarelanguagesdesignedforprogramminga
computer.
Computersdonotunderstandhumanlanguages,so
programsmustbewritteninalanguageacomputer
canuse.
Therearehundredsofprogramminglanguages,and
theyweredevelopedtomaketheprogramming
processeasierforpeople.
Programminglanguagesareclassifiedintothree
categories.Machine,AssemblyandHigh-LevelLanguage
What is ProgrammingLanguages?
7
What is ProgrammingLanguages?
Machine Language
Machinelanguageisasetofprimitiveinstructions
builtintoeverycomputer.
Theinstructionsareintheformofbinarycode,so
youhavetoenterbinarycodesforvariousinstructions.
Programwithnativemachinelanguageisatedious
process.
Moreovertheprogramsarehighlydifficulttoread
andmodify.
Forexample,toaddtwonumbers,youmightwritean
instructioninbinarylikethis:
1101101010011010
8
What is ProgrammingLanguages?
Assembly Language
Programminginmachinelanguageisatediousprocess.
Moreover,programswritteninmachinelanguagearevery
difficulttoreadandmodify.
Forthisreason,assemblylanguagewascreatedintheearly
daysofcomputingasanalternativetomachinelanguages.
Assemblylanguageusesashortdescriptiveword,knownasa
mnemonic,torepresenteachofthemachine-language
instructions.
Forexample,themnemonicADDtypicallymeanstoadd
numbersandSUBmeanstosubtractnumbers.
Toaddthenumbers2and3andgettheresult,youmight
writeaninstructioninassemblycodelikethis:add2,3,result
9
What is ProgrammingLanguages?
Assembly Language
Assemblylanguagesweredevelopedtomakeprogramming
easy.
Sincethecomputercannotunderstandassemblylanguage,
however,aprogramcalledassemblerisusedtoconvertassembly
languageprogramsintomachinecode,asshowninthefollowing
Figure.
Forexample,toaddtwonumbers,youmightwritean
instructioninassemblycodelikethis:
ADD2,3,result
10
What is ProgrammingLanguages?
Assembly Language
Writingcodeinassemblylanguageiseasierthaninmachine
language.
However,itisstilltedioustowritecodeinassemblylanguage.
WritinginassemblyrequiresthatyouknowhowtheCPU
works.
Assemblylanguageisreferredtoasalow-levellanguage,
becauseassemblylanguageiscloseinnaturetomachine
languageandismachinedependent.
11
What is ProgrammingLanguages?
High-Level Language
Theyareplatform-independent,whichmeansthat
youcanwriteaprograminahighlevellanguageand
runitindifferenttypesofmachines.
Thehigh-levellanguagesareEnglish-likeandeasyto
learnandprogram.
Theinstructionsinahigh-levelprogramming
languagearecalledstatements.
Forexample,thefollowingisahigh-levellanguage
statementthatcomputestheareaofacirclewith
radius5:area=5*5*3.1415;
12
What is ProgrammingLanguages?
High-Level Language
Therearemanyhigh-levelprogramminglanguages,
andeachwasdesignedforaspecificpurpose.
SomepopularonesareC,C++,C#,VIBandJava.
ButforthiscourseJavaisourfocus.
Aprogramwritteninahigh-levellanguageiscalleda
sourceprogramorsourcecode.
Becauseacomputercannotunderstandasource
program,asourceprogrammustbetranslatedinto
machinecodeforexecution.
13
What is ProgrammingLanguages?
High-Level Language
Thetranslationcanbedoneusinganother
programmingtoolcalledaninterpreteroracompiler.
Aninterpreterreadsonestatementfromthesource
code,translatesittothemachinecodeorvirtual
machinecode,andthenexecutesitrightaway,as
showninthefollowingfigure.
14
What is ProgrammingLanguages?
High-Level Language
Acompilertranslatestheentiresourcecodeintoa
machine-codefile,andthemachine-codefileisthen
executed,asshowninfigurebelow.
Thedifferencebetweencompilingandinterpretingisthat
compilingtranslatesthehigh-levelcodeintoatargetlanguage
codeasasingleunitand
Interpretingtranslatestheindividualstepsinahigh-level
programoneatatimeratherthanthewholeprogramasasingle
unit.Eachstepisexecutedimmediatelyafteritistranslated.
15
What is Programming Paradigm?
Solvingaprogrammingproblemrequireschoosing
therightconcepts.
Allbutthesmallesttoyproblemsrequiredifferent
setsofconceptsfordifferentparts.
Thisiswhyprogramminglanguagesshouldsupport
manyparadigms.
Aparadigmisawayofdoingsomething(like
programming).
Aprogrammingparadigmisastyleor“way”of
programming.or
ProgrammingParadigmsisawaytoclassify,
programminglanguages,accordingtostylesof
computerprogramming.
16
What is Programming Paradigm?
Featuresofvariousprogramminglanguages
determinewhichprogrammingparadigmstheybelong
to.
Someprogramminglanguagesfallintoonlyone
paradigm,whileothersfallintomultipleparadigms.
Eachparadigmsupportsasetofconceptsthatmakes
itthebestforacertainkindofproblem.
Forexample,object-orientedprogrammingisbestfor
problemswithalargenumberofrelateddata
abstractionsorganizedinahierarchy.
17
Some Major Types of Programming Paradigms
1.Imperative or procedural
2.Declarative
3.Logical or Rule based
4.Functional
5.Object-Oriented
Itisbasedoncommandsthat
updatevariablesinstorage.
Controlflowisanexplicit
sequenceofcommands.
Commandsshowhowthe
computationtakesplace,stepby
step.
Eachstepaffectstheglobalstate
ofthecomputation.
SomeprogrammingLanguages
usedinthisparadigmareFortran,
Pascal,Basic,Cetc
18
Some Major Types of Programming Paradigms
1.Imperative or procedural
2.Declarative
3.Logical or Rule based
4.Functional
5.Object-Oriented
Controlflowindeclarative
programmingisimplicit:the
programmerstatesonlywhatthe
resultshouldlooklike,nothowto
obtainit.
Programsstatetheresultyou
want,nothowtogetit.
19
Some Major Types of Programming Paradigms
1.Imperative or procedural
2.Declarative
3.Logical or Rule based
4.Functional
5.Object-Oriented
LogicProgrammingisa
programmingparadigmbasedon
formallogic.
Itisasetofsentencesinlogical
form,expressingfactsandrules
aboutsomeproblemdomain.
Majorlogicprogramming
languagefamiliesincludePROLOG,
ASPandDATALOG.
20
Some Major Types of Programming Paradigms
1.Imperative or procedural
2.Declarative
3.Logical or Rule based
4.Functional
5.Object-Oriented
Inthisparadigmweexpress
computationsastheevaluationof
mathematicalfunctions.
Thereasonisthattheparadigm
originatesfromapurelymathematical
discipline:thetheoryoffunctions.
Infunctionalprogrammingcontrol
flowisexpressedbycombining
functioncalls,ratherthanbyassigning
valuestovariables.
21
Some Major Types of Programming Paradigms
1.Imperative or procedural
2.Declarative
3.Logical or Rule based
4.Functional
5.Object-Oriented
Theobject-orientedparadigmhas
gotgreatpopularityintherecent
years.
Object-OrientedProgrammingisa
programmingparadigmbasedonthe
conceptof“Objects”,whichmay
containdata,intheformoffields,
oftenknownasAttributes;andcode,
intheformofMethods.
Thesepropertiesareveryimportant
whenprogramsbecomelargerand
larger.
Java,C++,C#,pythonaresome
examples of object-oriented
programminglanguages
22
What is Java Programming Language?
Javaisapowerfulandversatileprogramming
languagefordevelopingsoftwarerunningonmobile
devices,desktopcomputers,andservers.
JavaprogramminglanguageisanObject-Oriented
generalpurposeprogramminglanguagethathasa
syntaxsimilartothatofC/C++.
Itisdesignedtobepowerfulandsimpleby
avoidingtheoverlycomplexfeaturesthathave
boggeddownotherOOLs,suchasC++.
Astheresult,thejavalanguagehasprovedvery
muchpopularwithprogrammers.
23
What is Java Programming Language?
Javaenablesuserstodevelopanddeploy
applicationsontheInternetforservers,desktop
computers,andsmallhand-helddevices.
Thefutureofcomputingisbeingprofoundly
influencedbytheInternet,andJavapromisesto
remainabigpartofthatfuture.
Hence,JavaistheInternetprogramminglanguage.
24
Java can be used to develop:
a)Applications
Some Uses of Java Programming Language
Anapplicationisaprogram
thatrunsonyourcomputer,
undertheoperatingsystemof
thatcomputer.Anapplication
createdbyJavaismoreorless
likeonecreatedusinganyother
typeofcomputerlanguage,
suchasVisualBasicorC++.
Javaapplicationsdo
havethemain()as
memberoftheirclass
Java is a general purpose
programming language.
Youcanuseittodevelop
applicationsonyourdesktopandon
theserver.
Youcanalsouseittodevelop
applicationsforsmallhand-held
devices,suchaspersonaldigital
assistants(PDA)andcellphones.
E.g.,ThefollowingpicturesshowsaJava
programthatdisplaysthecalendarona
BlackBerry
®
andonacellphone.
26
b) Server-side applications
Java server pages (JSP)
Java Servlets
Java Server Face (JSF)
Java Beans, etc.
c)Multimedia application
Java Graphics, Java Graphics 2D, etc.
d) Etc…
Some Uses of Java …
27
Key Features of Java Technology
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Nolanguageissimple,butJavais
abiteasierthanthepopular
object-orientedprogramming
languageC++,whichwasthe
dominantsoftware-development
languagebeforeJava.
JavaispartiallymodeledonC++,
butgreatlysimplifiedand
improved.
28
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Javaisinherentlyobject-oriented.
Althoughmany object-oriented
languagesbeganstrictlyasprocedural
languages,Javawasdesignedfromthe
starttobeobject-oriented.
Object-orientedprogramming(OOP)is
apopularprogrammingapproachthat
isreplacingtraditionalprocedural
programmingtechniques.
Oneofthecentralissuesinsoftware
developmentishowtoreusecode.
Object-orientedprogrammingprovides
greatflexibility,modularity,clarity,and
reusabilitythroughencapsulation,
inheritance,andpolymorphism.
29
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Distributedcomputinginvolvesseveral
computersworkingtogetherona
network.Javaisdesignedtomake
distributedcomputingeasy.
Sincenetworkingcapabilityisinherently
integratedintoJava,writingnetwork
programsislikesendingandreceiving
datatoandfromafile.
30
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
YouneedaninterpretertorunJava
programs.Theprogramsarecompiled
intotheJavaVirtualMachinecode
calledbytecode.
Thebytecodeismachine-independent
andcanrunonanymachinethathasa
Javainterpreter,whichispartofthe
JavaVirtualMachine(JVM).
31
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
JavaIs Interpreted
JavaIsRobust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Robustmeansreliable.
Javacompilerscandetectmany
problemsthatwouldfirstshowupat
executiontimeinotherlanguages.
Javahaseliminatedcertaintypesof
error-proneprogrammingconstructs
foundinotherlanguages.
Javahasaruntimeexception-handling
featuretoprovideprogramming
supportforrobustness.
32
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
JavaIs Interpreted
Java Is Robust
JavaIsSecure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Javaimplementsseveralsecurity
mechanismstoprotectyoursystem
againstharmcausedbystrayprograms.
33
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
JavaIs Interpreted
Java Is Robust
Java Is Secure
JavaIs Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Architectural-Neutral means
platform-independent.
With a Java Virtual Machine
(JVM), you can write one program
that will run on any platform.
Write once, run anywhere.
34
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
JavaIs Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
BecauseJavaisarchitecture
neutral,Javaprogramsare
portable.
Theycanberunonanyplatform
withoutbeingrecompiled.
Thereisnoplatform-specific
featuresintheJavalanguage.
35
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
JavaIs Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Java’sperformanceissometimes
criticized.
BecauseJavaisarchitectureneutral,
Javaprogramsareportable.Theycan
berunonanyplatformwithout
beingrecompiled.
JavadevelopersdevelopedtheJava
HotSpotPerformanceEngine,which
includesacompilerforoptimizing
thefrequentlyusedcode.
TheHotSpotPerformanceEngine
canbepluggedintoaJVMto
dramaticallyboostitsperformance.
36
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
JavaIs Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Multithreadingisaprogram’scapability
toperformseveraltaskssimultaneously.
Multithreadprogrammingissmoothly
integratedinJava,whereasinother
languagesyouhavetocallprocedures
specifictotheoperatingsystemtoenable
multithreading.
37
Key Features of Java …
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
JavaIs Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java is Performance
Java Is Multithreaded
Java Is Dynamic
Javawasdesignedtoadapttoan
evolvingenvironment.
Newcodecanbeloadedonthefly
withoutrecompilation.
Thereisnoneedfordevelopersto
create,andforuserstoinstall,major
newsoftwareversions.
Newfeaturescanbeincorporated
transparentlyasneeded.
38
The Java Language Specification, API, JDK, and IDE
Computerlanguageshavestrictrulesofusage.Ifyoudonot
followtheruleswhenwritingaprogram,thecomputerwillbe
unabletounderstandit.
SunMicrosystems,theoriginatorofJava,intendstoretain
controlthelanguagefromlosingitsunifiedstandards:
TheJavalanguagespecificationandJavaAPIdefinethe
Javastandard.
oTheJavalanguagespecificationisatechnical
definitionofthelanguagethatincludesthesyntaxand
semanticsoftheJavaprogramminglanguage.
oTheapplicationprograminterface(API)contains
predefinedclassesandinterfacesfordevelopingJava
programs.
NB:ThefollowingpictureshowstheJavaAPIspecification.
Java API Specification
Version Number of Packages Number of classes
Java 1.0 8 212
Java 1.1 23 504
Java 1.2 59 1520
Java 1.3 77 1595
Java 1.4 103 2175
Java 1.5 131 2656
Java 1.6 203 3792
Java 1.7 209 4024
39
The Java Language Specification…
40
The Java Language Specification…
TherearethreeeditionsoftheJavaJDK:
Java2StandardEdition(J2SE)
Java2EnterpriseEdition(J2EE)
Java2MicroEdition(J2ME).
Javaisafull-fledgedandpowerfullanguagethatcanbeused
inmanyways.
•J2SEcanbeusedtodevelopclient-sidestandalone
applicationsorapplets.
•J2EEcanbeusedtodevelopserver-sideapplications,
suchasJavaservletsandJavaServerPages.
•J2MEcanbeusedtodevelopapplicationsformobile
devices,suchascellphones.
41
The Java Language Specification…
ThetwoprincipalproductsintheJavaplatformare:Java
DevelopmentKit(JDK)andJavaRuntimeEnvironment(JRE).
TheJDKisasupersetoftheJRE,andcontainseverything
thatisintheJRE,plustoolssuchasthecompilersand
debuggersnecessaryfordevelopingappletsand
applications.
oJavaPlatform=JDK(becauseJREissubsetofJDK)
oJRE=JVM+JavaPackagesofClasses(likeutil,math,
lang,awt,swingetc)+runtimelibraries.
NB:
If you have the JDK installed, you don’t need to install
the JRE separately to run any Java software.
JVM is platform dependent
42
The Java Language Specification…
IntegratedDevelopmentEnvironment(IDE)isprovidedbythe
JavadevelopmenttoolforrapidlydevelopingJavaprograms.
Editing,compiling,debugging,andonlinehelpareintegratedin
onegraphicaluserinterface.
Justentersourcecodeinonewindoworopenanexisting
fileinawindow,thenclickabutton,menuitem,orfunction
keytocompileandruntheprogram.
43
Java DevelopmentTools
Three major development tools are:
NetBeansOpen Source by Sun
Eclipse Open Source by IBM
JBuilderby Borland
Other useful tools are:
Code Warrior by Metrowerks
TextPadEditor
JCreatorLE
JEdit
JGrasp
BlueJ
DrJava
44
A Simple Java Program
A class is a templateused to create anobject.
Class is a named template or descriptor for a set of objects
that sharethe same attributes(data Field), behaviors(methods),
and relationships.
Every Java program must have at least one class.
A class is a construct that defines data and methods.
Each class has a name.
By convention, class names start with an uppercase letter.
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
45
Creating, Compiling, and Executing a Java Program
TheJavaprogramming-developmentprocessconsistsof
creating/modifyingsourcecode,compiling,andexecuting
programs.
Likeanyotherprogramminglanguage,Javahasitsown
syntax,andyouneedtowritecodethatobeysthesyntaxrules.
TheJavacompilerwillreportsyntaxerrorsifyourprogram
violatesthesyntaxrules.
Iftherearenosyntaxerrors,thecompilergeneratesa
bytecodefilewitha.classextension.
Thebytecodeissimilartomachineinstructionsbutis
architecture-neutralandcanrunonanyplatformthathasa
JVM.ThisisoneofJava'sprimaryadvantages:Javabytecode
canrunonavarietyofhardwareplatformsandoperating
systems.
46
Creating, Compiling and Executing ...
Thefollowingfiguredescribestheprocessofcreating,
compilingandexecutingaJavaprogram.
47
Creating, Compiling, and Executing ...
Source Code
Create/Modify Source Code
Compile Source Code
i.e., javac Welcome.java
Bytecode
Run Byteode
i.e., java Welcome
Result
If compilation errors
If runtime errors or incorrect result
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
…
Method Welcome()
0 aload_0
…
Saved on the disk
stored on the disk
Source code (developed by the programmer)
Byte code (generated by the compiler for JVM
to read and interpret, not for you to understand)
Java
Bytecodes
move locally
or through
network
Java
Source
(.java)
Java
Compiler
Java
Bytecode
(.class )
Java
Interpreter
Just in
Time
Compiler
Runtime System
Class
Loader
Bytecode
Verifier
Java
Class
Libraries
Operating System
Hardware
Java
Virtual
machine
Runtime
Environment
Compile-time
Environment
Java Environment/Life Cycle of Java Code