Transcript Document

Lecture 2: Computers,
Programs, and Your First
Java Program
Michael Hsu
CSULA
What is a computer?
Input Device
Output
Device
http://www.cs.rpi.edu/academics/courses/fall09/os/c01/01-06.jpg
Content summarized from Liang, Introduction to Java Programming 10th edition instructor slides
Jargons to Know


Programs:

Known as software, instructions to the computer

You telling what the computer to do

Written using programming languages

Examples:

Your operating system

Web browsers, anti-virus software, device drivers, android apps, Skype, Steam, video games
Algorithm:

A series of steps/rules to be followed


Examples: Rubik’s cube algorithms, Sieve of Eratosthenes
Standard input/output:

Preconnected input and output communication channels between a computer program and its
environment when it begins execution
How is Data Stored on the computer?

Zeroes and ones

Usually mapped to memory addresses

More Info:

Memory address
http://en.wikipedia.org/wiki/Computer_data_storage
Memory content
.
.
.
.
.
.
2000
01001010
Encoding for character ‘J’
2001
01100001
Encoding for character ‘a’
2002
01110110
Encoding for character ‘v’
2003
01100001
Encoding for character ‘a’
2004
00000011
Encoding for number 3
Programming Languages


Machine language

Primitive instruction built into every computer in the form of binary code

Difficult to read/understand/modify

Add two numbers: 1101101010011010

Platform dependent
Assembly language

Make programming easier (lol still hard)

Since computers can’t understand it, we need an assembler (also a program) to convert
assembly language program to machine code.

Example: ADDF3 R1, R2, R3

Platform dependent, you have to write different code for different processors

Pokemon gold/silver is written in assembly by four people
Assembler
NASM Assembly Language Program
Example to Print “Hello, World”
; ---------------------------------------------------------------------------------------; Writes "Hello, World" to the console using only system calls. Runs on 64-bit Linux only.
; To assemble and run:
;
; nasm -felf64 hello.asm && ld hello.o && ./a.out
; ---------------------------------------------------------------------------------------global _start
section .text
_start:
; write(1, message, 13)
mov rax, 1
; system call 1 is write
mov rdi, 1
; file handle 1 is stdout
mov rsi, message
; address of string to output
mov rdx, 13
; number of bytes
syscall
; invoke operating system to do the write
; exit(0)
mov eax, 60
; system call 60 is exit
xor rdi, rdi
; exit code 0
syscall
; invoke operating system to exit
message:
db
"Hello, World", 10
; note the newline at the end
http://cs.lmu.edu/~ray/notes/x86assembly/
High Level Programming Languages

Much, much easier to write

Greater abstraction


Allows better productivity


For example, in the next slide, you do function/method calls instead of direct memory
manipulation like assembly
Less lines of code to write, less lines to debug
More Info:

http://en.wikipedia.org/wiki/High-level_programming_language
Printing “Hello, World” in different high
level languages

NOTE: these are not complete programs

Java:
Sytstem.out.println("Hello, World");


C++:


Python 3:


std::out << “Hello, World”;
print “Hello, World“
C#:

System.Console.WriteLine("Hello, World");
Popular High-Level Languages
Language
Description
Ada
Named for Ada Lovelace, who worked on mechanical general-purpose computers. The Ada
language was developed for the Department of Defense and is used mainly in defense projects.
BASIC
Beginner’s All-purpose Symbolic Instruction Code. It was designed to be learned and used easily
by beginners.
C
Developed at Bell Laboratories. C combines the power of an assembly language with the ease of
use and portability of a high-level language.
C++
C++ is an object-oriented language, based on C.
C#
Pronounced “C Sharp.” It is a hybrid of Java and C++ and was developed by Microsoft.
COBOL
COmmon Business Oriented Language. Used for business applications.
FORTRAN
FORmula TRANslation. Popular for scientific and mathematical applications.
Java
Developed by Sun Microsystems, now part of Oracle. It is widely used for developing platformindependent Internet applications.
Pascal
Named for Blaise Pascal, who pioneered calculating machines in the seventeenth century. It is a
simple, structured, general-purpose language primarily for teaching programming.
Python
A simple general-purpose scripting language good for writing short programs.
Visual
Basic
Visual Basic was developed by Microsoft and it enables the programmers to rapidly develop
graphical user interfaces.
Why Should I know About Assembly At
All?

