CS代考 ECS 140A Programming Languages

ECS 140A Programming Languages
August 9, 2022

Administrative stuff

Copyright By PowCoder代写 加微信 powcoder

The videos about the recursive descent parser have been posted on Canvas in the Pages tab.
HW1 has been posted and is due Sunday. HW2, 3, and 4 will be due on Sundays also: Aug 21, Aug 28, and Sep 4. HW 5 will be due on Friday, Sep 9, the last day of the summer session.
Your final exam will be in class on Tuesday, Sep 6. Quizzes in class on Thursdays: Aug 11, 18, 25, and Sep 1.

Language #1 – Java

The language of the Internet
Java was created at Sun Microsystems by and . The language is designed to be a machine- independent programming language (a very important concept) that is safe enough to be sent across networks (so that you don’t have to worry that some stranger’s Java code will run on your computer and hose your files) and powerful enough to do what you’ve come to expect of machine-specific (native) executable code.

The language of the Internet
Java has its roots in a language called Oak, which the Sun folks used to program interactive TV set-top boxes. But Sun abandoned set-top boxes, and Joy and Gosling had a language with no place to go. In 1993, the World Wide Web erupted, and these guys had a small, robust, platform-independent and object-oriented language for use in cable TV networks.
But hey, the same features that made Oak good for those networks would also make it good for the Internet. So Gosling and Joy did a little more work, and Sun started distributing Java as their choice for the language of the Internet.

Design principles
There were five primary goals in the creation of the Java language:
1.It must be “simple, object-oriented, and familiar”. 2.It must be “robust and secure”.
3.It must be “architecture-neutral and portable”. 4.It must execute with “high performance”.
5.It must be “interpreted, threaded, and dynamic”.

Platform independence
Any Java code written on any hardware (Motorola, Intel, RPi, ARM, RISCV, whatever) under any operating system (Mac, Windows, Unix, Linux, etc.) will run on any other system. If it doesn’t, then by definition it’s not Java (or at least it’s not the current version of Java). That’s a very nice feature. A language that didn’t have that feature couldn’t very well be the language of the Internet, could it? In other words, if you write some program on your Windows box that you want to run on my Macintosh when I’m browsing your web site, the program needs to be platform independent.

Platform independence
Java achieves that independence through what was then a fairly unusual approach. Instead of just distributing big Java compilers for every known platform, Java language processors are broken into two smaller pieces, each of which is somewhat easier to create than a larger monolithic Java compiler would be.

Platform independence
The first piece is a compiler too, but it compiles high-level Java instructions into a universally-accepted set of instructions called Java byte-code (or J-code). A
C compiler, on the other hand, typically generates instructions in the machine language of the host computer. So to write a C compiler for one platform may take a whole lot of different knowledge than writing the same compiler for a different platform.

Platform independence
That byte-code is then executed on something called a Java run-time interpreter (not a compiler, so a Java system is part compiler, part interpreter…it’s called a hybrid). That interpreter often goes by the name “Java virtual machine” or JVM for short. The JVM does all the work of a hardware processor executing machine instructions, but the extra layer of software allows a degree of safety we’ll talk about soon. The JVM manages the activation stack and storage heap, manipulates data types, and so on, and does so within a strictly-defined open specification that anyone can follow who wants to implement a JVM on a given platform.

Platform independence
So anyone who wants to write the Java compiler front end need only worry about translating Java source code to Java byte code…they don’t have to worry about machine- specific issues. And the folks who have to worry about getting the JVM working only have to worry about translating a standard byte-code to some native machine language, a task which supposedly is much more manageable than converting Java source directly to native machine instructions. Frankly, none of these jobs sounds appealing to me. In any case, the Java interpreters are relatively small by comparison to full blown compilers, and can be implemented in whatever form or language is desirable for a given platform.

Platform independence
But wait…there¡¯s more!!
The JVM was intended to interpret byte code generated by a Java compiler, but that¡¯s not a requirement. So you can create a compiler for some other language that generates Java byte code, and you can build that compiler without worrying about the machine-level details of the computer that you ultimately want your program to run on. Your compiler just needs to know how to produce the byte code, and then the byte code can run on any machine that has a JVM installed.

Platform independence
Are there languages that work this way? To name a few:
Java (obviously)
Processing
(plus lots of little ones)
And then implementations of existing languages:
Golang, COBOL, Haskell, Pascal, PHP, Prolog, Python, Ruby, Scheme, and many more

Safety and security
When you’re browsing the Web, there are lots of programs running on your computer that didn’t come with your computer, that you didn’t write, and that you didn’t buy. They’re little Java programs that fly across the Internet from the Web site you’re looking at (the server) to your computer (the client). They make the little animations happen, and they do the exciting flashing banner advertisements that you ignore, and so on. But the point here is that there are programs running on your computer that you didn’t agree to have on your computer. How do you know those programs aren’t installing viruses on your machine or stealing your credit card numbers or something?

