Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture25LifeAfterCS106A,Part1
2
Plan for today•Announcements•LifeaftertheACMLibraries•LifeafterJava•LifeafterPCprograms–Internetapplications–Mobileapplications
Tomorrow:IntrotoMachineLearning!
3
Anonymous Questions•Whatisyourmusictaste?•HowdidyouknowyouwantedtopursueCS?•Whatwasyourfirstcodefor?
4
Plan for today•Announcements•LifeaftertheACMLibraries•LifeafterJava•LifeafterPCprograms–Internetapplications–Mobileapplications
5
Export to JAR• JAR:JavaArchive.AcompressedbinaryofaJavaprogram.
– ThetypicalwaytodistributeaJavaappasasinglefile.– EssentiallyjustaZIPfilewithJava.classfilesinit.
• MakingaJARofyourprojectinEclipse:– File→Export...→Java→RunnableJARFile
• seehandoutoncoursewebsite
6
Life After The ACM Libraries• AllquarterwehavereliedontheACMJavalibraries.
– Karel,ConsoleProgram,RandomGenerator– GraphicsProgram,GOval,GRect,GOval,GLine,GImage,...
• TodaywewillseehowstandardJava programsaremade.
7
Using the ACM Librariesimport acm.program.*;
public class MyProgram extends ConsoleProgram {public void run() {
println("Hello, world!");}
}
• ThisisaconsoleprogramwrittenusingtheACMlibraries.– ItusestheConsoleProgram classtorepresentaconsole.– Therunmethodcontainstheprogramcode.– Theprintlnmethodprintsoutputtothegraphicalconsole.
8
Pulling Back The CoversMyProgram program = new MyProgram();...program.init();...program.run();...
9
Pulling Back The Coverspublic static void main(String[] args) {
MyProgram program = new MyProgram();program.init();program.run();
}
10
A Barebones Java Program
public class Hello {public static void main(String[] args) {
System.out.println("Hello, world!");}
}
• Themethodmain isthetrueentrypointforaJavaprogram.– Itmusthavetheexactheadingshownabove.– TheString[] args are"commandlinearguments"(ignored).– Theprintln command'struenameisSystem.out.println.– StandardJavamethodsarestatic unlesspartofaclassofobjects.
11
Console Programs• WhatdoestheConsoleProgram libraryclassdo?
– Createsanewgraphicalwindow– Putsascrollabletextarea intoit– Providesprint andprintln commandstosendtextoutput tothatwindow
– containsamainmethod thatcallsyourprogramclass'srunmethod•ConsoleProgram'srun isempty,butyouextendandoverrideit
public class Hello extends ConsoleProgram {public void run() {
println("Hello, world!");}
}
12
ACM console inputpublic class Age extends ConsoleProgram {
public void run() {String name = readLine("What's your name? ");int age = readInt("How old are you? ");int years = 65 - age;println(name + " has " + years
+ " years until retirement!");}
}
• TheACMlibraryhassimpleconsoleinputcommandslikereadLine,readInt,readDouble,andsoon.
• Thesemethodsdisplaya'prompt'message,waitforinput,re-promptiftheusertypesabadvalue,andreturntheinput.
13
Java console inputpublic class Age {
public static void main(String[] args) {Scanner console = new Scanner(System.in);System.out.print("What's your name? ");String name = console.nextLine();System.out.print("How old are you? ");int age = console.nextInt();int years = 65 - age;System.out.println(name + " has " + years
+ " years until retirement!");}
}
• InstandardJava,youmustcreateaScanner orsimilarobjecttoreadinputfromtheconsole,whichisalsocalledSystem.in.– Itdoesnotautomaticallyre-promptandcancrashonbadinput.
14
Graphics ProgramsTheACMlibrarydoesseveralthingstomakegraphicseasier:• Automaticallycreatesanddisplaysawindow onthescreen.
– InstandardJava,wemustdothisourselves;itiscalledaJFrame.
• Setsupadrawingcanvas inthecenterofthewindowInstandardJava,wemustcreateourowndrawingcanvas.
• Providesconvenientmethodstolistenformouseevents.– InstandardJava,eventhandlingtakesabitmorecodetosetup.
15
ACM GUI examplepublic class ColorFun extends Program {
public void init() {JButton button1 = new JButton("Red!");JButton button2 = new JButton("Blue!");add(button1, SOUTH);add(button2, SOUTH);addActionListeners();
}public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Red!")) {setBackground(Color.BLUE);
} else {setBackground(Color.RED);
}}
}
16
Java GUI examplepublic class ColorFun implements ActionListener {
public static void main(String[] args) {new ColorFun().init();
}private JFrame frame;public void init() {
frame = new JFrame("ColorFun");frame.setSize(500, 300);JButton button1 = new JButton("Red!");JButton button2 = new JButton("Blue!");button1.addActionListener(this);button2.addActionListener(this);frame.add(button1, "South");frame.add(button2, "South");frame.setVisible(true);
}public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Red!")) {frame.setBackground(Color.BLUE);
} else {frame.setBackground(Color.RED);
} } }
17
Summary• Benefitsoflibraries:
– simplifysyntax/roughedgesoflanguage/API– avoidre-writingthesamecodeoverandover– possibletomakeadvancedprogramsquickly– leverageworkofothers
• Drawbacksoflibraries:– learna"dialect"ofthelanguage("ACMJava"vs."realJava")– lackofunderstandingofhowlowerlevelsorrealAPIswork– somelibrariescanbebuggyorlackdocumentation– limitationsonusage;e.g.ACMlibrarycannotbere-distributedforcommercialpurposes
18
Plan for today•Announcements•LifeaftertheACMLibraries•LifeafterJava•LifeafterPCprograms–Internetapplications–Mobileapplications
19
Programming Languages
20
Programming Languages
https://imgs.xkcd.com/comics/standards.png
21
JavaArrayList<Double> evens = new ArrayList<>();for(int i = 0; i < 100; i++) {
if(i % 2 == 0) {evens.add(i);
}}println(evens);
prints [2, 4, 6, 8, 10, 12, … ]
22
C++Vector<double> evens;for(int i = 0; i < 100; i++) {
if(i % 2 == 0) {evens.add(i);
}}cout << evens << endl;
prints [2, 4, 6, 8, 10, 12, … ]
23
Pythonevens = []for i in range(100):
if i % 2 == 0:evens.append(i)
print evens
prints [2, 4, 6, 8, 10, 12, … ]
24
Javascriptvar evens = []for(var i = 0; i < 100; i++) {
if(i % 2 == 0) {evens.push(i)
}}console.log(evens)
prints [2, 4, 6, 8, 10, 12, … ]
25
Plan for today•Announcements•LifeaftertheACMLibraries•LifeafterJava•LifeafterPCprograms–Internetapplications–Mobileapplications
26
Programs and the Internet
Howdoesyourphone
communicatewithFacebook?
27
Programs and the Internet
TheJavaprogramonyourphone talkstotheJavaprogram
atFacebook.
28
*AndroidphonesrunJava.SodoFacebookservers!
FacebookServer
32
Programs and the Internet
Therearetwotypesofinternet
programs:clientsandservers.
33
Programs and the Internet
Clientssendrequests toservers,whorespond tothoserequests.
34
Servers Are Computer Programs!
FacebookServer
=
35
Servers
Server
RequestsomeRequest
StringserverResponse
36
What is a Request?
/* Request has a command */String command;
/* Request has parameters */HashMap<String,String> params;
37
Clients
Send
ChatClient
Send
ChatClient> Hello world> Hello world
38
Plan for today•Announcements•LifeaftertheACMLibraries•LifeafterJava•LifeafterPCprograms–Internetapplications–Mobileapplications
39
Recap•Announcements•LifeaftertheACMLibraries•LifeafterJava•LifeafterPCprograms–Internetapplications–Mobileapplications
Tomorrow:IntrotoMachineLearning!