1 crash course in java based on notes from d. hollinger based in part on notes from j.j. johns also:...
Post on 20-Dec-2015
222 views
TRANSCRIPT
1
Crash Course in Java
Based on notes from D. Hollinger
Based in part on notes from J.J. Johns
also: Java in a Nutshell
Java Network Programming and Distributed Computing
2
What is Java?
• A programming language.– As defined by Gosling, Joy, and Steele in the Java
Language Specification
• A platform– A virtual machine (JVM) definition.– Runtime environments in diverse hardware.
• A class library– Standard APIs for GUI, data storage, processing,
I/O, and networking.
3
Why Java?
• Network Programming in Java is very different than in C/C++– much more language support– error handling– no pointers! (garbage collection)– threads are part of the language.– some support for common application level
protocols (HTTP).– dynamic class loading and secure sandbox
execution for remote code.– source code and bytecode-level portability.
4
Java notes for C++ programmers
• Everything is an object.– Every object inherits from java.lang.Object
• No code outside of class definition!– No global variables.
• Single inheritance– an additional kind of inheritance: interfaces
• All classes are defined in .java files– one top level public class per file
5
More for C++ folks
• Syntax is similar (control structures are very similar).
• Primitive data types similar– bool is not an int.
• To print to stdout:– System.out.println();
6
First Program
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
7
Compiling and Running
HelloWorld.java javac HelloWorld.java
java HelloWorld HelloWorld.class
compile
run
bytecode
source code
8
Java bytecode and interpreter
• bytecode is an intermediate representation of the program (class).
• The Java interpreter starts up a new “Virtual Machine”.
• The VM starts executing the users class by running it’s main() method.
9
A Picture is Worth…
The Interpreter's are sometimes referred to as the Java Virtual Machines
The output of the compiler is .class file
10
PATH and CLASSPATH
• The java_home/bin directory is in your $PATH
• If you are using any classes outside the java or javax package, their locations are included in your $CLASSPATH
12
Java Data Types
• Primitive Data Types:– boolean true or false– char unicode! (16 bits)– byte signed 8 bit integer– short signed 16 bit integer– int signed 32 bit integer– long signed 64 bit integer– float,double IEEE 754 floating point
not an int!
13
Other Data Types
• Reference types (composite)– classes– arrays
• strings are supported by a built-in class named String
• string literals are supported by the language (as a special case).
14
Java Primitive Data TypesData Type
Characteristics Range
byte 8 bit signed integer -128 to 127
short 16 bit signed integer -32768 to 32767
int 32 bit signed integer -2,147,483,648 to 2,147,483,648
long 64 bit signed integer -9,223,372,036,854,775,808 to- 9,223,372,036,854,775,808
float 32 bit floating point number
+ 1.4E-45 to+ 3.4028235E+38
double 64 bit floating point number
+ 4.9E-324 to+ 1.7976931348623157E+308
boolean true or false NA, note Java booleans cannot be converted to or from other types
char 16 bit, Unicode Unicode character, \u0000 to \uFFFF Can mix with integer types
15
Type Conversions
• conversion between integer types and floating point types.– this includes char
• No automatic conversion from or to the type boolean!
• You can force conversions with a cast – same syntax as C/C++.
int i = (int) 1.345;
16
Casting• Casting is the temporary conversion of a variable from its
original data type to some other data type.– Like being cast for a part in a play or movie
• With primitive data types if a cast is necessary from a less inclusive data type to a more inclusive data type it is done automatically.
int x = 5;double a = 3.5;double b = a * x + a / x;double c = x / 2;
• if a cast is necessary from a more inclusive to a less inclusive data type the class must be done explicitly by the programmer– failure to do so results in a compile error.
double a = 3.5, b = 2.7;int y = (int) a / (int) b;y = (int)( a / b );y = (int) a / b; //syntax error
17
Operators
• Assignment: =, +=, -=, *=, …
• Numeric: +, -, *, /, %, ++, --, …
• Relational: ==. !=, <, >, <=, >=, …
• Boolean: &&, ||, !
• Bitwise: &, |, ^, ~, <<, >>, …
Just like C/C++!
18
Control Structures
• More of what you expect:
conditional: if, if else, switch
loop: while, for, do
break and continue (but a little different than with C/C++).
19
Enhanced for loop
• New in Java 5.0• a.k.a. the for-each loop• alternative for iterating through a set of valuesfor(Type loop-variable : set-expression)
statement
• logic error (not a syntax error) if try to modify an element in array via enhanced for loop
20
Enhanced for loop
public static int sumListEnhanced(int[] list){ int total = 0;
for(int val : list){ total += val;
System.out.println( val );}return total;
}
public static int sumListOld(int[] list){ int total = 0;
for(int i = 0; i < list.length; i++){ total += list[i];
System.out.println( list[i] );}return total;
}
21
Method Overloading and Return• a class may have multiple methods with the same
name as long as the parameter signature is unique– may not overload on return type
• methods in different classes may have same name and signature– this is a type of polymorphism, not method overloading
• if a method has a return value other than void it must have a return statement with a variable or expression of the proper type
• multiple return statements allowed, the first one encountered is executed and method ends– style considerations
22
Exceptions
• Terminology:– throw an exception: signal that some
condition (possibly an error) has occurred.– catch an exception: deal with the error (or
whatever).
• In Java, exception handling is necessary (forced by the compiler)!
23
Try/Catch/Finallytry {// code that can throw an exception
} catch (ExceptionType1 e1) { // code to handle the exception} catch (ExceptionType2 e2) { // code to handle the exception} catch (Exception e) { // code to handle other exceptions} finally { // code to run after try or any catch}
24
Exception Handling
• Exceptions take care of handling errors– instead of returning an error, some method
calls will throw an exception.
• Can be dealt with at any point in the method invocation stack.
• Forces the programmer to be aware of what errors can occur and to deal with them.
25
Concurrent Programming
• Java is multithreaded! – threads are easy to use.
• Two ways to create new threads:– Extend java.lang.Thread
• Overwrite “run()” method.
– Implement Runnable interface• Include a “run()” method in your class.
• Starting a thread– new MyThread().start();– new Thread(runnable).start();
26
Classes and Objects
• “All Java statements appear within methods, and all methods are defined within classes”.
• Java classes are very similar to C++ classes (same concepts).
• Instead of a “standard library”, Java provides a lot of Class implementations.
27
Defining a Class
• One top level public class per .java file.– typically end up with many .java files for a
single program.– One (at least) has a static public main()
method.
• Class name must match the file name!– compiler/interpreter use class names to
figure out what file name is.
28
Sample Class (from Java in a Nutshell)
public class Point {public double x,y;public Point(double x, double y) {
this.x = x; this.y=y;}public double distanceFromOrigin(){
return Math.sqrt(x*x+y*y);}
}
29
Objects and new
You can declare a variable that can hold an object:
Point p;
but this doesn’t create the object! You have to use new:Point p = new Point(3.1,2.4);
there are other ways to create objects…
30
Using objects
• Just like C++: – object.method()– object.field
• BUT, never like this (no pointers!)– object->method()– object->field
31
Strings are special
• You can initialize Strings like this:
String blah = "I am a literal ";
• Or this ( + String operator):
String foo = "I love " + "RPI";
32
Arrays
• Arrays are supported as a second kind of reference type (objects are the other reference type).
• Although the way the language supports arrays is different than with C++, much of the syntax is compatible.– however, creating an array requires new
33
Array Examples
int x[] = new int[1000];
byte[] buff = new byte[256];
float[][] mvals = new float[10][10];
34
Notes on Arrays
• index starts at 0.
• arrays can’t shrink or grow.– e.g., use Vector instead.
• each element is initialized.
• array bounds checking (no overflow!)– ArrayIndexOutOfBoundsException
• Arrays have a .length
35
Array Example Code
int[] values;
int total=0;
for (int i=0;i<value.length;i++) {
total += values[i];
}
36
Array Literals
• You can use array literals like C/C++:
int[] foo = {1,2,3,4,5};
String[] names = {“Joe”, “Sam”};
37
Reference Types
• Objects and Arrays are reference types
• Primitive types are stored as values.
• Reference type variables are stored as references (pointers that we can’t mess with).
• There are significant differences!
38
Primitive vs. Reference Types
int x=3;
int y=x;
Point p = new Point(2.3,4.2);
Point t = p;
Point p = new Point(2.3,4.2);
Point t = new Point(2.3,4.2);
There are two copies of the value 3 in memory
There is only one Point object in memory!
39
Passing arguments to methods
• Primitive types: the method gets a copy of the value. Changes won’t show up in the caller.
• Reference types: the method gets a copy of the reference, the method accesses the same object!
40
Example
int sum(int x, int y) {x=x+y;return x;
}
void increment(int[] a) {for (int i=0;i<a.length;i++) {
a[i]++;}
}
41
Packages
• You can organize a bunch of classes and interfaces into a package.– defines a namespace that contains all the
classes.
• You need to use some java packages in your programs– java.lang java.io, java.util