Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/01-java_fundamentals.pdf · 9/9/16...
Transcript of Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/01-java_fundamentals.pdf · 9/9/16...
9/9/16
1
Objec+ves• BasicsofJavaSyntax• Javafundamentals
Ø Primi+vedatatypesØ Sta+ctypingØ Arithme+coperatorsØ Rela+onaloperators
1Sept12,2016 Sprenkle-CSCI209
Review• Whatarequali+esofgoodsoOware?
• WhatisJava?Ø BenefitstousingJava?
• HowdoyoucompileaJavaprogram?Ø Howdoyourun/executeaJavaprogram?
2Purpose of questions?Sept12,2016 Sprenkle-CSCI209
9/9/16
2
Review:BenefitsofJava• Rapiddevelopmentofprograms
Ø Largelibraryofclasses,includingGUIs,Enterprise-levelapplica+ons,Webapplica+ons
• PortabilityØ Runprogramonmul+pleplaXormswithoutrecompiling
• Sta+cally-typedlanguageØ Compiling-findsomeerrorsbeforeexecu+on,performancebenefits
3Sept12,2016 Sprenkle-CSCI209
Review:JavaProgrammingLanguage• En+relyobject-oriented• SimilartoPython
4
Program.java
Wri[eninJavaProgrammingLanguage
Compiler
Program.class
Bytecode:machinecodeforavirtualCPU
javac
Step1:
Sept12,2016 Sprenkle-CSCI209
9/9/16
3
Review:JavaVirtualMachine
• SamebytecodeexecutesoneachplaXorm• Don’tneedtoprovidethesourcecode
5
Program.class
MacJVM
BytecodeWindowsJVM
UNIXJVM
…
CPU(machinecode)
Step2:
Sept12,2016 Sprenkle-CSCI209
JavaClassLibraries• Pre-definedclasses
Ø IncludedwithJavaDevelopmentKit(JDK)andJavaRun+meEnvironment(JRE)
Ø Viewtheavailableclassesonline:http://docs.oracle.com/javase/8/docs/api/
• SimilarinpurposetomodulesincludedwithPython
Sept9,2016 Sprenkle-CSCI209 6
9/9/16
4
SummaryofJavaPlaXormSE7.0
Sept9,2016 Sprenkle-CSCI209 7
Imagefromhttp://docs.oracle.com/javase/8/docs/index.html
BenefitsofJava• Rapiddevelopmentofprograms
Ø Largelibraryofclasses,includingGUIs,Enterprise-levelapplica+ons,Webapplica+ons
• PortabilityØ Runprogramonmul+pleplaXormswithoutrecompiling
• Sta+cally-typedlanguageØ Compiling:findsomeerrorsbeforeexecu+on!Ø Cangiveperformanceboostbydoingop+miza+ons
Sept9,2016 Sprenkle-CSCI209 8
9/9/16
5
Which‘Java’isthisclassabout?• Javaprogramminglanguage• Javaclasslibraries
• UsetheJVMbutwon’tlearnabouthowitworksØ Formoreinforma+on:http://docs.oracle.com/javase/specs/
Sept9,2016 Sprenkle-CSCI209 9
Aside:JavaScriptvsJava• JavaScriptisnotJava
Ø JavaScriptisascrip&nglanguage,primarilyembeddedinHTML,executedbyWebbrowsers
Sept9,2016 Sprenkle-CSCI209 10
WebBrowser
JavaScript
<script type="text/javascript">function myFunction() {
return ("Hello, have a nice day!")}</script></head><body><script type="text/javascript">
document.write(myFunction())</script>
9/9/16
6
JavaDevelopmentKit• JDK:JavaDevelopmentKit• SDK:SoOwareDevelopmentKit• FreefromOracle• Contains
Ø javac:JavacompilerØ java:JavaVirtualMachineØ Javaclasslibraries
Sept9,2016 Sprenkle-CSCI209 11
http://www.oracle.com/technetwork/java/javase/downloads/index.html
PythonReview
12
# a Python programdef main():
print("Hello")
main()
What does this program do?
Sept12,2016 Sprenkle-CSCI209
9/9/16
7
ExampleJavaProgram
13
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
What are your observations about this program?What can you figure out?
Sept12,2016 Sprenkle-CSCI209
ExampleJavaProgram
• EverythinginJavaisinsideaclass Ø Javaisen&relyobject-oriented*Ø ThisclassisnamedHello
14
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
Sept12,2016 Sprenkle-CSCI209
9/9/16
8
ExampleJavaProgram
• Ingeneral,eachJavaprogramfilecontainsoneclassdefini+on*
• NameoftheclassisnameoffileØ E.g.,Hello.java
15
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
Definestheclass“Hello”
Blocks of code marked with { }
Sept12,2016 Sprenkle-CSCI209
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
ExampleJavaProgram
AccessModifier:controlsifotherclassescanusecodeinthisclass
16Sept12,2016 Sprenkle-CSCI209
9/9/16
9
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
ExampleJavaProgram
• Classcontainsonemethod:main
17
method
Sept12,2016 Sprenkle-CSCI209
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
ExampleJavaProgram:mainMethod
• SimilartomaininPythonØ Butmustbeassociatedwithaclass
• Musttakeoneparameter:anarrayofStringsØ Forcommand-linearguments
• Mustbepublic static • Mustbevoid:datatypeofwhatmethodreturns(nothing)• mainisautoma+callycalledwhenprogramisexecutedfrom
commandline
18Sept12,2016 Sprenkle-CSCI209
9/9/16
10
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
ExampleJavaProgram
• MethodcontainsonelineofcodeØ Whatdoyouthinkitdoes?
19Sept12,2016 Sprenkle-CSCI209
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
ExampleJavaProgram:PrintStatements
• CallstheprintlnmethodontheSystem.out object
• println takesoneparameter,aString• Displaysstringonterminal,terminatesthelinewithnewline(\n)character
20Sept12,2016 Sprenkle-CSCI209
9/9/16
11
ExampleJavaProgram:Comments
• Comments:/* */or//Ø /** */ arespecialJavaDoccomments
21
/** * Our first Java class * @author Sara Sprenkle */public class Hello {
public static void main(String[] args) {//print a messageSystem.out.println("Hello");
}}
Sept12,2016 Sprenkle-CSCI209
CodeStyle• Commentsattopofprogram
Ø MustincludeyournameØ High-leveldescrip+onofprogram
• ProperindentaEonØ SimilartoPythonØ Everythingwithinsetsof{}isindentedthesame
22
public class Hello {public static void main(String[] args) {
System.out.println("Hello");}
}
/** * Our first Java class * @author Sara Sprenkle */
Sept12,2016 Sprenkle-CSCI209
9/9/16
12
WhataretheDifferences?
23
# a Python programdef main():
print(“Hello”)
main()/** * Our first Java class * @author Sara Sprenkle */public class Hello {
public static void main(String[] args) {//print a messageSystem.out.println("Hello");
}}Sept12,2016 Sprenkle-CSCI209
Javavs.Python,sofar…• Seman&csthesame,syntaxdifferent
Ø BlocksofcodeØ Endstatements
• Accessmodifiers• Datatypedeclara+ons• Class-basedprograms• Compiled
24
We’ll see more differences as we go…
Sept12,2016 Sprenkle-CSCI209
9/9/16
13
LiteralTransla+ontoPythonProgram?
25
/** * Our first Java class * @author Sara Sprenkle */public class Hello {
public static void main(String[] args) {//print a messageSystem.out.println("Hello");
}}
Sept12,2016 Sprenkle-CSCI209
Transla+ontoPythonProgram
26
class Hello:"""Our first Python class"""
def __init__(self):# fill in later…
def main(self):print ("Hello")
Semi-literaltransla+on
Sept12,2016 Sprenkle-CSCI209
9/9/16
14
JAVAFUNDAMENTALS
27Sept12,2016 Sprenkle-CSCI209
PrintStatement• Syntax:
• SimilartoPython’sfile.write() methodØ NeedtocombineparameterintooneStringusing+’s• Python’sprint usedcommas
Ø MoreonStringopera+onslater
28
System.out.println(<String>);System.out.print(<String>);
No newline
Sept12,2016 Sprenkle-CSCI209
9/9/16
15
StringConcatena+on• Ifastringisconcatenatedwithsomethingthatisnotastring,theothervariableisconvertedtoastring.
29
System.out.println("The answer is " + 78);
Automatically converted to a String
Note +
Sept12,2016 Sprenkle-CSCI209
EscapeSequences• SameasPython:
• InJava,youcanprinta'withoutescaping• Whatdoesthefollowingdisplay?
System.out.println("To print a \\, you must use \"\\\\\"");
30First.java
Meaning Sequence
Newlinecharacter(carriagereturn)
\n
Tab \tQuote \"Backslash \\
Sept12,2016 Sprenkle-CSCI209
9/9/16
16
Javakeywords/reservedwords• Case-sensi+ve• Can’tbeusedforvariableorclassnames• Reservedwordsseensofar…
Ø publicØ classØ staticØ void
• Exhaus+velistØ http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
31Sept12,2016 Sprenkle-CSCI209
DataTypes• Javaisstrongly-typed
Ø Everyvariablemustbeadeclaredtype• AlldatainJavaisanobjectexceptfortheprimiEvedatatypes:
32
int 4bytes(-2,147,483,648->2,147,483,647)short 2bytes(-32,768->32,767)long 8bytes(reallybigintegers)byte 1byte(-128->127)float 4bytes(floa+ngpoint)double 8bytes(floa+ngpoint)char 2bytes(Unicoderepresenta+on),singlequotesboolean false ortrueSept12,2016 Sprenkle-CSCI209
9/9/16
17
Variables• Mustbedeclaredbeforeused
Ø Syntax:<datatype> <name> [= value];
• Variablenamestypicallystartwithlowercasele[erØ _(underscore)alsoavalidfirstcharacterØ Conven+on:Subsequentwordsarecapitalized
• Called“CamelCasing”
33
Op+onalassignment
Sept12,2016 Sprenkle-CSCI209
VariableExamples• Mustbedeclaredbeforeused
Ø Syntax:<datatype> <name> [= value];
• Examples:Ø int x;Ø double pi = 3.14;Ø char exit = 'q';Ø boolean isValid = false;
34
CamelCasing
Note must use single quotes for chars
Sept12,2016 Sprenkle-CSCI209
9/9/16
18
FloatsinJava• Decimalliteralsareconsidereddoubles• Thiscodewon’tcompile:
• Compilererrormessage:
• Tofixcode,addanftospecifica+onofnumberordeclareasdouble
35
Float.java:13: possible loss of precisionfound : doublerequired: float float f = 3.14;
float f = 3.14;
Float.java
Compiler reads 3.14as a double
Sept12,2016 Sprenkle-CSCI209
PythonTransi+onWarning
• OK:
• NotOK:
36
int x = 3;x = -3;
int x = 3;int x = -3;…boolean x = true;
Compilererrors
You cannot redeclare a variable name in the same scope
Sept12,2016 Sprenkle-CSCI209
9/9/16
19
MoreDataTypeInforma+on• Defaultdatatypes
Ø SameasPython2,notPython3Ø Resultofintegerdivisionisanint
• Example:4/3 = ??
• Cas+ngØ SimilartoPythonforprimi+vetypesØ Example:4/(double) 3
37Sept12,2016 Sprenkle-CSCI209TestScore.java
Forma[edOutput• printforformat
Ø System.outisaPrintStreamobject
38
double d1=3.14159, d2=1.45, total=9.43;
// simple formatting...System.out.printf("%6.5f and %5.2f ", d1, d2);
// %n is platform-specific line separator, // e.g., \n or \r\nSystem.out.printf("%-6s%5.2f%n", "Tax:", total);
Format.javaSept12,2016 Sprenkle-CSCI209
9/9/16
20
Constants• Read-onlyvariables
Ø Cannotbeassignednewvalues
• Keywordfinal precedesdatatypeØ Examplewithinamethod:
39
final double CM_PER_INCH = 2.540;
Why might we want to use constants within a method?
Sept12,2016 Sprenkle-CSCI209
ClassConstants• Constantvariableforallmethodsinclassorformul+pleclassesØ Muchmorecommonthanconstantinstancevariables
• Requiresstatic keywordØ static:“forclass”Ø Alsousedformethods(willseemorelater)
40
static final double CM_PER_INCH = 2.540;
Sept12,2016 Sprenkle-CSCI209
9/9/16
21
Arithme+c,Rela+onalOperators• JavahasmostofthesameoperatorsasPython:
Ø Arithme+coperators:+, -, *, /, %• Nopoweroperator:**
Ø Rela+onaloperators:==, !=, <, >, <=, >=• Evaluatetoaboolean value
Ø Incrementanddecrement• += x, -= y, etc.• Addi+onalshortcutfor+=1,-=1:++ , --
41Conversion.javaSept12,2016 Sprenkle-CSCI209
UnixOutputRedirec+on:>• Wecanredirectoutputtoafile
Ø Forexample
Ø Abovecommandsavestheoutputfromthels commandintothefilenamedjava_files.out
• ThisishowyouwillsaveoutputfromyourJavaprogramsini+allyØ Forexample
42
java Intro > out
ls *.java > java_files.out
Please follow instructions on namesSept12,2016 Sprenkle-CSCI209