The Java Language: Intro for Software Developers

Preview:

DESCRIPTION

The Java Language: Intro for Software Developers. Phil Miller. (very briefly…) Who is this guy?. Consulting Software Engineer for IBM Global Services since 1999 Worked on parallel processing R&D Projects at Intel 1988-93 BSEE from Purdue, MSCSE from OGI. How do I know about Java?. - PowerPoint PPT Presentation

Citation preview

The Java Language: Intro for Software Developers

Phil Miller

(very briefly…) Who is this guy?

Consulting Software Engineer for IBM Global Services since 1999

Worked on parallel processing R&D

Projects at Intel 1988-93

BSEE from Purdue, MSCSE from OGI

How do I know about Java?

What I do: Java-based software that collects information about IBM-branded servers and sends it to an IBM web site for use by customer service

Why is Java important?

Very wide acceptance and use on the web• Virtually all software companies use Java for

web development• “Everybody but Microsoft”

(.Net …)

Platform independenceVersatilitySimplicity, clarity

Platform IndependenceJava uses a Java Runtime Environment that works the same way on every platform.

Language Standards

Managed by license agreement with Sun Microsystems

Industry standards

The most important concepts in Java: simplicity and clarity

Simplicity is the ultimate sophistication.-- Leonardo da Vinci

Of two equivalent theories or explanations, all other things being equal, the simpler one is to be preferred.-- William of Ockham (Occam’s Razor)

Versatility

Traditional Unix command-line “filter” applications

Graphical User Interfaces

“lightweight applications” for a wide range of frameworks (e.g., “servlets”, “applets”)

“embedded” applications; (cell phones, for example)

Why you’d like Java

It’s harder to write bad programs in Java

It’s hard to write non-OO programs in Java

Most obvious problems are solved by the compiler and the run-time environment

You’d be more productive in Java

How programs are evolving

Typical Unix file-centric, “batch” programming model

cc is the “driver” programcpp preprocessorccom is parser, intermediate code generatoropt is the optimizercgen generates assembly codeas translates to object code ld links together object modules to produce “a.out” file

cc

cpp ccom opt cgen as ld

Typical user interface program

Program responds to user input: “event-driven”

Programs often developed in a framework

Lightweight Applications

Very small, specialized pieces of software that perform a limited operation, then terminate (freeing resources, etc.)

example: a piece of code that understands how to buy a product using a credit card

Think “nanotech”; Java components

What Java looks like

(in comparison with C…)

Hello, World in Cint main(int argc, char **argv) {

char *h = “Hello CS”, *j=“ Winter 2005”; int i = 321;

printf( “%s%d%s!”, h, i, j );}

Note that printf is a special type of function called a varargs function:

int printf( char *, … );

Example: Hello, world

public class hello { public static void main(String[] args) {

String h=“Hello CS”, j=“ Winter 2005”;

int i=321; System.out.println( h + i + j ); }}

Compiler auto-matically converts i to a String

Demo: Java compiler and Java runtime

Java has namespaces

Allow hierarchical folders for source code

Source files use package to specify directory:package edu.pdx

public class yourclass

Java program uses “fully qualified class name”:

java edu.pdx.yourclass

Directories reflect namespace:

edu\pdx\yourclass.class

Demo: Java namespaces

Primitive types in C: integers

Integers: char, signed char, unsigned char, short, short int, signed short, unsigned short, signed short int, unsigned short int, int, signed int, unsigned int, signed long, unsigned long, long int, signed long, unsigned long, signed long int, unsigned long int (29 types)

long >= int >= short

More on integers in C

Typically (but not universally): char is 8 bits, short is 16; int may be 16 or 32, long is 32 bits; the details are specified in limits.h.

char is usually 8 bits, but sometimes 7 or 9

Compiler implementers can make char signed or unsigned as they choose; see example!

how unsigned chars cause portability problems…

/* runs ∞ if char is unsigned… */

int main() {char ch;while ((ch = getchar()) != EOF) putchar(ch);

}

Primitive data types in Java

boolean, byte, char, short, int, long, float, and double (8 types)

no notion of “unsigned”

Everything else is an object instance…

type size signed? Default value

boolean 1/8 n/a false

byte 8 yes 0

char 16 NO ‘\u0000’

short 16 yes 0

int 32 yes 0

long 64 yes 0L

float 32 yes 0.0f

double 64 yes 0.0d

Objects (classes)

Java has a class hierarchy with the class Object as the superclass of every other class

Java does not have multiple inheritance; it has single inheritance (i.e., inherited behavior) and interfaces (i.e., specified, required behavior)

Some common classes

String is a very commonly used object

There are “wrapper” classes for primitive types to make them work like objects:

