37
Introduc)on to Java

Introduc)on to Java - University of California, Santa Cruz · PDF fileIntroduc)on to Java What is Java? ... – This line of code is used to write output to the ... • int cost =

  • Upload
    vukien

  • View
    215

  • Download
    1

Embed Size (px)

Citation preview

Introduc)ontoJava

WhatisJava?

•  JavaisanObject-OrientedProgrammingLanguage– Programminglanguage–avocabularyandsetofgramma)calrulesforinstruc)ngacomputerorcompu)ngdevicetoperformspecifictasks.ThespecifictasksareknownasaComputerProgram.

Acomputerprogram

•  Isasetofinstruc)onsthatperformsaspecifictaskwhenexecutedbyacomputer.

MakeandDrinkCoffeecoffeeMethod=frenchPress;grindBeans();boilWater();pourWaterOverBeans();wait(5);//waitfor5minutespourCoffeeInCup();while(coffeeS)llInCup()){drinkCoffee();

}

Whatcancomputersunderstand?

•  Acomputerprobablycouldn’tfollowtheinstruc)onswejustgaveformakingcoffee.

•  Differentcomputershavedifferentbasicopera)onstheycanperform,likeaddi)on,subtrac)on,printtext,openfile,etc.

•  Acompilerconvertsourprogramsintothethingsacomputercanunderstand.

CompilingandRunningPrograms

SourceCode(Javacode)

JavaByteCode

JavaVirtualMachine(JVM)

Sourcecodeiscompiled

BytecodeisexecutedbytheJVM

DownloadingJava

•  JDK(JavaDevelopmentKit)– AllowsyoutocompileandrunJavaprograms– Gotoh[p://www.oracle.com/technetwork/java/javase/downloads/index.htmlforlatestJDK

OpeningEclipse

•  EclipseisanIDE•  IDE–IntegratedDevelopmentEnvironment–wherewewriteandtestcode.

•  Thisiswherewe’llbewri)ngallofourJavaprograms.

•  Downloadinstruc)onsoncoursewebpage

Wri)ngaFirstProgram

public class HelloWorld{public static void main(String[] args){

System.out.println(“Hello World!”);}

}

HelloWorld!

Output:

Wri)ngaFirstProgram

public class HelloWorld{public static void main(String[] args){

System.out.println(“Hello World!”);}

}

ClassDeclara)on

Mainmethoddeclara)on Bodyofmainmethod

ProgramAnatomy

•  Classdeclara)on– public class HelloWorld– Everyjavafilewillneedaclassdeclara)on.The“publicclass”partwillalwaysneedtobethesame,buttheHelloWorldpartwillbenamedbyyou.

•  Mainmethoddeclara)on– Youwillbememorizingthisline.Itwillalwaysbethesame.

•  Bodyofmainmethod– Allthelinesofcodewe’retryingtorun.

ProgramAnatomy

•  Someothercomponentsofourprogram:– CurlyBraces–{}

•  Everycurlybracethatopens,alsoneedstobeclosed•  Curlybraceswillaccompanytheclass,andmethods,(andotherswe’llgettolater)

– Semi-colon–;•  Everylineofcodemustendwithasemi-colon

ProgramAnatomypublic class HelloWorld{

public static void main(String[] args){System.out.println(“Hello World!”);

}}

Curlybraces

Semicolon

Syntax–thesetofrulesthatdefinesthecombina)onsofsymbolsthatareconsideredtobeacorrectlystructureddocumentorfragmentinthatlanguage.Syntaxreferstothespellingandgrammarofaprogramminglanguage.

Wri)ngaFirstProgram

•  System.out.println();– Thislineofcodeisusedtowriteoutputtotheconsole

– The“ln”suffixtellsustherewillbeanewlineafertheoutputhasbeenprinted

System.out.println(“First line”);System.out.println(“Second line”);System.out.println(“Third line”);

FirstlineSecondlineThirdline

Output:

Wri)ngaFirstProgram

•  System.out.print();– UnlikeSystem.out.println(),thislineofcodewillnotgotothenextline

System.out.print(“First”);System.out.print(“Second”);System.out.print(“Third”);

FirstSecondThirdOutput:

CommentsandWhitespace

•  Acommentistextaddedtocodebyaprogrammer,intendedtobereadbyhumanstobe[erunderstandthecode,butignoredbythecompiler.– Single-linecomment:Commentconsis)ngofoneline

– Mul)-linecomment:Commentconsis)ngofmorethanoneline

•  Whitespaceisusedtoputspaceinbetweencodetomakeitmorereadable

Commentspublic class CommentDemo{

public static void main(String[] args){System.out.println(“This program demos two

types of comments”);// This is a single line comment

/* This commentspans multiplelines

*/}

}

Variables

•  Avariablestoresavalue;wecanchangeandusethevalue.– Forexample,wecreateavariabletostorethecostofacomputer•  int cost = 600;•  Thevariablecosthasbeendeclaredandini)alized•  Theintmeansthisvariablecanonlystoreintegers

