61
1 Introduction to Java CS 236369, Spring 2010

1 Introduction to Java CS 236369, Spring 2010. 2 הבהרה בשני השיעורים הקרובים נעבור על יסודות שפת Java. מטרתם היא הקניית כלים

  • View
    220

  • Download
    0

Embed Size (px)

Citation preview

1

Introduction to Java

CS 236369, Spring 2010

2

הבהרה בשני השיעורים הקרובים נעבור על יסודות שפת

Java.

מטרתם היא הקניית כלים שישמשו אתכם ברכישתמהוות קישור שיפתח המסומנות כךמילים השפה.

בפניכם עולם ומלואו...

כמעט על כל פרק ניתן להרחיב הרבה מעבר למופיעבמצגת...

.רשימת הנושאים בשקף הבא הינה הבסיס שיילמדבתוספת לימוד עצמי להרחבתו )בעזרת הקישורים(

.Javaתרכשו רמה התחלתית טובה לעבודה עם

3

בשני השיעורים הקרובים... Java Vs. C++ Why Java? )Introduction to( Java:

OOP Language Basics Classes & Objects Interfaces & Inheritance Numbers & strings Naming conventions Javadoc Packages

)Essential( Java Classes: Exceptions Basic I/O

Eclipse Examples

4

Java Vs. C++

Java is )an interpreted( write once, run anywhere language.

The .class files generated by the compiler are not executable binaries. Instead, they contain “byte-codes” to be executed by the Java Virtual Machine.

5

Java Vs. C++ Everything must be in a class.

There are no global functions or global data. If you want the equivalent of globals, make static methods and static data within a class.

There are no structs or enumerations or unions, only classes.

Java has both kinds of comments like C++ does.

Java has built-in support for comment documentation - Javadoc.

6

Java Vs. C++

Java has no preprocessor. If you want to use classes in another library, you use import

with the name of the library. There are no preprocessor-like macros.

All the primitive types in Java have specified sizes that are machine independent for portability.

There are Strings in JAVA Strings are represented by the String-class, they aren‘t only some

renamed pointers.

7

Java Vs. C++ There is a garbage collection in JAVA

Garbage collection means memory leaks are much harder to cause in Java, but not impossible. )If you make native method calls that allocate storage, these are typically not tracked by the garbage collector.(

The garbage collector is a huge improvement over C++, and makes a lot of programming problems simply vanish. It might make Java unsuitable for solving a small subset of problems that cannot tolerate a garbage collector, but the advantage of a garbage collector seems to greatly outweigh this potential drawback.

There are no destructors in Java. There's no need because of garbage collection.

8

Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object. The inheritance of properties of different classes is handled by

interfaces.

Java contains standard libraries for solving specific tasks. C++ relies on non-standard third-party libraries. These tasks include:

Networking, Database Connection )via JDBC( Compression, Commerce Whatever you want: VoIP, Video-Telephony, MIDI, Games,...

Java Vs. C++

9

So, Why Java?Java is for many reasons a highly suitable framework for

Web and XML programming:

It’s sandboxing security mechanism makes it easier to safely execute non-trusted code

Safe runtime model)for example: array bound checks, automatic garbage collection(

Platform Independent

10

Why Java? Cont. A good support for multi-threading and concurrency control

)useful for both client and servers development(

Not Convinced? Try comparing this list with the features of other languages such as C, Perl, VB, PHP. )C# has been designed to compete with Java(

Comes with powerful libraries for network programming

Supports data migration and dynamic class loading

Natively supports Unicode

11

Let’s Java!

12

First Example - SimpleClient

13

What Is an Object?

An object is a software bundle )חבילה( of related state and behavior.

14

What is a class? A class is a blueprint or prototype from which objects

are created.

A class consists of a collection of fields, or variables, very much like the named

fields of a struct all the operations )called methods( that can be performed on

those fields can be instantiated

A class describes objects and operations defined on those objects

15

What Is Inheritance?Classes inherit state and behavior from their

superclasses, and one class can be derived from another using the simple syntax provided by Java.

16

Interface

What Is an Interface? An interface is a contract between a class and the outside

world. It defines a protocol of communication between two objects.

An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions.

A class that implements an interface must implement all the methods declared in the interface.

17

Example

18

What Is a Package?A package is a namespace for organizing classes and

interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage.

19

The Java platform provides an enormous class library )a set of packages( suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short.

The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java Platform 6, Standard Edition. Load the page in your browser and bookmark it

What is API?

20

Most Basic Program Structureimport …;

public class SomethingOrOther {

public static void main(String [] args) {

… statements…

}

}

This must be in a file named SomethingOrOther.java !

21

Building Standalone JAVA Programs (on UNIX)

Prepare the file foo.java using an editor Invoke the compiler: javac foo.java This creates foo.class Run the java interpreter: java foo Fortunately we will use Eclipse…

22

HelloWorld (standalone)

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

System.out.println("Hello World!"); }}

23

Running on Unix:

24

Comments are almost like C++ /* This kind of comment can span multiple lines */ // This kind is to the end of the line /**

* This kind of comment is a special * ‘javadoc’ style comment */

Javadoc is a tool for generating API documentation in HTML format from doc comments in source code.

Javadoc Example

The resulting HTML from running Javadoc is:

26

Primitive data types are like C Main data types are int, double, boolean, char Also have byte, short, long, float boolean has values true and false Declarations look like C, for example,

double x, y; int count = 0;

27

Expressions are like C

Assignment statements mostly look like those in C; you can use =, +=, *= etc.

Arithmetic uses the familiar + - * / % Java also has ++ and -- Java has boolean operators && || ! Java has comparisons < <= == != >= >

