Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 22

IntroductiontoJava

CS331

Introduction
PresentthesyntaxofJava
IntroducetheJavaAPI
Demonstratehowtobuild
standaloneJavaprograms
Javaapplets,whichrunwithinbrowserse.g.
Netscape

Exampleprograms

WhyJava?
Itsthecurrenthotlanguage
Itsalmostentirelyobjectoriented
Ithasavastlibraryofpredefinedobjectsand
operations
Itsmoreplatformindependent
thismakesitgreatforWebprogramming

Itsmoresecure
ItisntC++

Applets,Servletsand
Applications
Anappletisdesignedtobeembeddedina
Webpage,andrunbyabrowser
Appletsruninasandboxwithnumerous
restrictions;forexample,theycantread
filesandthenusethenetwork
Aservletisdesignedtoberunbyaweb
server
Anapplicationisaconventionalprogram

BuildingStandaloneJAVA
Programs(onUNIX)

Preparethefilefoo.javausinganeditor
Invokethecompiler:javac foo.java
Thiscreatesfoo.class
Runthejavainterpreter:java foo

JavaVirtualMachine
The.classfilesgeneratedbythecompilerare
notexecutablebinaries
soJavacombinescompilationandinterpretation

Instead,theycontainbytecodestobe
executedbytheJavaVirtualMachine
otherlanguageshavedonethis,e.g.UCSDPascal

Thisapproachprovidesplatform
independence,andgreatersecurity

HelloWorld(standalone)
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

NotethatStringisbuiltin
printlnisamemberfunctionforthe
System.outclass

CommentsarealmostlikeC++
/*Thiskindofcommentcanspanmultiplelines
*/
//Thiskindistotheendoftheline
/**
*Thiskindofcommentisaspecial
*javadocstylecomment
*/

PrimitivedatatypesarelikeC
Maindatatypesareint,double,
boolean,char
Alsohavebyte,short,long,float
boolean hasvalues trueand false
DeclarationslooklikeC,forexample,
doublex,y;
intcount=0;

ExpressionsarelikeC
AssignmentstatementsmostlylooklikethoseinC;you
canuse=,+=,*=etc.
Arithmeticusesthefamiliar+ - * / %
Javaalsohas++ and
Javahasbooleanoperators&& || !
Javahascomparisons< <= == != >= >
Javadoesnothavepointersorpointerarithmetic

ControlstatementsarelikeC
if(x<y)smaller=x;
if(x<y){smaller=x;sum+=x;}
else{smaller=y;sum+=y;}
while(x<y){y=yx;}
do{y=yx;}while(x<y)
for(inti=0;i<max;i++)
sum+=i;

BUT:conditionsmustbe boolean!

ControlstatementsII
switch(n+1){
case0:m=n1;break;
case1:m=n+1;
case3:m=m*n;break;
default:m=n;break;
}

Javaalsointroducesthetrystatement,
aboutwhichmorelater

Javaisn'tC!

InC,almosteverythingisinfunctions
InJava,almosteverythingisinclasses
Thereisoftenonlyoneclassperfile
Theremustbeonlyonepublicclassperfile
Thefilenamemustbethesameasthename
ofthatpublicclass,butwitha.java
extension

Javaprogramlayout
AtypicalJavafilelookslike:
importjava.awt.*;
importjava.util.*;
publicclassSomethingOrOther{
//objectdefinitionsgohere
...
}
This must be in a file named SomethingOrOther.java !

Whatisaclass?
Earlylanguageshadonlyarrays
allelementshadtobeofthesametype

Thenlanguagesintroducedstructures(called
records,orstructs)
alloweddifferentdatatypestobegrouped

ThenAbstractDataTypes(ADTs)became
popular
groupedoperationsalongwiththedata

So,whatisaclass?
Aclassconsistsof
acollectionoffields,orvariables,verymuch
likethenamedfieldsofastruct
alltheoperations(calledmethods)thatcanbe
performedonthosefields
canbeinstantiated

Aclassdescribesobjectsandoperations
definedonthoseobjects

Nameconventions
Javaiscasesensitive;maxval,maxVal,and
MaxValarethreedifferentnames
Classnamesbeginwithacapitalletter
Allothernamesbeginwithalowercaseletter
Subsequentwordsarecapitalized:theBigOne
Underscoresarenotusedinnames
Theseareverystrongconventions!

Theclasshierarchy
Classesarearrangedinahierarchy
Theroot,ortopmost,classisObject
EveryclassbutObjecthasatleastone
superclass
Aclassmayhavesubclasses
Eachclassinheritsallthefieldsandmethods
ofits(possiblynumerous)superclasses

Anexampleofaclass
classPerson{
Stringname;
intage;
voidbirthday(){
age++;
System.out.println(name+'is
now'+age);
}
}

Anotherexampleofaclass
classDriverextendsPerson{
longdriversLicenseNumber;
DateexpirationDate;
}

Creatingandusinganobject
Personjohn;
john=newPerson();
john.name="JohnSmith";
john.age=37;
Personmary=newPerson();
mary.name="MaryBrown";
mary.age=33;
mary.birthday();

Anarrayisanobject
Personmary=newPerson();
intmyArray[]=newint[5];
or:

intmyArray[]={1,4,9,16,
25};
Stringlanguages[]=
{"Prolog","Java"};

You might also like