Safety and security
Turns out there are some different things that the Java folks thought about to protect you from the dangers of running somebody else’s programs on your machine. First of all, and this protects you from yourself too, Java prevents programs from doing stuff in memory locations that they shouldn’t be messing with. With Java, you don’t get to do the kind of pointer arithmetic that you can do in C. Java checks memory references at run-time, so Java programs can only access parts of memory that are set aside for that sort of thing.

Safety and security
Beyond that sort of thing, the Java Virtual Machine includes a security manager which controls access to system resources like the filesystem, network ports, and the windowing environment. The security manager can be adjusted to be more or less trusting of outside code, as the application requires. The security manager in turn relies on a class loader to manage classes brought to your computer from other sources and keep them somehow separate from your own trusted code.

Safety and security
And the whole thing relies on something called a verifier to make sure that Java byte-code to be executed is well- behaved and obeys the rules of Java. Verified code can’t forge pointers or violate access permissions on objects. It can’t cast values from one data type to another in illegal ways or use objects in ways that weren’t intended. In short, verified code can’t do lots of things that nasty people like to do to get inside your machine.

Performance
In terms of computing power, Java lets you do pretty much whatever you need to do (except maybe creep around in areas of memory that you shouldn’t be creeping around). The big complaint about Java comes in the speed department. In general, an interpreted program in language X will run slower than the same compiled program, so interpreters trade away speed in return for other things like run-time detection of errors and stuff like that. So it should be no surprise that since at least part of the Java system is an interpreter, Java programs might take more time to execute than their C++ counterparts, for example.

Performance
However, that performance hit is mitigated in a couple of ways. First, since you’re interpreting byte-code instead of source code, interpretation can go a lot faster (the instruction set is smaller and the interpreter itself can be smaller and faster). Second, there are ways to optimize byte-code by compiling byte-code in small chunks as needed, on the fly, using “just in time” compilation.