Understand the struggles of your predecessors

Debugging programs written in C/C++ using code dumps

Reverse engineering

Often without source code

Stepping through assembly instructions using tools such as ollydbg

Optimizations that require low level code

Space/performance constraints

Fitting your code/data on a Gameboy cartridge
Interpreting/Compiling Source Code

A program written in a high-level language is called a source program or
source code.

Because a computer cannot understand a source program, a source program
must be translated into machine code for execution. The translation can be
done using another programming tool called an interpreter or a compiler.
Interpreting Source Code

An interpreter reads one statement from the source code, translates it to the
machine code or virtual machine code, and then executes it right away, as
shown in the following figure. Note that a statement from the source code
may be translated into several machine instructions.

There are more nuances about different types of interpreters, etc. Do more
research online.
Compiling Source Code

A compiler translates the entire source code into a machine-code file, and the
machine-code file is then executed, as shown in the following figure.
Why Java For This Course?

Our whole sequence of classes uses Java, it’s part of the system

CS201, CS202, CS203

CS320, CS520

Relatively easy to learn compared to C/C++

Still very popular with lots of users

http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
History of Java

http://www.oracle.com/technetwork/java/javase/overview/javahistoryindex-198355.html

Developed by Sun Microsystems as an alternative to C++/C

Garbage collection

Pioneers of web development

Sun Microsystems acquired by oracle

Use widely in corporate environments, web servers

Minecraft, Android
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Creating, Compiling, and Running
Programs
Compiling Java Source Code


"Write once, run anywhere" (WORA)

Remember machine code is platform dependent

Compiler compiles the code, can only run on that platform
The Java Virtual Machine(JVM)

What if we don’t compile for each different platform, but use a virtual machine ,
and compile for that machine instead? Genius!

The Java compiler compiles your program into bytecode

The bytecode can then be run on any JVM on any platform
Compile and Running a Java Program
Compiling and Running HelloWorld.java

The name of the source file is “HelloWorld.java”

Change directory to the folder where the source file is in

Compile the source code into java bytecode:


javac HelloWorld.java
Execute the generated .class bytecode file


java HelloWorld
NOTE: without the .java extension
Anatomy of a Java Program

Class name

Main method

Statements

Statement terminator

Reserved words

Comments

Blocks
Class Name

Every Java Program must have at least one class.

Each class has a name

Use upper camel case by convention

Capitalize the first character of each word

Examples: HelloWorld, WelcomeHome, ThisIsAnExample, Hello
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
The Main Method

A method is a set of code which is referred to by name and can be called
(invoked) at any point in a program simply by utilizing the method's name.

In order to run a class, the class must contain a special method named main.
The program is executed from the main method.

It has to look exactly like this:
public static void main(String[] args)


Remember, computers are stupid
For now, all your classes will contain the main method.
Statement

A statement represents an action or a sequence of actions

The highlighted statement writes Hello World to standard output:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}

Notice the statement ends with a semicolon:

Every statement in Java ends with a semicolon(;).
Reserved Words

Reserved words or keywords are words that have a specific meaning to the
compiler and cannot be used for other purposes in the program. For example,
when the compiler sees the HelloWorld class, it understands that the word
after class is the name for the class.

In the example below, the reserved words are highlighted in red
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Blocks

