1 / 96

Introduction to Java

Learn about Java's characteristics, architecture, and object-oriented programming concepts. Understand Java language basics, variables, data types, and more. Dive into object-oriented programming principles and Java's runtime architecture. Explore inheritance, interfaces, and common programming problems.

eliseob
Download Presentation

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

  2. Java characteristics • Object-oriented • Distributed • Platform independent • Secure • Strongly typed

  3. Java 2 platform • Java virtual machine: execute byte code, just in time (jit) compilation • Java 2 enterprise edition (J2EE): service and enterprise applications • Java 2 standard edition (J2SE): desktop and personal applications • Java 2 Micro edition (J2ME): embedded and consumer devices

  4. J2SE • Java virtual machine: java • Tools: compiler javac, debugger jdb, Java class disassembler javap, documentation generator javadoc, • Core APIs: java.lang, java.util, java.io, java.net, java.security, etc. • GUI APIs: java.awt, javax.swing, javax.sound • Integration APIs: javax.rmi, java.sql (JDBC), javax.naming (JNDI), org.omg.CORBA

  5. J2EE • Superset of J2SE • Java servlet (javax.servlet) and Java Server Pages (JSP) (javax.servlet.jsp) • Enterprise Java Beans (EJB) javax.ejb • Email and messaging services javax.mail • Transaction management javax.transaction

  6. J2ME • Connected device configuration (CDC) for devices with large amount of memory and high network bandwidth • Connected, limited device configuration (CLDC) for devices with limited memory, low bandwidth, intermittent network connections • KVM runs on PDAs and cell phones

  7. Java runtime architecture Java source code Platform independent Java compiler Java byte code Platform dependent byte code compiler Java CPU byte code interpreter native machine code Java machine CPU JVM JVM CPU

  8. Java byte code • Byte code format • pc program counter • optop top of stack • vars local variables • frame execution environment • Garbage-collected heap • RISC like instruction set, 32-bit register • Stack-based architecture opcode (1-byte) operand1 operand2 …

  9. JVM instruction functions • Stack manipulation • Array management • Arithmetic/logical operations • Method invocation/return • Exception handling • Thread synchronization

  10. JVM security • Strong typing: no pointers, array bound checks, dynamic downcast checks • Byte code verification: loaded class files satisfy byte code specification • Run time access control: discretionary access control based on stack inspection, flexible security policy

  11. Java language • Object-Oriented Programming Concepts • Language basics • Object basics and simple data objects • Classes and inheritance • Interfaces and packages • Common problems/solutions

  12. OO programming concepts • What Is an Object? An object is a software bundle of related variables and methods. Software objects are often used to model real-world objects you find in everyday life. • What Is a Message? Software objects interact and communicate with each other using messages. • What Is a Class? A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind. • What Is Inheritance? A class inherits state and behavior from its superclass. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs. • What Is an Interface? An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

  13. Java language • Object-Oriented Programming Concepts • Language basics • Object basics and simple data objects • Classes and inheritance • Interfaces and packages • Common problems/solutions

  14. Language basics • public class BasicsDemo { public static void main(String[] args) { int sum = 0; for (int current = 1; current <= 10; current++){ sum += current; } System.out.println("Sum = " + sum); } }

  15. Language basics • Variables • Operators • Expressions, statements, and blocks • Control flow statements

  16. Variables • Definition:  A variable is an item of data named by an identifier • Data Types • Variable Names • Scope • Variable Initialization • Final Variables

  17. Data types • Primitive Data Types: • Integers: byte, short, int, long (8 – 64 bits) • Real numbers: float, double (32, 64 bits) • Others: char (16 bit unicode), boolean • Arrays, classes, and interfaces are reference types • The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable

  18. Variable names • It must be a legal identifier • It must not be a keyword, a boolean literal (true or false), or the reserved word null • It must be unique within its scope • By Convention: Variable names begin with a lowercase letter and class names begin with an uppercase letter • If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter (for example, isVisible)

  19. Scope • A variable's scope is the region of a program within which the variable can be referred to by its simple name • Scope determines when the system creates and destroys memory for the variable • if (...) { int i = 17; .. } System.out.println("The value of i = " + i); //error

  20. Variable initialization • Local variables and member variables can be initialized with an assignment statement when they're declared • Parameters and exception-handler parameters cannot be initialized in this way. The value for a parameter is set by the caller

  21. Final variable • The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other languages • final int aFinalVar = 0; // or • final int blankfinal; . . . blankfinal = 0;

  22. Language basics • Variables • Operators • Expressions, statements, and blocks • Control flow statements

  23. Operators • Arithmetic Operators: +, -, *, /, %, ++, -- • Relational (>, <, >=, <=, ==, !=) and Conditional Operators (&&, ||, &, |, !, ^) • Shift (<<, >>, >>>) and Bitwise Operators (&, |, ~, ^) • Assignment Operators (=, op =) • Other Operators: op1 ? op2 : op3, new, op1 instanceof op2, [], ., (params), (type)

  24. Expressions, statements, blocks • An expression is a series of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value • A statement forms a complete unit of execution • A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed

  25. Control flow statements Statement Type Keyword looping while, do-while, for decision making if-else, switch-case exception handling try-catch-finally, throw Branching break, continue, label:, return • control flow statement details { statement(s) }

  26. Java language • Object-Oriented Programming Concepts • Language basics • Object basics and simple data objects • Classes and inheritance • Interfaces and packages • Common problems/solutions

  27. Object basics • The Java platform groups its classes into functional packages • Instead of writing your own classes to represent character, string, or numeric data, you should use the classes that are already provided by the Java platform • Most of the classes discussed here are members of the java.lang package

  28. Creating objects Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100); 1.declaration 2.instantiation 3.initialization

  29. Using objects • Directly manipulate or inspect its variables • Call its methods • objectReference.variableName • int height = new Rectangle().height • objectReference.methodName(argumentList); or objectReference.methodName(); • int areaOfRectangle = new Rectangle(100, 50).area();

  30. Cleaning up unused objects • The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection • An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null

  31. Simple data objects • Characters and strings • Numbers • Arrays

  32. Characters and strings • When working with character data, you will typically use either the char primitive type, or one of the following three classes: • String — A class for working with immutable (unchanging) data composed of multiple characters. • StringBuffer — A class for storing and manipulating mutable data composed of multiple characters. This class is safe for use in a multi-threaded environment. • StringBuilder — A faster, drop-in replacement for StringBuffer, designed for use by a single thread only.

  33. Characters • char ch = 'a'; char[] • firstFiveLetters={ 'a', 'b', 'c', 'd', 'e' }; • char ch = string.charAt(i); • //Test whether a character is upper case. if (Character.isUpperCase(string.charAt(i)) { ... } • //Convert a character to lower case. char ch = Character.toLowerCase(string.charAt(i)); • //Determine if the character is a letter. if (Character.isLetter(string.charAt(i))) { ... }

  34. Strings • If your text is not going to change, use a string — a String object is immutable. • If your text will change, and will only be accessed from a single thread, use a string builder. • If your text will change, and will be accessed from multiple threads, use a string buffer • public class StringsDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); StringBuilder dest = new StringBuilder(len); for (int i = (len - 1); i >= 0; i--) { dest.append(palindrome.charAt(i)); } System.out.format("%s%n", dest.toString()); } }

  35. Strings and compiler • The compiler uses the StringBuilder class behind the scenes to handle literal strings and concatenation • int len = "Goodbye Cruel World".length(); • String s = "Hola Mundo"; The preceding construct is equivalent to, but more efficient than, this one, which ends up creating two identical strings: String s = new String("Hola Mundo"); //don't do this • String cat = "cat"; System.out.println("con" + cat + "enation"); The preceding example compiles to something equivalent to: System.out.println( new StringBuffer(). append("con").append(cat).append("enation").toString()); • int one = 1; System.out.println("You're number " + one);

  36. Number classes • Two reasons that you might use a Number class, instead of the primitive form: • When an object is required — such as when using generic types. For example, to constrain your list to a particular type argument, such as String. You must specify the Integer type, as in ArrayList<Integer> • When you need the variables or static methods defined by the class, such as MIN_VALUE and MAX_VALUE, that provide general information about the data type

  37. Simple data objects • Characters and strings • Numbers • Arrays

  38. Arrays • An array is a structure that holds multiple values of the same type. • The length of an array is established when the array is created. • After creation, an array is a fixed-length structure.

  39. Creating and using arrays • public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create an array of integers // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } } } • You can write an array declaration like this: float anArrayOfFloats[]; //this form is discouraged • new elementType[arraySize]; // create new array • boolean[] answers = { true, false, true, true, false }; // initialize array • arrayname.length // get size of the array

  40. Java language • Object-Oriented Programming Concepts • Language basics • Object basics and simple data objects • Classes and inheritance • Interfaces and packages • Common problems/solutions

  41. Classes and inheritance • Writing classes • Manage inheritance • Nested classes • Enumerated types • Annotations • Generics

  42. Writing classes

  43. Declaring classes

  44. Declaring member variables • private List<Object> items; • Element Function • accessLevel (optional) Access level for the variable • public, protected, private, and default • static (optional) Declares a class variable • final (optional) variable value cannot change • transient (optional) the variable is transient • member variables that should not be serialized • volatile (optional) the variable is volatile • Prevents the compiler from performing certain optimizations on a member • type name The type and name of the variable

  45. Declaring methods • Element Function • @annotation (Optional) An annotation (sometimes called meta-data) • accessLevel (Optional) Access level for the method • static (Optional) Declares a class method • <TypeVariables> (Optional) Comma-separated list of type variables • abstract (Optional) Indicates that the method must be implemented in concrete subclasses • final (Optional) Indicates that the method cannot be overridden • native (Optional) Indicates that the method is implemented in another language • synchronized (Optional) Guarantees exclusive access to this method • returnType methodName The method's return type and name • ( paramList ) The list of arguments to the method • throws exceptions (Optional) The exceptions thrown by the method

  46. Providing constructors • public Stack() { items = new ArrayList<Object>(); } • public Stack(int size) { items = new ArrayList<Object>(size); } • public, private, protected, default

  47. Classes and inheritance • Writing classes • Manage inheritance • Nested classes • Enumerated types • Annotations • Generics

  48. Manage inheritance All Classes are Descendants of Object

  49. Inheritance • Every class has one and only one direct superclass (single inheritance) • A subclass inherits all the member variables and methods from its superclass • a subclass cannot access a private member inherited from its superclass • constructors are not members and so are not inherited by subclasses

  50. Overriding and hiding methods • An instance method in a subclass with the same signature and return type as an instance method in the superclass overrides the superclass's method • a method's signature is its name and the number and the type of its arguments • can also override a method with the same signature that returns a subclass of the object returned by the original method. This facility is called covariant return type • A subclass cannot override methods that are declared final in the superclass • A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract

More Related