1 / 61

Java

Java. What, Why and How …. 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

leeannr
Download Presentation

Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java What, Why and How…

  2. 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

  3. הבהרה • בשני השיעורים הקרובים נעבור על יסודות שפת Java . • מטרתם היא הקניית כלים שישמשו אתכם ברכישת השפה.מילים המסומנות כך מהוות קישור שיפתח בפניכם עולם ומלואו... • כמעט על כל פרק ניתן להרחיב הרבה מעבר למופיע במצגת... • רשימת הנושאים בשקף הבא הינה הבסיס שיילמד. בתוספת לימוד עצמי להרחבתו (בעזרת הקישורים) תרכשו רמה התחלתית טובה לעבודה עם Java.

  4. בשני השיעורים הקרובים... • (Essential) Java Classes: • Exceptions • Basic I/O • Eclipse • Examples • Java Vs. C++ • Why Java? • (Introduction to) Java: • OOP • Language Basics • Classes & Objects • Interfaces & Inheritance • Numbers & strings • Naming conventions • Javadoc • Packages

  5. Java is (an interpreted) write once, run anywhere language. Java Vs. C++ The .class files generated by the compiler are not executable binaries. Instead, they contain “byte-codes” to be executed by the Java Virtual Machine.

  6. 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.

  7. Java Vs. C++ • Java has no preprocessor. • If you want to use classes in another library, you say import and 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.

  8. 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.

  9. Java Vs. C++ • 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,...

  10. So, Why Java? Java is for many reasons a highly suitable framework for Web and XML programming: Platform Independent Safe runtime model(for example: array bound checks, automatic garbage collection) It’s sandboxing security mechanism makes it easier to safely execute non-trusted code.

  11. Why Java? Cont. • A good support for multi-threading and concurrency control (useful for both client and servers development) Natively supports Unicode. Supports data migration and dynamic class loading. Comes with powerful libraries for network programming 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)

  12. Let’s Java!

  13. First Example - SimpleClient

  14. What Is an Object? An object is a software bundle (חבילה) of related state and behavior.

  15. 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

  16. 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.

  17. 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.

  18. Example

  19. 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.

  20. What is API? 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.

  21. Most Basic Program Structure import …; public class SomethingOrOther { public static void main(String [] args) { … statements… } } This must be in a file named SomethingOrOther.java !

  22. 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…

  23. HelloWorld (standalone) public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

  24. Running on Unix:

  25. 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.

  26. The resulting HTML from running Javadoc is: Javadoc Example

  27. Primitive data types are like C • Main data types are int, double, boolean, char • Also have byte, short, long, float • booleanhas valuestrue andfalse • Declarations look like C, for example, • double x, y; • int count = 0;

  28. 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

  29. 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 !

  30. 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.

  31. 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!

  32. 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.

  33. fields Concatenation method An example of a class class Person { String name; int age; void birthday ( ) { age++; System.out.println (name + ' is now ' + age); }}

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

  35. An array is an object • int myArray[ ] = new int[5]; or: • int myArray[ ] = {1, 4, 9, 16, 25}; • String languages [ ] = {"Prolog", "Java"};

  36. 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.

  37. The “final” keyword • 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;

  38. Essential Java classes Exceptions, Basic I/O

  39. 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.

  40. 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.

  41. Try & Catch Blocks try {…} catch (ExceptionType name) {… } catch (ExceptionType name) {…} … • 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.

  42. 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.

  43. Example:

  44. 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 - catchblock, which will handle the exception within the method and a throwsclause which would in turn throw the exception to the caller to handle.

  45. A Question

  46. 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

  47. Byte Streams • 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.

  48. 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.

  49. 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.

  50. 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.

More Related