Java Syntax: Written by Amir Kirsh
Java Syntax: Written by Amir Kirsh
Lessons Objectives
By the end of this lesson you will:
Be familiar with Java environment and characteristics
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Java History
Started as an internal project at Sun Microsystems in Dec-1990
Today Java progress is ruled by the Java Community Process (JCP) based on Java Specification Requests (JSRs)
4
Sep-2004: J2SE 5.0 (added Generics, annotations, ) Dec-2006: Java SE 6 (support in code compilation, scripting, )
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Device Drivers when you need access to device memory and specific resources (C/C++ would be a choice)
When the device does not support Java
Handsets which dont have J2ME/Android old OS
Java can still be layered on top of native code, using JNI or Inter-Process-Communication:
User Interface above a Device Driver or other native code Management of the Real-Time part of an application
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Language Characteristics
You know you've achieved perfection in design, Not when you have nothing more to add, But when you have nothing more to take away.
Antoine de Saint Exupery
10
Language Characteristics
You know you've achieved perfection in design, Not when you have nothing more to add, But when you have nothing more to take away.
Antoine de Saint Exupery
Stated in "The Java Language Environment", a white paper by James Gosling and Henry McGilton, May 1996, Chapter 2:
http://java.sun.com/docs/white/langenv/Simple.doc.html
11
Language Characteristics
You know you've achieved perfection in design, Not when you have nothing more to add, But when you have nothing more to take away.
Antoine de Saint Exupery
Becoming a bit shaky starting from Java 5 and on - Generics, Annotations, etc. - Closures in Java 7 ! The language is becoming more and more complex
12
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
13
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
Based on C++ but without some complicated or annoying elements of C++ (e.g. pointers, operator overloading, header files) Automatic Garbage Collection! Useful libraries that are part of the language
14
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
Inheritance and Polymorphism Object class is base for all classes No global variables or functions!
15
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
Local and remote files are treated similarly Supports distributed applications Rich libraries for network operations
16
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
Java code is compiled to intermediate language (Java byte-code class file) and is interpreted in Runtime by the Java Virtual Machine No need to Link the application, linking is always done dynamically at Runtime JIT (just-in-time) JVMs make the interpretation efficient
17
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
The language is much more robust compared to C++ - No pointers, arrays bounds and variable initialization are checked: it is almost impossible to corrupt memory - Garbage Collection: harder (though possible) to create memory leaks - Strict type safety: very limited casting allowed
18
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
The byte-code is checked by the JVM before execution for any unsafe or vulnerable operations Code cannot access memory directly Additional security restrictions for code that comes from the network (e.g. Applets)
19
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
The code is agnostic to the physical architecture due to the JVM layer Code can be written and compiled on one environment and then executed on another one!
20
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
The language clearly defines issues that in other languages are left open: exact binary form of each data type, thread behavior, GUI behavior, etc. The JVM implementation takes care of the differences between the different environments
21
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
Java is much more efficient than other interpreted languages Java applications are of similar order of performance as C/C++, based on sophisticated JVM optimizations
22
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
Multithreading and thread synchronization are part of the language As with anything else, same multithreading API for all Operating Systems
23
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
24
The application can load classes after it has started Since linking is done in Runtime adding new stuff to existing classes doesnt break any binaries using it Reflection (though added after the above was stated) Can compile code in Runtime and use it (again, added after the above was stated but what the hell)
Language Characteristics
Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
Sounds Good!
25
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Java byte-code
(Binary files with .class suffix)
Java Compiler
javac [<params>] <java files> - Compile time classpath + required jars
JDK
27
JVM = Java Virtual Machine (part of the JRE) GC = Garbage Collector (part of the JVM) JSE = Java Standard Edition (the basic Java / pure java) JEE = Java Enterprise Edition (some more classes) Java API = The Java Application Programming Interface Classpath = Where to look for classes (well talk about it) JAR = a file packaging many classes together IDE = Integrated Development Environment
(not a must, one can use notepad or vi but we will use Eclipse)
28
where options include: -client to select the "client" VM -server to select the "server" VM -cp <class search path of directories and zip/jar files> -classpath <class search path of directories and zip/jar files> A ; separated list of directories, JAR archives, and ZIP archives to search for class files. -D<name>=<value> set a system property -? -help print this help message -Xms<size> set initial Java heap size -Xmx<size> set maximum Java heap size -Xss<size> set java thread stack size -Xprof output cpu profiling data
29
30
Trends in hardware and software made garbage collection far more practical:
Empirical studies in the 1970s and 1980s show garbage collection consuming between 25 percent and 40 percent of the runtime in large Lisp programs
31
32
Trace by reachability
Objects should be kept alive if they are reachable from:
- Static references - References on Stack
33
34
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Hello World
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); }
Method return value is similar to C. In this case void means that the method does not return a value
36
Hello World
main in Java is a static method inside a class public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } Each type in the class should declare its access modifier String[] means array of String objects String is a class defined in the Java language itself main gets array of strings from the command line
No ; at end of class
37
Run:
java HelloWorld
38
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
40
Java Syntax
Java Syntax is very similar to C++. In the following slides we will cover both the Java things that are similar to C++ as well as things that do not appear in C++ or work differently.
41
Data Types
Primitive Type
byte short int long float double
Class
Integer Short Integer Long Float Double
Usage
8 bit integer number in the range of: -128 to 127 16 bit integer number in the range of: -32,768 to 32,767 32 bit integer number in the range of: -2,147,483,648 to 2,147,483,647 64 bit integer number in the range of: -9,223,372,036,854,775,808 to ...807 32 bit floating point number 64 bit floating point number
boolean
char --42
Boolean
Primitive Variables
Primitive variables are variables of primitive types (i.e. not objects) they pass By Value
Example:
int i = 3; foo(i); System.out.println(i); // prints 3 void foo(int i) { i = 5; }
Example:
void someMethod(Person p) { p.setName("Momo"); }
44
Example 1:
void someMethod() { Person p; p.setName("Koko"); }
Example 2:
class Foo { Person p; // field p is initialized to null void someMethod() { p.setName("Annul"); Well, in fact its a } null reference }
47
Example 1:
void someMethod(Person p) { p = new Person("New Person"); p.setAge(0); }
48
Example 2:
void someMethod(String s) { s = "123"; }
So how do I change a String that was sent to me? You CANT. String is Immutable. As well as all the wrapper classes (Integer, Long etc.)
49
Example:
Person p = new Person("Noa"); Person q = p; q.setName("Q");
50
51
Since p and q do not share the same reference We will see NOT Equal! (== checks for reference equality)
52
Arrays
Examples: [1] int[] intArr = {1,2,3}; // or = new int[]{1,2,3}; [2] String[] sArr = new String[]{"a", "b", "c"}; [3] Person[][] personArr2d = new Person[3][2]; for(int i=0; i < personArr2d.length; i++) { for(int j=0; j < personArr2d[i].length; j++) { personArr2d[i][j] = new Person(); } }
54
Arrays
Examples (cont): [4] String[][] strArr2d = new String[3][]; for(int i=0; i < strArr2d.length; i++) { strArr2d = new String[i+1]; } strArr2d
0 1 2
null
null
null
55
foreach loop
New kind of loop introduced in Java 5 Example:
String[] sArr = {"Noa", "Koko", "Momo"}; for(String str : sArr) { System.out.println(str); }
- "foreach" is the common name for this new type of loop, but its not a keyword in the language
56
57
do { doSomething(); } while(!isDone());
58
Exceptions
Unchecked: RuntimeException (and Error)
Can throw without declaring in the methods signature
Checked:
Unchecked
RuntimeException
Unchecked
59
Exceptions
Keywords:
throw, throws, try, catch, finally
Not a must, since this is a RuntimeException
Example:
void foo(String snum) throws NumberFormatException { try { int number = Integer.valueOf(snum); System.out.println(Math.pow(number, 2)); } finally { System.out.println("getting out of foo"); } } Example continues in next page
60
Exceptions
Keywords:
throw, throws, try, catch, finally
Example (cont):
void bar() { try { foo("abc"); System.out.println("foo was OK"); } catch(NumberFormatException e) {
// an example, not really what we do with exceptions
Exceptions
Never absorb Exceptions!!!
Bad:
try { doSomething(); } catch(Exception e) { // this should never happen... System.out.println("Surprise!"); } try { doSomething(); } catch(Exception e) { // this should never happen... throw new RuntimeException(e); }
Instead:
62
Varargs
printf in Java (yes, there is such a thing!)
System.out.printf("i = %d, with message = %s", i, msg); The signature of printf (in classes PrintStream and PrintWriter) is: printf(String format, Object... args) Object... means that the user can send any number of parameters of type object (including zero number) The function gets the Object... as an array of Objects (=Object[])
63
64
Fields and Methods can be private or public (or protected or package friendly)
Classes themselves can be private or public (or package friendly)
65
66
67
No default parameters No operators overloading (methods overloading do exist) No multiple inheritance nor private / protected inheritance
(we will talk about inheritance later)
68
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Java API
Java API is the Help for Java libraries
We will start from here: http://java.sun.com/javase/6/docs/api/ Then take an example from here: http://java.sun.com/javase/6/docs/api/java/lang/String.html
70
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Java as an OO language
Well, we talked too much so far so we will have to leave it for after the break
BUT
Some exercise before!
72
Agenda
Java History What can be done with Java? Language Characteristics The Java Environment
Hello World
Basic Syntax
Java API
Java as an OO language Exercise
Exercise 1
Get strings from the command line and print to screen only those which contain the word Java (with a capital J).
74
Exercise 2
Get integers from the command line (well, you will get Strings but should find a way to turn them to ints), calculate the average then print to screen all the numbers and the average.
75
Exercise 3
Get Strings from the command line, present in the console a vertical bar chart of the frequency of each letter in the input.
Treat small and capital letters the same -- as capital Ignore any char that is not an English letter
Example
For the following input: we expect the following chart:
A E H O R Y U W # ## ## ## # ## # #
76
Exercise 4
This exercise is called the Rectangles game. Get from the command line the coordinates of two rectangles. The winning rectangle is set according to these rules:
If a rectangle is contained (even partially) in the other, the contained (=inner) rectangle wins If no one contains the other, the bigger by both area and perimeter wins If no one is bigger by both area and perimeter, we have a tie
Example
Rectangle A: 1 1 10 10 Rectangle B: 5 5 10 10 (which means: x1=1, y1=1, x2=10, y2=10) (which means: x1=5, y1=5, x2=10, y2=10)
77
amirk at mta ac il
78