Java does not have pointers or pointer arithmetic

28

Control statements are like C

if (x < y) smaller = x; if (x < y){ smaller=x;sum += x;}else { smaller = y; sum += y; }

while (x < y) { y = y - x; } do { y = y - x; } while (x < y) for (int i = 0; i < max; i++) sum += i;

Switch… BUT: conditions must be boolean !

29

Still, Java isn't C

In C, almost everything is in functions.

In Java, everything is in classes.

There must be only one public class per file.

30

Naming conventions Java is case-sensitive; maxval, maxVal, and MaxVal are three

different names

Class names begin with a capital letter

All other names begin with a lowercase letter

Subsequent words are capitalized: theBigOne

Underscores are not used in names

These are very strong conventions!

31

The class hierarchy

Classes are arranged in a hierarchy. The root, or topmost, class is Object. Every class but Object has at least one superclass. A class may have subclasses. Each class inherits all the fields and methods of

its )possibly numerous( superclasses.

32

An example of a class

class Person { String name; int age;

void birthday ( ) { age++; System.out.println (name + ' is now ' + age); }}

fields

method

Concatenation

33

Creating and using an object

Person john;john = new Person ( );john.name = "John Smith";john.age = 37;

Person mary = new Person ( );mary.name = "Mary Brown";mary.age = 33;mary.birthday ( );

34

An array is an object

int myArray[ ] = new int[5];or:

int myArray[ ] = {1, 4, 9, 16, 25};

String languages [ ] = {"Prolog", "Java"};

35

The “static” keyword Static Fields:Used for creating variables that are common to all objects of the same

class. Fields that have the static modifier in their declaration are called static fields or class variables.

Static Methods:Static methods, which have the static modifier in their declarations,

should be invoked with the class name, without the need for creating an instance of the class, as in ClassName.methodName(args) .

A common use for static methods is to access static fields.

36

final means, this value won't be changed hereafter.

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.

static final double PI = 3.141592653589793;

The “final” keyword

37

Essential Java classes

Exceptions, Basic I/O

38

Exceptions

Definition:  An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

39

Exceptions

After a method throws an exception, the runtime system attempts to find something to handle it. The list of methods is known as the call stack .

)The Catch or Specify Requirement ( Code that might throw certain exceptions must be enclosed by either of the following: A try statement that catches the exception. The

try must provide a handler for the exception. A method that specifies that it can throw the

exception. The method must provide a throws clause that lists the exception.

40

Try & Catch Blocks

To associate an exception handler with a try block, you must put a catch block after it.

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.

try {…}

catch (ExceptionType name) {… } catch (ExceptionType name) {…}

41

The finally block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.

Example:

43

Throwing Exception

Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases, however, it's better to let a method further up the call stack handle the exception.

Thrown exception can be handled in two ways: a try - catch block, which will handle the exception within the method and a throws clause which would in turn throw the exception to the caller to handle.

44

A Question

45

Basic I/O – I/O Streams

An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.

Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects.

A stream is a sequence of data.

We'll now see the most basic kind of streams

46

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.

There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

Byte Streams

Notice that read() returns an int value. If the input is a stream of bytes, why doesn't read() return a byte value? Using an int as a return type allows read() to use -1 to indicate that it has reached the end of the stream.

48

Always close streams - Closing a stream when it's no longer needed is very important — so important that CopyBytes uses a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to use character streams.

So why talk about byte streams? Because all other stream types are built on byte streams.

49

I/O from the Command Line

The Java platform supports three Standard Streams: Standard Input, accessed through System.in; Standard Output, accessed through System.out; and Standard Error, accessed through System.err.

You might expect the Standard Streams to be character streams, but, for historical reasons, they are byte streams.

50

System.out and System.err are defined as PrintStream objects which utilizes an internal character stream object to emulate many of the features of character streams.

By contrast, System.in is a byte stream with no character stream features. To use Standard Input as a character stream, wrap System.in in InputStreamReader:

InputStreamReader cin = new InputStreamReader(System.in);

51

Classpath

The Classpath is an argument set on the command-line that tells the Java Virtual Machine where to look for user-defined classes and packages in Java programs.

Basic examples from Wikipedia.

52

Eclipse

הכרות ראשונה

Workbench Terminology

Tool bar

PerspectiveandFast Viewbar

ResourceNavigatorview

Stackedviews

Propertiesview

Tasksview

Outlineview

Bookmarksview

Menu bar

Messagearea

EditorStatusarea

Texteditor

54

Java Perspective

Javaproject

package

class

field

method

Javaeditor

55

Browse type hierarchies

Typehierarchy

Selectedtype’s

members

56

Java Editor

Hovering over identifier shows Javadoc spec

57

Method completion in Java editor

List of plausible methods Doc for method

Java Editor

On-the-fly spell check catches errors early

Preview

Clickto seefixes

ProblemQuickfixes

Java Editor

Eclipse Java Debugger Run or debug Java programs – Debug

Perspective

Threads and stack

frames

Editor with breakpoint

marks

Console I/O

Local variables

60

Let’s try some…

Enough with presentation, now for some examples using Eclipse.

61

Resources used for this presentation

http://java.sun.com/docs/books/tutorial/ http://knight.cis.temple.edu/~lakaemper/courses/

cis068_2003/slides/cis068_JAVAvsCPP.ppt http://www.csee.umbc.edu/331/spring03/0101/lectures/

java01.ppt http://www.cis.upenn.edu/~matuszek/cit591-2004/

Lectures/eclipse.ppt An Inrtoduction to XML and Web Technologies –

Course’s Literature