introduction to java

142
Java Origins Computer language innovation and development occurs for two fundamental reasons: 1) to adapt to changing environments and uses 2)to implement improvements in the art of programming The development of Java was driven by both in equal measures. Many Java features are inherited from the earlier languages: •B C C++ Java 1

Upload: aabid-ali-khan

Post on 16-Aug-2015

223 views

Category:

Documents


3 download

TRANSCRIPT

Java OriginsComputerlanguageinnovationanddevelopment occurs for two fundamental reasons:1) to adapt to changing environments and uses2)toimplementimprovementsintheartof programmingThedevelopmentofJavawasdrivenbybothinequal measures.anyJavafeaturesareinheritedfromtheearlier languages:!CC"" Java1Before Java: C#esigned by #ennis $itchie in 1%&'s.!eforeC(therewasnolanguagetoreconcile:ease)of)useversuspower(safetyversusefficiency(rigidity versus e*tensibility.!+,-C(C.!./(0.$T$+1(2+,C+/optimi3ed one set of traits( but not the other.C)structured(efficient(high)levellanguagethat couldreplaceassemblycodewhencreatingsystems programs.#esigned(implementedandtestedbyprogrammers( not scientists.2Before Java: C++#esigned by !4arne ,troustrup in 1%&%.$esponse to the increased comple*ity of programs and respective improvements in the programming paradigms and methods:1) assembler languages2) high)level languages5) structured programming6) ob4ect)oriented programming 7..2)..28methodologythathelpsorgani3ecomple*programs through the use of inheritance( encapsulation and polymorphism.C"" e*tends C by adding ob4ect)oriented features.3Java History#esignedbyJames9osling(2atric:1aughton(Chris;arth( -nternet version of C""?@ 1o.Java was not designed to replace C""( but to solve a different setofproblems.TherearesignificantpracticalAphilosophical differences.4Java TechnologyThere is more to Java than the language.Java Technology consists of:1) Java 2rogramming /anguage2) Java Birtual achine 7JB)5) Java +pplication 2rogramming -nterfaces 7+2-s)5Java Language Features1) simple2) object-oriented3) robust4) multithreaded5) architecture-neutral6) interpreted and high-performance7) distributed8) dynamic9) secure6Java Language Features1)simple8Javaisdesignedtobeeasyforthe professional programmer to learn and use.2)ob4ect)oriented8aclean(usable(pragmatic approachtoob4ects(notrestrictedbytheneedfor compatibility with other languages.5)robust8restrictstheprogrammertofindthe mista:esearly(performscompile)time7strong typing)andrun)time7e*ception)handling)chec:s( manages memory automatically.7Java Language Features 6) multithreaded 8 supports multi)threaded programming for writing program that perform concurrent computationsC)architecture)neutral8JavaBirtualachineprovidesa platform independent environment for the e*ecutionof Java bytecodeD)interpretedandhigh)performance8Javaprogramsare compiled into an intermediate representation 8bytecode:a) can be later interpreted by any JBb)canbealsotranslatedintothenativemachinecodefor efficiency.8Java Language Features&)distributed8JavahandlesTC2A-2protocols( accessingaresourcethroughits=$/much li:e accessing a local file.E)dynamic8substantialamountsofrun)time typeinformationtoverifyandresolve access to ob4ects at run)time.%)secure8programsareconfinedtotheJava e*ecutionenvironmentandcannotaccess other parts of the computer.9Execution Platform;hat is an e*ecution platform@1) +n e*ecution platform is the hardware orsoftware environmentinwhichaprogramruns(e.g. ;indows 2'''( /inu*( ,olaris orac.,.2)ostplatformscanbedescribedasa combination of the operating system andhardware.10Java Execution Platform;hat is Java 2latform@1) + software)only platform that runs on top of other hardware)based platforms.2) Java 2latform has two components:a)JavaBirtualachine7JB)8interpretation fortheJavabytecode(portedontovarious hardware)based platforms.b)TheJava+pplication2rogramming-nterface 7Java +2-)11Java Platform n!e"en!ence12Java Program ExecutionJava programs are both compiled and interpreted:,teps:F write the Java programF compile the program into bytecodeFe*ecute7interpret)thebytecodeonthecomputer through the Java Birtual achineCompilation happens once.-nterpretationoccurseachtimetheprogramis e*ecuted.13Java Execution Process14Java #P;hat is Java +2-@1)alargecollectionofready)madesoftware componentsthatprovidemanyusefulcapabilities( e.g. graphical user interface2)groupedintolibraries7pac:ages)ofrelated classes and interfaces5)togetherwithJBinsulatesJavaprograms fromthehardwareandoperatingsystem variations15Java Program Ty"esTypes of Java programs:1) applications 8 standalone 7des:top) Java programs( e*ecutedfromthecommandline(onlyneedthe Java Birtual achine to run2)applets8JavaprogramthatrunswithinaJava)enabledbrowser(invo:edthrougha>applet? reference on a web page( dynamicallydownloaded to the client computer5)servlets8Javaprogramrunningontheweb server(capableofrespondingtoGTT2requests made through the networ:16$im"le Java Program+ class to display a simple message:class y2rogram Hpublic static void main7,tring args IJ) H,ystem.out.println7>0irst Java program.K)LMM17Running the ProgramType the program( save as y2rogram.4ava.-n the command line( type:N diry2rogram.4avaN 4avac y2rogram.4avaN diry2rogram.4ava( y2rogram.classN 4ava y2rogram0irst Java program.18Ex"laining the Process1) creating a source file ) a source file contains te*t written in the Javaprogramminglanguage(createdusinganyte*teditoron any system.2)compilingthesourcefile)Javacompiler74avac)readsthe source file and translates its te*t into instructions that the Java interpretercanunderstand.Theseinstructionsarecalled bytecode.5)runningthecompiledprogram)Javainterpreter74ava) installedta:esasinputthebytecodefileandcarriesoutits instructions by translating them on the fly into instructions that your computer can understand.19Java Program Ex"laine!y2rogram is the name of the class:class y2rogram Hmain is the method with one parameter args and no results:public static void main7,tringIJ args) Hprintln is a method in the standard ,ystem class:,ystem.out.println7>0irst Java program.K)LMM20Classes an! O%&ects+ class is the basic building bloc: of Java programs.+ class encapsulates:a) data 7attributes) andb) operations on this data 7methods)and permits to create ob4ects as its instances.21'ain 'etho!The main method must be present in every Java application:1)public static void main7,tringIJ args) where:a)public means that the method can be called by any ob4ectb)static means that the method is shared by all instancesc)void means that the method does not return any value2);hentheinterpretere*ecutesanapplication(itstartsby callingitsmainmethodwhichinturninvo:esothermethods in this or other classes.5)Themainmethodacceptsasingleargument8astringarray( which holds all command)line parameters.22Exercise: Java Program1) 2ersonali3e they2rogramprogram with your name so that it tells you>Gello( my name is O?2) ;rite a program that produces the following output:;elcome to 0irst Java 2rogramP)LMMTheprogramhassomeerrors.0i*theerrorssothattheprogram successfully compiles and runs. ;hat were the errors@ 23Java $yntax.n the most basic level( Java programs consist of:a) whitespacesb) identifiersc) commentsd) literalse) separatorsf) :eywordsg) operators/? 7e.g. 125/) are of type long.31Literals: Floating)Point Ty"esTwo notations:1) standard 8 2'''.C2) scientific 8 2.'''C0? 7e.g. 2.'''Cglobal? scope2) variables defined by a method have a >local? scope;e consider the scope of method variables onlyL class variables will be considered later.743aria%le $co"e75$co"e 1efinition+ scope is defined by a bloc::HOM+ variable declared inside the scope is not visible outside:Hint nLMn Y 1L76Exam"le: 3aria%le $co"eclass ,cope Hpublic static void main7,tring argsIJ) Hint *L* Y 1'Lif 7* YY 1') Hint y Y 2'L ,ystem.out.println7K* and y: K " * " >K " y)L* Y y S 2LM,ystem.out.println7K* is K " * " >y is? " y)LMM773aria%le LifetimeBariablesarecreatedwhentheirscopeisenteredby control flow and destroyed when their scope is left:1)+variabledeclaredinamethodwillnotholdits value between different invocations of this method.2) + variabledeclaredinabloc:loosesitsvaluewhen the bloc: is left.5) -nitiali3ed in a bloc:( a variable will be re)initiali3ed with every re)entry.Bariable5s lifetime is confined to its scopeP78Exam"le: 3aria%le Lifetimeclass LifeTime {public static void main(String args[]) {int x;for (x = 0; x < 3; x++) {int y = -1;System.out.println("y is: " + y);y = 100;System.out.println("y is now: " + y);}}}79Ty"e 1ifferences,uppose a value of one type is assigned to a variable of another type.T1 t1LT2 t2 Y t1L;hat happens@ #ifferent situations:1) types T1 and T2 are incompatible2) types T1 and T2 are compatible:a) T1 and T2 are the sameb) T1 is larger than T2c) T2 is larger than T180Ty"e Com"ati%ility;hen types are compatible:1)integertypesandfloating)pointtypesarecompatible with each other2) numeric types are not compatible with char or boolean5) char and boolean are not compatible with each other a is ) ve numK)LMMM964este! if $tatement+ nestedifisanifstatementthatisthetarget of another if or else. 1ested ifs are verycommon in programming. ;hen you nest ifs( the main thing to remember isthatanelsestatementalwaysreferstothe nearestifstatementthatiswithinthesame bloc:astheelseandthatisnotalready associated with an else.974este! if $tatementclass i is : > " i)LM-tispossibletoinitiali3emultiplevariableinthe initiali3ation bloc: of the for loop by separating it by commaasgiveninthebelowe*ample.0or7iY'(4YCLi^CLi"")-t is also possible to have more than one increment or decrementsectionaswellasgivenbelow.for7int iY'L i ^ C L i""( 4)))112The /hile Loo"The general form of the while loop iswhile7condition) HstatementLMThe condition can be any!oolean e*pression. The body of the loop will be e*ecuted as long as the conditional e*pression is true. ;henconditionbecomesfalse(controlpasses to the ne*t line of code immediately following the loop. Thecurlybracesareunnecessaryifonlya single statement is being repeated.113The /hile Loo"114The /hile Loo"class ;hile Hpublic static void main7,tring argsIJ) Hint n Y 1'Lwhile7n N ') H,ystem.out.println7Ktic: K " n)Ln))LMMM115!o)/hile Loo"general form isdo HAA body of loopM while 7condition)Lgoto?statement( whichtendstoproducecodethatishardto understand and maintain.Gowever(insomeplaces(theuseofgotosiswell 4ustified.-nparticular(whenbrea:ingoutfromthe deeply nested bloc:s of code.brea: occurs in two versions:1) unlabelled2) labeledThelabeledbrea:statementisa>civili3ed? replacement for goto.124La%ele! %rea*9eneral form:brea: labelLwherelabelisthenameofalabelthat identifies a bloc: of code:label: H O MTheeffectofe*ecutingbrea:labelListo transfer control immediately after the bloc: of code identified by label.125Exam"le: La%ele! %rea*class !rea: Hpublic static void main7,tring argsIJ) Hboolean t Y trueLfirst: H second: Hthird: H,ystem.out.println7K!efore the brea:.K)Lif 7t) brea: secondL,ystem.out.println7KThis won\t e*ecuteK)LM,ystem.out.println7KThis won\t e*ecuteK)L M,ystem.out.println7>+fter second bloc:.K)LMM M126Exam"le: 4este! Loo" %rea*class 1ested/oop!rea: H public static void main7,tring argsIJ) Houter: for 7int iY'L i^5L i"") H,ystem.out.print7K2ass K " i " K: K)L for 7int 4Y'L 4^1''L 4"") Hif 74 YY 1') brea: outerL AA e*it both loops,ystem.out.print74 " K K)LM,ystem.out.println7KThis will not printK)LM,ystem.out.println7K/oops complete.K)LMM127%rea* (ithout La%el-t is not possible to brea: to any label which is not defined for an enclosing bloc:. Trying to do so will result in a compiler error.class !rea: