1 / 130

Introduction to Java

Introduction to Java. Dr. Billy Lim Applied Computer Science Department Illinois State University. Objectives. Upon completion of this course, you will be able to Understand the architecture of Java technology Use the various programming language features of Java

blair-cain
Télécharger la présentation

Introduction to 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. Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

  2. Objectives • Upon completion of this course, you will be able to • Understand the architecture of Java technology • Use the various programming language features of Java • Develop basic Java applications • Write OO applications using Java

  3. Why Java? • Observations … • 4 million Java programmers and the community is growing at the rate of 30 percent a year • Java is now running on everything from smart cards to the Mars Rover • Java 2 Platform, Standard Edition v 1.4 hits the million mark • In less than a month, the latest version of J2SE has been downloaded over a million times • More than 20,000 attendees in a recent Java developer conference (JavaOne) • 100-million Java Consortium formed by some of the biggest software companies (IBM, Oracle, …) • Number of Fortune 500 adopting Java • More than 1/2 millions Java developers • … (many many more!)

  4. Java’s Penetration ...

  5. History of Java • “Java’s ancestor was a toaster!” • Began life as a programming language for consumer electronics • C/C++ not up to task! (not chip-independent)

  6. History of Java (2) • 1990: James Gosling at Sun designing a language called “Oak”, a small, reliable, architecture-independent language • 1993: WWW appeared and took Internet “by storm” • Gosling and his team thought, “hey, this is bigger than we thought.”

  7. History of Java (3) • Sun wrote a new WWW browser named HotJava • First browser to support Java applets However, only “alpha” Java API • Netscape later announced Java support • Later a beta API, and soon a Java 1.0 API released • The rest is history

  8. What is Java? • From “The Java Language: A White Paper” (by Sun): “A simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language”

  9. Simple • What’s simple? • Can learn quickly • Looks familiar • Poor programming features removed (e.g., no goto) • No pointers • Garbage collection - no memory leaks

  10. Object-Oriented • OO is ubiquitous! • Lots of commercially produced code in C++ (and Java, Smalltalk, etc.) • Focus on data, not procedures • Encapsulates data and functions • More “natural” • Exploits inheritance • (Almost) Everything in Java is an object!

  11. Distributed • Designed to support applications on networks • Applets downloaded over the net • Resources accessed via URLs • Socket class built in • easy to write • clients and servers, collaborative programs • Reliable stream network connections • Furthers goal towards making the network is the computer

  12. Interpreted • Java compiler’s output is in “byte-code” format • Must run an interpreter to run these bytecodes • Java Virtual Machine (JVM) is the interpreter • may be realized by software or hardware • JVM is built into AppletViewer, Netscape, IE, HotJava, etc. These bytecodes are architecture-neutral

  13. Architecture-Neutral • Bytecodes run on any machine, as long as an interpreter exists • Neutrality helps programmers -- no porting required • Unlike C/C++, no implementation-dependent features (e.g., int is always 4 bytes) • Using the AWT, we can create architecture-neutral windowing applications! • Abstract Windowing Toolkit (AWT) and “peer” classes give appropriate “look and feel”

  14. Architecture-Neutral (2) Java Source Java Compiler Java Bytecode JVM JVM JVM JVM Windows Solaris OS390 Mac “Write Once, Run Anywhere”

  15. Robust • Highly reliable • Helped by: • Strong typing features • Object-orientation • Java Memory Model • No Pointers • Garbage Collection • Exception Handling

  16. Secure • Security is very important in networked environments • No pointers • Applet only: Can’t access any computers other than host • Evolving security measures • JDK 1.02: sandbox (e.g., no disk I/O for applets) • JDK 1.1: signed applets • JDK 1.2 and beyond: “security policy” (with the SecurityManager class) • JVM enforces restrictions on applets • JAVA does not stand for “Just Allow Virtually Anything”

  17. Portable • Makes sure there are no implementation-dependent aspects • Strong API • Java compiler: written in Java • Java run-time system: written in ANSI C

  18. High-Performance • Interpreted: won’t be as fast as C (getting closer every day though!) • Performance-critical applications: JIT (“just in time”) compilers • HotSpot technology (Sun), Jikes (IBM) • Native methods • The spectrum: • Tcl/Tk, shells < Java <= C and C++

  19. Multithreaded • Multiple things at once • Supports multiple threads of execution (lightweight processes) • garbage collection thread • sound and animation • Java has built-in support for synchronization primitives • Thread class built in • synchronized keyword

  20. Dynamic • Dynamic class loading, as required, possibly over the net • Classes have run-time information • These classes can be anywhere on the Internet • All of this run-time loading is invisible to user

  21. How Do I Use Java (on the net)? • Web Users • transparent to you • Web Page Designers • use the <APPLET> tag in HTML • thousands of applets out there! • Java Developers • create Java applets, servlets (“server-side applets”), and/or JSP (Java Server Pages)

  22. Java Editions • Free download from http://java.sun.com • J2SE (Java 2 Standard Edition) • J2EE (Java 2 Enterprise Edition) • J2ME (Java 2 Micro Edition)

  23. J2SE

  24. J2SE Software Development Toolkit (SDK) • javac • Java compiler, converts .java to .class • All Java source codes must be stored in files with .java extension • java • Java virtual machine (i.e., the interpreter) • javadoc • generates HTML documentation from Java source files (/** … */ segment) • appletviewer • allows applet to be run outside of a browser • jar • Java archive tool (JDK 1.1 only) • javah • Java C header and stub generator • jdb • Java Debugger

  25. SDK (cont’d) • Java Package Library • java.lang, java.io, java.awt, java.net, java.util, java.applet (JDK 1.02) • java.beans, java.sql, java.rmi, … (a lot more) etc. (JDK 1.1, Java 1.2, Java 1.3) • JDK available in: • Unix platforms • Windows 95/98/NT/2000 • OS/2 • Macintosh • Windows 3.1 • OS 390 And more!!!

  26. Java IDE Tools • Eclipse (Apache Open Source Project) • Based on IBM VisualAge for Java • IBM WebSphere Application Developer (WSAD) • BlueJ • Borland JBuilder • Oracle JDeveloper • Symantec Visual Café • Sun Forte for Java • ...

  27. First Java Program: Hello, World! // This is a comment // The file is named HelloWorld.java publicclass HelloWorld { publicstaticvoid main(String args[]) { System.out.println(“Hello World!”); } } • Note: If the class is public, the name of the class (i.e., HelloWorld) must be the same as the name of the file plus the .java extension (i.e., HelloWorld.java)

  28. main(): Not quite so simple anymore • In Java, we can’t simply write main() • We have to create main as a method in a Java class which returns nothing (void) • Furthermore, we must make this method public and static • public: Anything can call it • static: It belongs to the class itself, not a instance of the class

  29. println explained • What exactly is System.out.println(“...”)? System is a classIt has a class variable named outout refers to an object of type PrintStreamPrintStream objects have an instance method named println QED

  30. package MyPackage; // used if adding class to a package import packageName; // used if a package/class is to be “loaded” accessType class ClassName extends SuperClass { // Field Declarations are given here accessType dataType fieldName; private int salary; // Method Definitions are given here accessType returnType methodName (parameter list) { … // method body } public void print () { System.out.println(“Salary is ” + salary); } } A Java Program Skeleton Bold - keywords ClassName.java Access Types: private public protected default = “friendly”

  31. Applications and Applets • Applications are stand-alone • No security restrictions • Applets are designed for the web • Security restrictions • Integrates with HTML • Shows up in WWW browser In the last few years, two other kinds of Java programs have been introduced – Servlets and JSPs

  32. The “Hello World” Applet // HelloApplet.java import java.awt.*; import java.applet.*; publicclass HelloApplet extends Applet { Font f = new Font(“TimesRoman”, Font.BOLD, 36); publicvoid paint(Graphics g) { g.setFont(f); g.setColor(Color.red); // draw string at x=5, y=50 (pixels) g.drawString(“Hello World!”, 5, 50); } }

  33. Java: The Programming Language

  34. Edit-Compile-Run Cycle in Java .java (source file) Compiler (e.g., javac ) .class (bytecodes) Java VM (e.g., java) output

  35. How to Compile and Run • Compile a source code file by typing javac <filename>.java(e.g., javac HelloWorld.java) • If no compile-time error appears, a .class file is produced. • Run an application by typing java <class name>(e.g., java HelloWorld) Not java HelloWorld.class

  36. Features Similar to C/C++’s • Same comment styles • new: /** to be processed by javadoc … */ • Same literals and data types • new: true and false for the boolean data type • new: strings not null terminated, not mutable • new: numeric sizes and their machine independence • Same operators • Same control structures

  37. Keywords

  38. Java’s Basic Constructs • Comments • // comment on one line • /* comment on one or more lines */ • /** documenting comments */ • Statements • int x; // statement ends with a semicolon (;) • x = 1 + 2;

  39. Primitive Data Types • There are 8 primitive data types in Java • All the numeric types (integer and floating point types) are signed (meaning they can be positive or negative). No unsigned numeric types in Java (unlike C/C++). • Three categories of data types: • Primitive data types • Class data types (coming later) • Interface data types (coming later)

  40. Integers byte (8 bits) short (16 bits) int (32 bits) long (64 bits) Characters char (16 bits Unicode) Floats float (32 bits) double (64 bits) Boolean boolean (1 bit) Strings String (an example of class data type) Basic Data Types Primitive data types capital case (because it is a class, not a primitive)

  41. Identifiers and Literals • Identifiers • case sensitive • have no maximum length • start with a letter, underscore, or dollar sign • e.g., user_name, _file, $money • Literals • numeric: 2 (int), 3L (long), 2.0f (float) 3.14 (double), 077 (octal), 0xDC (hex) • character: ‘a’, ‘t’ • boolean: true, false • string: “hello” Watch out for these!

  42. Booleans • Has value true or false (different from numeric type) • Returned by relational operators • Required for conditional statements • E.g., • // if x is an int • C/C++: if (x) { ...} // OK in C/C++, not OK in Java • Java: if (x == 1) { ...}

  43. Strings • String is a “built-in” class provided by Java • e.g., String s1 = “Hi there!”; • The ‘+’ operator is used for String concatenation • e.g., String s1 = “abc”; • String s2 = s1 + “ ” + s1; • String objects represent constant strings (content cannot be altered) • Many methods supported in the String class

  44. Strings (2) • Examples • String lastName = “Schaefer”; • lastName.length() // gives 8 • lastName.toUpper() // gives “SCHAEFER” • lastName.toLower() // gives “schaefer” • lastName.indexOf(“e”) // gives 4 • lastName.indexOf(“x”) // gives –1 (for not found) • lastName.indexOf(“e”,5) // gives 6 • lastName.substring(2,5) // gives “hae” (1st index is inclusive, 2nd index is exclusive)

  45. Declarations & Assignments // TestDataType.java public class TestDataType { public static void main(String[] args) { int x = 1; float y = 3.1415f; boolean truth = true; char c = ‘X’; String str1 = “Hello”, str2 = “World”, str3; str3 = str1 + str2; System.out.println("x="+x+"y="+y+"truth="+truth+"c="+c+"str3="+str3); System.out.println(“Length of str3 = “ + str3.length()); } } Syntax (first look): objectRef.methodName(argument list) Note: If the + operation has a string involved, a concatenation of all the operands is performed. Java automatically converts all data involved to their string representations.

  46. Operators • Partial list (in order of precedence): • ++, -- • !, (type) • *, /, % • +, - • <, >, <=, >=, instanceof • ==, != (equal to and not equal to operators, respectively) • && (this is the logical AND operator) • || (this is the logical OR operator) • =, *=, /=, +=, ... • ++ (Preincrement, Postincrement) // increments a variable by 1 • e.g., x = 1; System.out.println(x++); // displays 1 • System.out.println(x); // displays 2 • e.g., x = 1; System.out.println(++x); // displays 2 • System.out.println(x); // displays 2 • -- (Predecrement, Postdecrement) // decrements a variable by 1 • e.g., x = 1; System.out.println(x--); // displays 1 • System.out.println(x); // displays 0 • e.g., x = 1; System.out.println(--x); // displays 0 • System.out.println(x); // displays 0

  47. Casting and Promotion • Casting • conversion of one data type to another data type • Two ways to cast in Java: • implicit - Java does it for you automatically • For primitives, if expression on the right differs from the type of the variable on the left, automatic cast will happen if no possibility of losing information. The narrower data type will be promoted to the wider one. • For objects, later on this. • explicit - the programmer must take care of the casting • For primitives, if expression on the right differs from the type of the variable on the left and there is a possibility of losing information. • For objects, later on this.

  48. Promotion and Casting • e.g., // TestDataType2.java int x, y = 1; double z = 1.23; x = y / z; // compilation error x = y / (int) z; // OK x = (int) (y / z); // OK z = x; // OK

  49. Syntax (if, else): if (boolean expr) { statements; } else { statements; } Example: int status; ... if ( status == 1) { deduction = 500; marriedCount ++; } else { deduction = 100; singleCount ++; } Decision Structures Note: else part is optional

  50. Syntax (switch): switch (expr) { case expr1: stmt1; break; case expr2: stmt2; break; default: stmt; break; } Example: switch (status) { case 1: marriedCount++; break; case 2: singleCount ++ break; default: // error; break; } Decision Structures (2)

More Related