Transcript
Page 1: Learning Java 1 – Introduction

Learning JavaLearning 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

Page 2: Learning Java 1 – Introduction

Overview (Ch. 1–5)Overview (Ch. 1–5)

• Java• Hello World!• Using Java• Java Language• Objects

Page 3: Learning Java 1 – Introduction

JavaJava

• 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/

Page 4: Learning Java 1 – Introduction

Let’s Go!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

Page 5: Learning Java 1 – Introduction

HelloJava.javaHelloJava.java

public class HelloJava{

public static void main(String[] args){

System.out.println(“Hello World!”);}

}

Run with:java -cp . HelloJava

Outputs:Hello World!

Page 6: Learning Java 1 – Introduction

Some NotesSome 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 .).

Page 7: Learning Java 1 – Introduction

CommentsComments

• /* */ 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

Page 8: Learning Java 1 – Introduction

VariablesVariables

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;

ints are signed 32-bitlongs are signed 64-bitfloats are signed 32-bitdoubles are signed 64-

bitbytes are signed 8-bitchars are signed 16-bitshorts are signed 16-bitbooleans are 1-bit, either true or false

Page 9: Learning Java 1 – Introduction

OperatorsOperators

• Standard arithmetic operators for ints, longs, shorts, bytes, floats and doubles– + - * / % << >> >>>

• Boolean operators for non-floating point– & | ^ ~

• Logical operators for booleans– && || ^^ ~– Comparisons generate booleans

• == < <= > >= !=

• 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

Page 10: Learning Java 1 – Introduction

Reference TypesReference Types

• Reference Types are non-primitive constructs– Includes Strings

• 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());

Page 11: Learning Java 1 – Introduction

StringString

• 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\n”;

Page 12: Learning Java 1 – Introduction

CoercionCoercion

• 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);

Page 13: Learning Java 1 – Introduction

Expressions and Expressions and StatementsStatements

• 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);

Page 14: Learning Java 1 – Introduction

if-then-elseif-then-else statementsstatements

• 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);

Page 15: Learning Java 1 – Introduction

Do-while loopsDo-while loops

• while (bool) stmt;• do stmt; while (bool);

boolean stop = false;while (!stop){

// Stuffif (i == 100) stop = true;

}

Page 16: Learning Java 1 – Introduction

forfor loops 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 ”

Page 17: Learning Java 1 – Introduction

switchswitch statement statement

switch (int expression){

case int_constant: stmt;break;case int_constant: stmt;case int_constant: stmt;default: stmt;

}

Page 18: Learning Java 1 – Introduction

ArraysArraysint[] 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]);

Page 19: Learning Java 1 – Introduction

enumenumss

• 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: // …

}

Page 20: Learning Java 1 – Introduction

Loop breakingLoop breaking

• break breaks out of the current loop or switch statement

while (!stop) {while (0 == 0) {

break;}// Execution continues here

}

Page 21: Learning Java 1 – Introduction

Loop continuingLoop 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;

}

Page 22: Learning Java 1 – Introduction

ObjectsObjects

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();

Page 23: Learning Java 1 – Introduction

SubclassingSubclassing

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

Page 24: Learning Java 1 – Introduction

Abstract ClassesAbstract 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}

}

Page 25: Learning Java 1 – Introduction

InterfacesInterfaces

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

Page 26: Learning Java 1 – Introduction

Static and finalStatic 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);

Page 27: Learning Java 1 – Introduction

Special functionsSpecial 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)

Page 28: Learning Java 1 – Introduction

PackagesPackages

• 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;

Page 29: Learning Java 1 – Introduction

Using PackagesUsing 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)

Page 30: Learning Java 1 – Introduction

PermissionsPermissions

• 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

Page 31: Learning Java 1 – Introduction

Coding StyleCoding Styleclass 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);

}}

Page 32: Learning Java 1 – Introduction

Tools: EclipseTools: Eclipse

• Popular• Auto

Complete

• Fancy• Multi-

language

Page 33: Learning Java 1 – Introduction

Tools: NetBeansTools: NetBeans

• Another good GUI

• Full-featured

• Java-centric

Page 34: Learning Java 1 – Introduction

Tools: JSwatTools: JSwat

• Debugger

Page 35: Learning Java 1 – Introduction

emacsemacs

Page 36: Learning Java 1 – Introduction

vivi

Page 37: Learning Java 1 – Introduction

TextPadTextPad

Page 38: Learning Java 1 – Introduction

HomeworkHomework

• Download Java• Download a GUI and learn it (e.g.,

Eclipse)• Implement a Card class

– enums 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