Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CS 134:
Introduction to Java
Slide content based on http://www.cs.cmu.edu/~mjs/courses/121-F14-W/Java4Python.pdf 
Announcements & Logistics
• Lab 9 Boggle :  Due tonight/tomorrow @ 11pm
• Lots of office hours
• Come talk to us if you have questions!
• HW 9 available today, due Mon 5/9 @ 11pm
• Covers “advanced” topics from recent lectures
• Lab 10 Selection Sort in Java (next Mon/Tue) 
• No pre-lab work; hope most of you will start and finish during your 
lab session
• Final exam reminder:  Sunday, May 22 @ 9:30 AM 
• Course evals next Friday 5/13 (bring a laptop to class if possible)
Do You Have Any Questions?
May the 4th Be With You
• Working on partner labs be like — hopefully none of you had to resort 
to git push --force!
Last Time
• Briefly reviewed searching algorithms:
• :  binary search runtime in a sorted array-based list
• :  linear searching runtime in an unsorted list
• Discussed two classic sorting algorithms:
• :  merge sort runtime
• :  selection sort runtime
• What about (extra) space for sorting?
• :  naive merge sort
• :  selection sort
• Time-space tradeoff!
O(log n)
O(n)
O(n log n)
O(n2)
O(n)
O(1)
Today
• Begin discussing Java
• Discuss how to run programs in Java 
• Learn about Java syntax
• Take a closer look at data types in Java
• Goals of next 4-5 lectures: 
• Understand the key similarities and differences between Python 
and other programming languages (Java)
• Review basic features of Python in preparation for final exam
• Gain confidence in our programming abilities
• Help ease the transition to CS 136 (and beyond!)
Python vs. Java
• Powerful language used by many 
programmers
• Features for making common 
programming tasks relatively 
simple
• Can run programs as scripts or 
interactively
• Dynamically typed: Run-time 
error when variables are used 
incorrectly
• Good fit for teaching 
programming to new computer 
scientists
• Powerful language used by many 
programmers
• Features for building large-scale 
systems design 
• Must be "compiled" and run from 
terminal
• Statically typed: compile-time 
error when variables are used 
incorrectly
• Good fit for large software 
projects, but steep learning curve
Python Java
Hello, World!
Python in Week 1:
Python in Week 11: Java:
Hello, World!
Java:Python:
Hello, World!
Python: Java:
Running Our Code
• Python is an interpreted language
• The Python interpreter runs through our code line by line and 
executes each command
• Other interpreted languages: PHP, R, Ruby, and JavaScript
• Java is a compiled language*
• The Java compiler converts our code into machine code that the 
processor can execute
• Compiled languages require code to be manually compiled 
before execution
• Other compiled languages: C, C++, Haskell, Rust, and Go
• Interpreted languages were once significantly slower than compiled 
languages. But that gap is shrinking.
*Technically Java is both interpreted and compiled, but we can ignore that detail for now.  
Using the Java Compiler
• The compiler converts our Java source code 
into compiled byte code which is faster to 
run (hence the performance benefits)
• Java source files are always named 
.java 
• To compile, type: 
javac .java 
• Compilers detect and report syntax errors 
before execution
• Compiler creates class files:  
.class 
• Code is executed by typing  
java   
(without the .class extension)
Important Java Rules
• Every Java program must define a class, and all code is inside a class.
• The file name must be the same as the class name (Hello.java). 
• Every object in Java must have an explicit type. 
• Every Java program that we want to execute must have a main 
method:  public static void main(String[] args) 
• Blocks of code contained within {} (versus indentation in Python)
• Statements end with ; (versus new line in Python)
Important Java Rules
This curly brace closes  
the one on line 1.
Define a class called Hello.   
Notice the curly brace. 
• Every Java program must define a class, and all code is inside a class.
• The file name must be the same as the class name (Hello.java). 
• Every object in Java must have an explicit type. 
• Every Java program that we want to execute must have a main 
method:  public static void main(String[] args) 
• Blocks of code contained within {} (versus indentation in Python)
• Statements end with ; (versus new line in Python)
Important Java Rules
Defines the main method. Similar to saying  
if __name__ == “__main__” in Python.
Opening curly brace
Closing curly brace
• Every Java program must define a class, and all code is inside a class.
• The file name must be the same as the class name (Hello.java). 
• Every object in Java must have an explicit type. 
• Every Java program that we want to execute must have a main 
method:  public static void main(String[] args) 
• Blocks of code contained within {} (versus indentation in Python)
• Statements end with ; (versus new line in Python)
Important Java Rules
Print “Hello, World!” to the terminal. Statements end with a ;
• Every Java program must define a class, and all code is inside a class.
• The file name must be the same as the class name (Hello.java). 
• Every object in Java must have an explicit type. 
• Every Java program that we want to execute must have a main 
method:  public static void main(String[] args) 
• Blocks of code contained within {} (versus indentation in Python)
• Statements end with ; (versus new line in Python)
Public, Private, Protected
• public indicates to the Java compiler that this is a method that 
anyone can call
• Java enforces several levels of security on methods (also variables and 
classes): public, protected, and private
• Similar to _ and __ methods in Python, but more strictly enforced
static
• static indicates that this is a method that is part of the class, but is not a method for any 
one instance of the class (static exists in both Java and Python!)
• Most methods we used in Python required an instance of the class in order for the method 
to be called:
• Example: s.upper() (where s is a string and upper() is a method in the string class)
• With a static method, the object to the left of the . is a class, not an instance of the class. 
• For example the way that we would call the main method directly is: Hello.main(…). 
• Similar to Python modules (such as random) that don’t require an instance
• Example: random.randint(0,15)
void
• void tells the Java compiler that this method will not return a value
• void means “no type”
• Roughly analogous to omitting the return statement in a Python method 
(or having an implicit return of None)
String args[ ]
• Our main method takes as input an array (denoted by []) of Strings 
called args 
• This is used for handling command-line arguments but we won't 
worry about that now
• Since everything in Java must have a type, we also have to tell the compiler 
that the types of values stored in our array are Strings
• Recall that arrays are a lot like lists in Python
System.out and System.in
• System is a Java class
• Within the System class we find the object named out
• The out object is the standard output stream for this program.  The in 
object is the standard input stream.  We’ll come back to that soon.
• The println method prints a string with a newline character at the end
• Anywhere in Python that you used the print(…) function you will use 
the System.out.println(…) method in Java
Moving on…
Programming Language Features
• Basic features: 
• Data Types
• Reading user input
• Loops
• Conditionals 
• Advanced topics: 
• Classes 
• Interfaces 
• Collections 
• Graphical User Interface Programming 
We have extensively studied all of these 
features in Python.  Let’s compare and 
contrast with Java.
• Basic features: 
• Data Types
• Reading user input
• Loops
• Conditionals 
• Advanced topics: 
• Classes 
• Interfaces 
• Collections 
• Graphical User Interface Programming 
Programming Language Features
Let’s start with data types and reading 
user input.
Basic Data Types
• All data types in Python are objects
• Implemented using classes and methods just like our LinkedList
• Two types of data types in Java: primitive (non-objects) and Objects
• Example: int (lowercase) and Integer (uppercase)
• The benefit of primitive data types is fast operations
• We’ll mostly use the Object versions and let the compiler handle 
conversions to primitives for us
• Java data types:
Simple Example
• Consider this Python script: temp.py
• What does it do?
Simple Example
• Consider this Python script: temp.py
• What does it do?
• Asks user to enter a temperature in Fahrenheit and converts the 
string input to float
• Does the computation to convert temperature to Celsius
• Prints result
Simple Example
• Same program in Java:  TempConv.java
Simple Example
• Same program in Java:  TempConv.java
Comments in Java start with // 
compared to # in Python
Simple Example
• Java uses import statements to tell the compiler what classes to use
Java import statements are similar to  
from module import xxx 
statements in Python
Simple Example
• Java is statically typed.  Thus, all variables must be declared with a name and 
type before they are used.  Common convention is to declare variables at the top 
of our methods/classes.
Lines 6-8 are variable declarations, which 
define the name and type of our variables.  Once 
declared, the types cannot be changed.  
Simple Example
• Let’s try to compile: javac TempConv.java
Note: Removing these lines will cause the 
compiler to report several errors.
The compiler will report several 
errors (sometimes repeatedly) 
when we try to compile our 
program after removing our 
variable declarations.
Simple Example
• After declaring a Scanner object named in, we also have to 
initialize it before using it (like calling __init__() in Python).  
On Line 8 we give our Scanner the name in.   
On Line 10, we initialize our Scanner object with the 
parameter System.in to read input from the user. 
Note: Always use new when initializing new objects. 
Simple Example
• System.out.print and System.out.println are like print in Python.  
• in.nextDouble() automatically reads the user input as a Double (like using 
input() in Python and then converting to float) 
On Line 11 we print a prompt to the screen.   
On Line 12, we use our Scanner to read the 
input value as a Double (a double precision 
floating point number) and store the value as fahr.
An Aside: Using the Java Scanner
• Since Java is strongly typed, we have to be extra careful when reading 
input from the user to make sure it is of the expected type
• The Scanner class provides methods for making sure the next value 
(like an iterator!) is of the expected type
• Here are some methods for the Java Scanner class
Simple Example
On Line 14 we perform the calculation to convert. 
On Line 15 we print the results.
• Arithmetic calculations in Java and Python are very similar wrt syntax
• When we print, we use the + operator to perform string concatenation
Simple Example
• Before running our program, we compile using javac 
 
javac TempConv.java 
• To run, we use java 
 
java TempConv
]
]
]
Recap: Python vs. Java
• Step 1: Prepare to read input from user.
]
]
Java:
Python:
]]
• Step 2: Prompt user for input.
Recap: Python vs. Java
Java:
Python:
]]]
• Step 3: Read user input and convert to float/double (that is, a number 
with a decimal point).
Recap: Python vs. Java
Java:
Python:
]]
• Step 4: Perform conversion to Celsius. 
Recap: Python vs. Java
Java:
Python:
]]
• Step 5: Print result.
Recap: Python vs. Java
Java:
Python:
An Aside: Java GUIs
• Java has more built-in support for making 
GUIs and supporting graphical objects
• Here is a graphical version of our 
program