Java quickstart guide
A program is a collection of classes.
Below is a definition of a class. A class is a package of instructions that specify what kinds of data will be operated on and what kinds of operations there will be. All the Java programs you write will consist of one or more classes. Nothing happens without a class, because classes spawn objects. Nothing happens without objects either (usually).
public class Oreo {
public static void main (String[] args) {
System.out.println (“Feed me more Oreos!”); }

A sample Java application program
The inner part is the definition of a method. A method is a group of Java statements (instructions) that has a name and performs some task. Here the name is ¡°main¡±.
public class Oreo {
public static void main (String[] args) {
System.out.println (“Feed me more Oreos!”); }
All the Java programs you create will have a main method. It¡¯s where the execution of the program begins.
The class name must match the file name.

Reserved words
There are 52 53 reserved words here…the number changes occasionally
double else
implements import
instanceof int interface long native
protected public
static strictfp super
switch synchronized this
throws transient

Identifiers
An identifier must start with a letter and be followed by
zero or more letters and/or digits. Digits are 0 through 9. Letters are the 26 characters in the English alphabet,
both uppercase and lowercase, plus the $ and _ (also alphabetic characters from other languages). There¡¯s no limit to how many characters you can put in your identifiers
Which of the following are not valid identifiers?
userName user_name $cash 2ndName first name user.age _note_ note2

Identifiers
An identifier must start with a letter and be followed by
zero or more letters and/or digits. Digits are 0 through 9. Letters are the 26 characters in the English alphabet,
both uppercase and lowercase, plus the $ and _ (also alphabetic characters from other languages). There¡¯s no limit to how many characters you can put in your identifiers
Which of the following are not valid identifiers?
userName user_name $cash 2ndName first name user.age _note_ note2

Identifiers
Java is case sensitive.
Oreo oreo OREO
are all different identifiers, so be careful. This is a common source of errors in programming.

White space
White space: the blanks between the identifiers and other symbols. Tabs and newline characters are included.
White space doesn¡¯t affect how the program runs.

White space
//******************************************************* // Oreo.java Author:
// Demonstrating good use of white space //*******************************************************
public class Oreo {
public static void main (String[] args) {
System.out.println (“Feed me more Oreos!”); }

White space
//******************************************************* // Oreo3.java Author:
// Demonstrating totally bizarre use of white space //*******************************************************
public class
System.out.println
main (String[] args) {
(“Feed me more Oreos!”)

White space
//******************************************************* // Oreo4.java Author:
// Demonstrating deep psychological issues //*******************************************************
System.out.println
(“Feed me more Oreos!”)

Most computers already have the Java Virtual Machine (JVM) installed. You may read or hear about the JVM using different words, like Java Runtime Environment (JRE). They’re the same thing. Having the JRE installed means your computer can execute Java programs that have already been compiled. But your computer may not have the Java compiler already installed.
To install the Java compiler on your computer, you’ll want to download the Java Software Development Kit (or Java SDK), which is also called just the Java Development Kit (or JDK).

Point your web browser to
https://www.oracle.com/technetwork/java/javase/downloads/index.html
https://openjdk.java.net

Data types
For every variable, we have to declare a data type.
We can use one of eight primitive data types provided by the
Java language.
For something more complicated than those eight primitive data types, we can use data types created by others and provided to us through the Java libraries, or we can invent our own.

Primitive data types (part one)

-2,147,483,648
2,147,483,647
-9,223,372,036,854,775,808
9,223,372,036,854,775,807
approx -3.4E38 (7 sig.digits)
approx 3.4E38 (7 sig.digits)
approx -1.7E308 (15 sig. digits)
approx 1.7E308 (15 sig. digits)
Six primitive data types are all about numbers…are they integer or floating point…and how big they can be.
The primitive data types all occupy fixed size in memory.

Primitive data types (part two)
Character Type:
Java has one character type named char. Java uses the Unicode character set and so each char occupies 2 bytes of memory. (This is not the same as a character string.)
Boolean Type:
Java has one Boolean type named boolean. Variables of type boolean have only two valid values: true and false. How much memory is used by a boolean type is left up to the discretion of whoever writes the Java Virtual Machine.

Variable declarations
public class Test3 {
public static void main (String[] args) {
int b = 3;
a = b + c;
System.out.println (“The answer is ” + a);

The conditional statement
The conditional statement allows us to choose which statement will be executed next based on a boolean expression (a test or a condition) which evaluates to either true or false. For example:
if (age < 20) System.out.println("Really, you look like you are " + (age + 5) + "."); would print the intended message if the value assigned to the variable age is less than 20. Block statements We often want to do a bunch of things based on some condition, not just one. Java allows us to replace a single statement with multiple statements by surrounding those statements with (curly) braces: if (x == y) // == is an equality test; = is assignment { System.out.println("x equals y!"); System.out.println("I'm happy"); } System.out.println("x is not equal to y"); System.out.println("I'm depressed"); System.out.println("How about you?"); Programming with classes and objects What do we do when the data we want to work with is more complex than can be accommodated by the few primitive data types? We make our own data type! We do that by creating a class. A class specifies the nature of the data we want to work with as well as the operations that can be performed on that kind of data. The operations that are defined within a class are called methods. More accurately, before we make our own we check to see if someone else hasn¡¯t already created our desired class for us. We do that by looking at the Java libraries written by other programmers. Programming with classes and objects For example, Java provides us with a char primitive data type which is a single character, but what if I want to work with a sequence of characters -- a character string? A quick(?) look at the online Java library documentation at https://docs.oracle.com/javase/7/docs/api/ tells us that there is a String class already written for us. (It¡¯s also described in your book.) The documentation tells us everything we need to know to use this class. The classes in the libraries are often referred to as the Application Programming Interfaces or just API. Programming with classes and objects Recall that a primitive data type like int allows us to create multiple variables of type int, each with a different name, and each with its own assigned value -- in this case, an integer. In somewhat the same way, the String class allows us to create multiple instances of the class String, each with a different name and each with its own associated value -- in this case, a character string. A specific instance of a class is called an object. Classes are templates for objects. We as programmers define classes; objects are created from classes. Creating classes and objects Let¡¯s say we wanted to quit this computer science career path and choose to make millions by owning and operating a bunch of vending machines. It could happen. But first, we want to simulate our collection of vending machines, using our Java programming skills. We could start off by creating a CokeMachine class, then making some CokeMachine objects from that class definition and see how they work. Or course, this is going to be a very very simplified simulation. If you want more robustness, feel free to add more code. Creating classes and objects A minimal simulation of a soda pop vending machine has to, at the very least, keep track of how many cans of pop were in the machine, and there has to be a way of ¡°buying¡± a can of pop from the machine. So our vending machine class, which we call CokeMachine, will be written so that there¡¯s a variable for keeping track of how many cans of pop remain. Also, there will be a method that simulates what happens when someone buys a can of pop from a machine. The next few slides highlight these two components. Creating classes and objects public class CokeMachine // This is how we begin any class Creating classes and objects public class CokeMachine public int numberOfCans; // Here¡¯s how we specify that any object // created from the CokeMachine class // has a variable to keep track of how // many cans of pop remain. Creating classes and objects public class CokeMachine public int numberOfCans; public void buyCoke() // Here¡¯s the method for buying // a can of pop // If the machine is not empty // then decrease the number of // cans by one and print an // appropriate message // otherwise the machine is // empty, so print ¡°sold out¡± if (numberOfCans > 0)
numberOfCans = numberOfCans – 1;
System.out.println(“Have a Coke”);
System.out.print(numberOfCans);
System.out.println(” cans remaining”);
System.out.println(“Sold Out”);

Creating classes and objects
The CokeMachine class needs one more component. In Java, classes don¡¯t do anything except serve as templates for the objects generated by those classes. Nothing in Java really happens until an object is created from a class; objects do all the work (almost). So our CokeMachine class needs to specify what happens when a new CokeMachine object is created from the CokeMachine class specification.
The specification of what happens when a new objects is created from a class is given by the constructor method for that class. The constructor method is always given the same name as the
class it¡¯s in. T

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com