Boolean, Byte, Character, Short, Integer, Long, Float, and Double are wrappers for boolean, byte, char, short, int, long, float, and double.

What EVERY Object can do

clone - Creates and returns a copy of this object. equals – Compares two objects for equalityfinalize - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.getClass - Returns the runtime class of an object.hashCode – Used in hashing algorithms to categorize & sort objects.notify - Wakes up a single thread that is waiting on this object.notifyAll - Wakes up all threads that are waiting on this objectwait - Causes current thread to wait until another thread invokes notify or notifyAll.

toString – Provides a string representation of an object

The toString method

All Java objects support a method toStringIt returns a String representation of the objectThis is most noticeable (and useful) when doing I/O:

Object foo = new Object();System.out.println(“foo = “ + foo);

The “toString” is implied in a “string context”

Java Reflection

Array – Dynamically create and access arrays

Constructor – Dynamically construct objects

Field – Provides information about (and access to) a single field (variable) of a class or an interface.

Method – Provides information about a method in a class or interface; allows execution of a method.

Modifier – Provides a way to decode and modify the access of members of an object.

Java Beans (Java Reflection at work)

Java beans are heavily used in web applicationsJava beans use conventions for variable definition to provide access to methods and fields.

Example:

A field called fooBar can be accessed by accessor method getFooBar(); a program using the bean uses reflection (aka introspection) to gain access to fooBar

Simplicity and Clarity revisited

C/C++ sources are typically divided into 3 parts: implementation: the actual C/C++ code,typically in a file with suffix “.cpp”declarations: the description of the C/C++ code, typically with suffix “.h”documentation: an explanation of how the code can be used, typically “.man”

Javadoc – developer documentation

Everything you need to know about a class is contained in one file with suffix “.java”.

Specially formatted comments describe the code:

/** Slash-star-star starts a javadoc comment and star-slash ends it. */

Javadoc demo

Inheritance and polymorphism in Java

class Pet { … }

class Dog extends Pet { … }

class Cat extends Pet { … }

Pet p = new Cat();…

p = new Dog();

if ( p instanceof Dog ) ….

Collection classes in Java

Built-in support for dynamic arrays, associative maps, B-trees, sets, ….All collection classes are polymorphic

ArrayList al = new ArrayList();al.add( "hello " );al.add( "CS321 " );al.add( "Winter 2005 " );System.out.println( "al now has " + al.size() + " elements." );

// get things out of a collectionStringBuffer sb = new StringBuffer();for (Iterator iter=al.iterator();

iter.hasNext(); ) { String x = (String) iter.next(); sb.append( x );}

System.out.println( sb.toString() );

Demo: Eclipse

Free java development environment available from www.eclipse.org

Garbage Collection in Java

Unlike other languages, you don’t “free” objects in Java.

When an object goes “out of scope”, it’s available for GC:

if ( expr == true) { String abc = “abc”; }// abc is “out of scope” HERE.

Also, when all references to an object are removed, it becomes available for GC

An example of garbage collection using Strings

String myName = “Phil”; // line 1

// other code…

myName = “Miller”; // line 2

1. The string “Phil” is an immutable object; once it’s created, it’s not possible to change it.

2. “Phil” becomes an object with no references, and the garbage collector eventually reclaims it.

An interesting optimization using StringBuffer

What the compiler sees:String abc =

“This “ + “is “ + “a “ + “long “ + “string”;

This is actually wasteful; five strings are created, then immediately handed over to the garbage collector.

What the compiler does:

StringBuffer $1 = new StringBuffer();$1.append(“This “); $1.append(“is “);$1.append(“a “); $1.append(“long “);$1.append(“string”);String abc = $1.toString();

Design Patterns

A design methodology that promotes standard solutions to everyday problems.

Provides terminology for discussing designs.

This book can be downloaded in PDF form for free:http://www.patterndepot.com/put/8/JavaPatterns.htm

Another example: Hello, world JSP application (“servlet”)

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class MyHello extends HttpServlet implements Servlet { public MyHello() { super(); }

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( "text/html" ); PrintWriter out = res.getWriter(); out.println( "<HTML>" ); out.println( "<HEAD><TITLE>Hello, World</TITLE></HEAD>" ); out.println( "<BODY>" ); out.println( "<BIG>Hello, World</BIG>" ); out.println( "</BODY></HTML>" ); }

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { }

Summary

Learn Java to enjoy the good life!

Resources

Java development environment:http://java.sun.com

Integrated development environment:http://eclipse.org

Open-source web server, application server, etc.:http://apache.org

Design Patterns:http://www.dofactory.com/Patterns/Patterns.aspxhttp://www.industriallogic.com/papers/learning.htmlhttp://www.patterndepot.com/put/8/JavaPatterns.htm