A pair of braces ({ }) in a program forms a block that groups components of a
program:
public class Test {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Class block
Method block
Special Symbols
Character Name
{}
()
[]
//
" "
;
Description
Opening and closing
braces
Opening and closing
parentheses
Opening and closing
brackets
Double slashes
Denotes a block to enclose statements.
Opening and closing
quotation marks
Semicolon
Enclosing a string (i.e., sequence of characters).
Used with methods.
Denotes an array.
Precedes a comment line.
Marks the end of a statement.
How Do I Have Quotes as Part of the
String?

When an escape sequence is encountered in a print statement, the compiler
interprets it accordingly.

For example, if you want to put quotes within quotes you must use the
escape sequence, \", on the interior quotes. To print the sentence:

She said "Hello!" to me.

you would write:

System.out.println("She said \"Hello!\" to me.");
Escape Sequences
Escape Sequence
Description
\t
Insert a tab in the text at this point.
\b
Insert a backspace in the text at this point.
\n
Insert a newline in the text at this point.
\r
Insert a carriage return in the text at this point.
\f
Insert a formfeed in the text at this point.
\'
Insert a single quote character in the text at this point.
\"
Insert a double quote character in the text at this point.
\\
Insert a backslash character in the text at this point.
Examples
EscapeSequence.java
Programming Conventions

Why follow conventions?

Won’t make my eyes bleed

I look at all your assginements

I will take off points if you don’t.

Easier to read and maintain

Lots of APIs and frameworks rely on proper naming conventions

Maven, Expression Langague, etc
Appropriate Comments

Comments at the beginning of your code to state the purpose of the program

Your source code should be self-documenting

If it can be confusing to the reader, add inline comments
Comments Example
/* CS201
* Spring 2015
* Example 1
*/
public class HelloWorld {
//Write Hello, World to standard output
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Naming Conventions

Choose meaningful and descriptive names.


Length of name is no longer an issue, since most editors support autocomplete
Class names:

Upper Camel Case

Capitalize the first letter of each word in the name. For example, the class name
ComputeExpression.
Proper Indentation and Spacing

The machine doesn’t care whether you indent it or not. In fact, compressing
everything to one line saves a lot of space

Indentation and spacing is used so your code is readable.

Use Indentation to show different levels of the code block/structure

Generally two spaces per level, or you can use tabs

In fact, languages like python make it mandatory, or it won’t even compile

Use a plugin for your editor to automate the process.

I’m not too picky on the style, as long as it’s readable
Readable Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Unreadable Code
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}
Conventions Grading Criteria

If you don’t follow conventions, I will take off up till 20% of your lab grade
depending on the offense.
Programming errors

Syntax Errors


Runtime Errors


Detected by the compiler, won’t compile at all
Causes the program to abort
Logic Errors

Produces incorrect result

Most difficult to debug
Syntax Error
public class Test {
publi static void main(String[] args) {
System.out.println("lol, you can't spell");
}
}
What is wrong with this code?
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
System.out.println(1 / 0);
}
}
What is wrong with this code?
Logic Errors
public class CalculateAreaOfTriangle {
public static void main(String[] args) {
System.out.println("Base is 20, height is 10");
System.out.println("Area is: ");
System.out.println(20 + 10);
}
}
What is wrong with this code?
Reading Error Messages

Pay attention to the line number

Understand what type of error it is

Read your own code and find the problem.


At this stage, it is most likely a problem with your code or your environment setup,
Java is not the problem.
More Info

http://www.dummies.com/how-to/content/tackling-error-messages-in-javaprogramming.html
Lecture Code Examples:

https://github.com/mhsu0020/CSULA-CS201-Spring2015/

GitHub is a popular Git repository hosting service

Git:

A popular version control software

Allows you to keep track of your code changes and collaborate with others

Go to the folder for the week, click on the source file, then click raw. You can
then right click and save the file. Remember to change the extension to .java

If you’re feeling adventurous, you can setup git/github client on your machine
and directly pull from the repository

Check out the git and github tutorials from the course webpage resource section
Reminder:

Lab 1 due next Thursday before class

Follow the JDK setup guide on the course website so you can work on the labs