Learning Java 1: Introduction Christopher Swenson Center for Information Security University of Tulsa 600 S. College Ave Tulsa, OK 74104
Learning Java Based on  Learning Java , by  Niemeyer and Knudsen Quick and Dirty overview of Java fundamentals and advanced  programming Introduction Objects and Classes Generics, Core Utilities Threads, Synchronization I/O, Network Programming Swing
Overview (Ch. 1–5) Java Hello World! Using Java Java Language Objects
Java Modern, Object-Oriented (OO) Language with C-like syntax Developed at Sun Microsystems (James Gosling, Bill Joy) in the early 1990s Virtual Machine Intermediate bytecode Extremely portable Surprisingly fast (comparable to C++) Features HotSpot on-the-fly native compiling Safe and Clean Dynamic Memory Management Robust Error Handling http://java.sun.com http://java.sun.com/j2se/1.5.0/docs/api/
Let’s Go! Standard CLI utilities, although IDEs and GUIs exist (Eclipse, Netbeans) Windows: Start    Run    “ cmd ” UNIX / OS X: Open up a command terminal “ javac HelloJava.java ” Compiles the file  HelloJava.java Outputs executable  .class  files
HelloJava.java public class HelloJava { public static void main(String[] args) { System.out.println(“Hello World!”); } } Run with: java -cp . HelloJava Outputs: Hello World!
Some Notes public class HelloJava  { … Everything in Java must be in a class (container for code and data). public static void main(String[] args){ … This is a method (which contains executable code). The function called from the command-line is required to be  main . Takes a  String  array (the arguments), and returns nothing ( void ). System.out.println(“Hello World!”); System  is a class that contains a lot of useful system-wide tools, like standard I/O, and its  out  class represents standard out. The  println  method of out (and all  PrintStream  objects) prints the  String  containted within, followed by a newline. java -cp . HelloJava Invokes the Java Virtual Machine (JVM) to execute the  main  of the named class ( HelloJava ). Searches the current directory for the class file ( -cp . ).
Comments /* */  C-style comments are also supported /** */  are special JavaDoc comments Allow automatic documentation to be built from source code, using the  javadoc  utility. //  C++-style comments are preferred Less ambiguity Simpler
Variables String s = “string”; int a = -14; long b = 5000000000l; float c = 2.5f; double d = -4.0d; byte e = 0x7f; char f = ‘c’; short g = -31000; boolean h = true; int s are signed 32-bit long s are signed 64-bit float s are signed 32-bit double s are signed 64-bit byte s are signed 8-bit char s are signed 16-bit short s are signed 16-bit boolean s are 1-bit, either  true  or  false
Operators Standard arithmetic operators for ints, longs, shorts, bytes, floats and doubles + - * / % << >> >>> Boolean operators for non-floating point & | ^ ~ Logical operators for  boolean s && || ^^ ~ Comparisons generate  boolean s == < <= > >= != Can be suffixed with  =  to indicate an assignment a = a + b      a += b ++   and   --   operators also ( a = a - 1      a-- ) Ternary Operator: (a >= b) ? c : d      if (a >= b) c else d
Reference Types Reference Types are non-primitive constructs Includes  String s Consist of variables and methods (code) Typically identified with capital letter Foo bar = new Foo(); Use the  new  keyword to explicitly construct new objects Can take arguments No need for destructor or to explicitly remove it No pointers C++:  Foo &bar  = *(new Foo());
String Strings are a reference type, but  almost  a primitive in Java String s = “this is a string”; No need for  new  construction Overloaded + operator for concatenation String s = “a” + “ kitten
”;
Coercion Coercion = automatic conversion between types Up is easy ( int  to  double , anything to  String ) Down is hard int i = 2; double num = 3.14 * i; String s = “” + num; int a = Integer.parseInt(t);
Expressions and Statements An statement is a line of code to be evaluated a = b; An statement can be made compound using curly braces { a = b; c = d; } Curly braces also indicate a new scope (so can have its own local variables) Assignments can also be used as expressions (the value is the value of the variable after the assignment) a = (b = c);
if-then-else  statements if (bool) stmt1; if (bool) stmt1 else statement2; if (bool) stmt1 else if stmt2 else stmt3; if (bool) { stmt1; … ; } … if  (i == 100) System.out.println(i);
Do-while loops while (bool) stmt; do stmt; while (bool); boolean stop = false; while  (!stop) { // Stuff if (i == 100) stop = true; }
for  loops for  ( prestmt ;  bool ;  stepstmt ;)  stmt ; =  {  prestmt ; while ( bool ) {  stmt ;  stepstmt ; } } for (int i = 0; i < 10; i++) { System.out.print(i + “ “); } Outputs: “ 0 1 2 3 4 5 6 7 8 9   ”
switch  statement switch  ( int expression ) { case   int_constant :   stmt ; break ; case   int_constant :   stmt ; case   int_constant :   stmt ; default:   stmt ; }
Arrays int []  array =  { 1,2,3 } ; int []  array =  new int[ 10 ]; for (int i = 0; i <  array.length ; i++) array [ i ]  = i; Array indices are from 0 to (length – 1) Multi-dimensional arrays are actually arrays of arrays: int [][]  matrix = new int [3][3]; for (int i = 0; i <  matrix.length ; i++) for (int j = 0; j <  matrix[i].length ; j++) System.out.println(“Row: “ + i + “, Col: “ + j + “ = “ + matrix [i][j] );
enum s What about something, like size? Pre-Java 1.5,  int small = 1, medium = 2, … But what if  mySize == -14 ? enum  Size {Small, Medium, Large}; Can also do switch statements on enums switch (mySize) { case Small:  // … default:  // … }
Loop breaking break  breaks out of the current loop or switch statement while (!stop) { while (0 == 0) { break ; } // Execution continues here }
Loop continuing continue  goes back to the beginning of a loop boolean stop = false; int num = 0; while (!stop) { if (num < 100)  continue ; if (num % 3) stop = true; }
Objects class  Person { String name; int age; } Person me =  new  Person(); me.name = “Bill”; me.age = 34; Person[] students = new Person[50]; students[0] = new Person();
Subclassing class Professor  extends  Person { String office; } Professor bob = new Professor(); bob.name = “Bob”; bob.age = 40; bob.office = “U367”; However, a class can only “extend” one other class
Abstract Classes If not all of its methods are implemented (left abstract), a class is called abstract abstract  class Fish { abstract  void doesItEat(String food); public void swim() { // code for swimming } }
Interfaces class MyEvent  implements  ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println(“My Action”); } } Can implement multiple interfaces Interfaces have abstract methods, but no normal variables
Static and final A  static  method or variable is tied to the class, NOT an instance of the class Something marked  final  cannot be overwritten (classes marked final cannot be subclassed) class Person { public  final static  int version = 2; static  long numberOfPeople = 6000000000; static void birth() { numberOfPeople++; } String name; int age; } // … in some other code Person.numberOfPeople++; System.out.println(“Running Version “ + Person.version + “ of Person class);
Special functions All classes extend the Object class Classes have built-in functions: equals(Object obj), hashCode(), toString() Equals used to determine if two objects are the same o == p  – checks their memory addresses o.equals(p)  – runs  o.equals() hashCode()  – used for hash tables ( int ) toString()  – used when cast as a  String  (like printing)
Packages Classes can be arranged into packages and subpackages, a hierarchy that Java uses to find class files Prevents naming issues Allows access control By default, a null package Doesn’t work well if you need more than a few classes, or other classes from other packages java.io  – Base I/O Package java.io.OutputStream  – full name Declare a package with a  package  keyword at the top Import stuff from package with the import keyword import java.io.*; import java.util.Vector; import static java.util.Arrays.sort;
Using Packages Compile like normal Packages = a directory Java has a “classpath”: root directories and archives where it expects to look for classes Example java -cp compiled swenson.MyServer In the the “compiled” directory, look for a class MyServer in the subfolder “swenson” /compiled/swenson/MyServer.class Also need to specify  -classpath  when compiling Class files can also be put into ZIP files (with a suffix of JAR instead of ZIP)
Permissions public  – accessible by anyone  protected  – accessible by anything in the package, or by subclasses (default) – accessible by anything in the package private  – accessible only by class
Coding Style class Test { public static void main(String[] args) { if (args.length > 0) System.out.println(“We have args!”); for (int i = 0; i < args.length; i++) { int q = Integer.parseInt(args[i]); System.out.println(2 * q); } System.exit(0); } }
Tools: Eclipse Popular Auto Complete Fancy Multi-language
Tools: NetBeans Another good GUI Full-featured Java-centric
Tools: JSwat Debugger
emacs
vi
TextPad
Homework Download Java Download a GUI and learn it (e.g., Eclipse) Implement a Card class enum s for Suit hashCode()  should return a different value for two different cards, but should be the same for two instances of the same card (e.g., Jack of Diamonds) Write a program that builds a deck and deals 5 cards to 4 different players toString()  should work so you can use System.out.println() to print out a deck, hand, or a card