– Wechangethecostofthecomputerto500•  cost = 500;•  Thevariablecosthasbeenassignedanewvalue

Variables

•  Variablerules:– Mustconsistofle[ers(a-z,A-Z,_,$)anddigits(0-9)

– Muststartwithale[er– Can’tbeareservedword

•  Reservedwordsarelistedattheendofsec)on2.3– Makeitdescrip.ve!

Variables

•  Giveadescrip)venametoyourvariable.

int x = 0;int balance = 0;

xdoesn’tgivemuchdescrip)onaboutwhattypeofinforma)onisbeingstored

balancewouldbemoredescrip)ve

VariablesExampleVariableName Valid?

grade Yes

_grade_ Yes

$grade$ Yes(butbad)

=grade No

grade3 Yes

GRADE Yes

class No

Class Yes(butbad)

a_long_variable_name Yes

aLongVariableName Yes

“alongvariablename” No

Primi)veDataTypesDataType Bits Descrip.on Example

byte 8 -27to27 238

short 16 -215to215

int 32 -231to231

long 64 -263to263

float 32 coefficientof23bits,exponentof8bits

3.14159265359

double 64 coefficientof53bits,exponentof11bits

char 16 ASCIIcharacters ‘A’,‘!’,‘9’

boolean 1 Trueorfalsevalue True,false

VariousVariableIni)aliza)ons// declare multiple variablesint time, date, year;

// declare and initialize multiple variablesint time=1245, date=1002, year=2017;

// declare some variables, declare and initialize othersint time=1330, date=929, year;

StringDataType

•  Notquiteaprimi)vedatatype,butofen)mesusedlikeone.

Constants// constants can’t be changedfinal double BOILING_TEMP = 212.0;final double HUMAN_TEMP = 98.6;

Arithme)cExpressionsArithme.coperator Descrip.on

+ Addi)on

- Subtrac)on

* Mul)plica)on

/ Division

% Modulo

Modulo

•  Givestheremainderofdivision– Recallthatintegerdivisiononlyresultsinquo)ent

4%6=410%6=412%6=07%5=29%5=4

TypeConversion•  Implicitconversion–happensautoma)cally– Nolossofprecision

•  Examples:

•  Asageneralrule,lowertypesareconvertedtohighertypes–  int<long<float<double

int num1 double num2 Expression Result

5 2.0 num1*num2 10.0

5 2.0 num1/num2 2.5

TypeCas)ng

•  Thisisforcedtypeconversiondouble numerator = 5.0;int denominator = 2;

// the variable expression below evaluates to 2, an intint expression = (int)numerator/denominator;

//----------------------------------------------------------

int numerator2 = 5;int denominator2 = 2;

// the variable experssion2 below evaluates to 2.5, a doubledouble expression2 = (double)numerator2/denominator;

BasicInputimport java.util.Scanner;public class ScannerTest {

public static void main(String[] args){Scanner keyboard = new Scanner(System.in);System.out.println(“Please enter a number

between 1 and 10”);int x = keyboard.nextInt();System.out.println(x);

}} Thisprogramprintsamessagetotheuser“Pleaseenteranumber

between1and10”,thentakeswhatevertheuserentersandassignsittothevariablex

ConversionMethodswithScannerClass

next() String

nextInt() int

nextLong() long

nextFloat() float

nextDouble() double

nextBoolean() boolean

nextLine() String

Ge|ngasinglecharacter

•  UsecharAtmethodwhichbelongstotheStringclass

String user = “Guest User”;System.out.println(user.charAt(0));System.out.println(user.charAt(2));System.out.println(user.charAt(4));

Whatisamethod?

•  Method–anamedcollec)onofinstruc)ons– Methodcalls– Methoddefini)ons

•  Sta)cmethods–  ClassName.methodName(…arguments…)

•  Instancemethods–  instanceOfClass.methodName(…arguments…)

MathMethods

•  Noimportstatementrequired(java.langlibraryisincludedbydefault)

Math.sqrt(x) – evaluates to squareroot of xMath.pow(x,y) – evaluates to xy

Math.round(x) – x rounded to the nearest intMath.random() – random double between 0 and 1

Math.PI – the value of pi as a doubleMath.E – the value of e as a double

Errorsandwarnings

•  Codeneedstobewri[enperfectly,otherwiseyouwillgetasyntaxerror– SomeExamples:

•  Forge|ngsemicolon•  Forge|ngcurlybrace•  Misspellingreservedwords

Errorsandwarnings// How many errors can you find in this program?

/ This program prints a message about Santa Cruzpublic class Errors{

public static void main(String[] args){System.out.print(“Santa Cruz );System.out.println(“is the real “)System.out.println(“Surf City”);

}

A.  0B.  1C.  2D.  3E.  4

RunningaProgramattheCommandLine

javac HelloWorld.javajava HelloWorld

Compilestheprogramandgeneratesa.classfile.Ifyouhaveerrors,theywillbediscoveredhere.

Runstheprogrambyexecu)ngthe.classfile.