Java part 1

85
Java Prepared by Abegail T. Soñas December 15, 2011

description

OOP Concepts & Language Basics

Transcript of Java part 1

  • 1. Prepared by Abegail T. SoasDecember 15, 2011

2. Table of ContentsIntroductionI Java Definition | Language Features |Java Editions | Java Translation ProcessOOP ConceptsIIObject | Class | Inheritance |Interface | PackageLanguage BasicsIII Variables | Operators | Expressions,Statements, & Blocks | Control FlowStatements 3. Home 4. Java programming language originally developed by JamesGosling Sun Microsystems (now part of Oracle Corporation) released in 1995 as a core component of SunMicrosystems Java platformHome 5. LANGUAGE FEATURES Platform Independence Java compilers do not produce native object code for a particular platform but rather byte code instructions for the Java Virtual Machine (JVM). Making Java code work on a particular platform is thensimply a matter of writing a byte code interpreter tosimulate a JVM. What this all means is that the same compiled byte code will run unmodified on any platform that supports Java. 6. LANGUAGE FEATURES Object Orientation Java is a pure object-oriented language. This means that everything in a Java program is an object and everything is descended from a root object class. 7. LANGUAGE FEATURES Rich Standard Library The Java environment includes hundreds of classes and methods in six major functional areas. 8. LANGUAGE FEATURES Applet Interface In addition to being able to create stand-alone applications, Java developers can create programs that can be downloaded from a web page and run on a client browser. 9. LANGUAGE FEATURES Familiar C++ like Syntax One of the factors enabling the rapid adoption of Java is the similarity of the Java syntax to that of the popular C++ programming language. 10. LANGUAGE FEATURES Garbage Collection Java does not require programmers to explicitly freedynamically allocated memory. This makes Java programs easier to write and lessprone to memory errors. 11. Java Editions Java EditionsStandardEnterprise Micro Home 12. Java EditionsJava Java Edition FormerlyAcronymcalledJava SE Java Standard J2SE For building desktop small number of users applications and at one timeEdition appletsJava EE Java Enterprise J2EE Tailored for moreserver based complex applications applicationsEdition to suit medium tomulti-users large businessesJava ME Java MicroJ2ME Used onEdition mobile (e.g., cell phone, PDA) embedded devices (e.g., TV tuner box, printers)Home 13. Java Translation Process Source Code (Hello.java)Compiler (Javac) Byte Code (Hello.class) Interpreter Executable ProgramHome 14. Source Code vs. Byte Code SOURCE CODE BYTE CODE Has the .java extension Has the .class extension A series of Compiled source codeinstructions that tellshow the program willreact or do in certainsituations Home 15. Translator TypesCompilerInterpretertransformstransformssource code tobyte code tobyte code executableprogram Home 16. JRE Java Runtime EnvironmentJVM Java Virtual MachineJDK Java Development KitAPI Java Application Programming InterfaceIDE Integrated Development EnvironmentHome 17. JRE Java Runtime Environment When installed on a computer, the JRE provides theoperating system with the means to run Java programs It provides the libraries, the Java Virtual Machine, andother components to run applets and applications writtenin the Java programming language. In addition, two key deployment technologies are part ofthe JRE: Java Plug-in - enables applets to run in popular browsers Java Web Start - deploys standalone applications over anetworkHome 18. JVM Java Virtual Machine A virtual machine capable of executing Java bytecode. JVMs are available for many hardware and software platforms. The use of the same bytecode for all JVMs on allplatforms allows Java to be described as a "write once,run anywhere" programming language.Home 19. JDK Java Development Kit JDK is a collection of tools used by a programmer to create Java applications. Home 20. JAVA API Java API (Application Programming Interface) It is actually a huge collection of library routines thatperforms basic programming tasks such as looping,displaying GUI form etc. It is not but a set of classes and interfaces that comeswith the JDK.Home 21. IDE Integrated Development Environment It is a software application that providescomprehensive facilities to computer programmers forsoftware development. An IDE normally consists of: a source code editor a compiler and/or an interpreter build automation tools a debuggerHome 22. Home 23. Object-Oriented Programming ConceptsObject-Oriented Programming Concepts1) What Is an Object?2) What Is a Class?3) What Is Inheritance?4) What Is an Interface?5) What Is a Package?Home 24. Object-Oriented Programming ConceptsObject entity, real-world objects 2 characteristics of Objects1) STATE An object stores its state in fields (variables in someprogramming languages)2) BEHAVIOR An object exposes its behavior through method(functions in some programming languages)Home 25. Object-Oriented Programming ConceptsObject Example Object Dog StateName, color, breed Noun, Adjective Behavior Barking, fetching VerbHome 26. Object-Oriented Programming ConceptsObject Data Encapsulation Hiding internal state and requiring all interaction tobe performed through an objects methods all statements are within the curly braces of a class {} use of access modifier (define whether the attribute isaccessible to other class public, private) Home 27. Object-Oriented Programming ConceptsClass blueprint from which individual objects are created In object-oriented terms, we say that yourbicycle is an instance of the class of objectsknown as bicycles. Variable a term, symbolic name given to some known or unknown quantity or information Field represent the objects stateHome 28. Object-Oriented Programming ConceptsInheritance OOP allows classes to inherit commonly used state and behavior from other classes Promotes code reuse In Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.Home 29. Object-Oriented Programming ConceptsInheritanceSuperclass(Parent Class)Subclasses(Child Class) Home 30. Object-Oriented Programming ConceptsInheritanceKeyword! SYNTAX:class MountainBike extends Bicycle {// new fields and methods defining amountain bike would go here}Home 31. Object-Oriented Programming ConceptsInterface group of related methods with empty bodies Home 32. Object-Oriented Programming ConceptsInterface SYNTAX: Creating the interface Bicycleinterface Bicycle {void changeCadence(int newValue); // wheel revolutionsper minutevoid changeGear(int newValue);void speedUp(int increment);void applyBrakes(int decrement);} SYNTAX: Implementing the interface in ACMEBicycle classclass ACMEBicycle implements Bicycle {// remainder of this class implemented as before } Home 33. Object-Oriented Programming ConceptsPackage a namespace that organizes a set of related classes and interfaces Set of Packages -> API API (Application Programming Interface) class library collection of packagesHome 34. Object-Oriented Programming ConceptsStatement Method Interface (related methods with empty bodies)API (set of packages) ClassPackage ProjectHierarchyHome 35. Home 36. Language BasicsLanguage Basics1) Variablesa) Primitive Data Typesb) Arrays2) Operatorsa) Assignment, Arithmetic, and Unary Operatorsb) Equality, Relational, and Conditional Operatorsc) Bitwise and Bit Shift Operators3) Expressions, Statements, and Blocks4) Control Flow Statementsa) The if-then and if-then-else Statementsb) The switch Statementc) The while and do-while Statementsd) The for Statemente) Branching Statements Home 37. Language BasicsKinds of VariablesInstance Variables(Non-Static Fields) Class Variables (Static Fields) Local Variables Parameters Home 38. Language BasicsKinds of Variables1) Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Home 39. Language BasicsKinds of Variables1) Instance Variables (Non-Static Fields) Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words) the currentSpeed of one bicycle is independent fromthe currentSpeed of another. Home 40. Language BasicsKinds of Variables2) Class Variables (Static Fields) A class variable is any field declared with the staticmodifier this tells the compiler that there is exactly one copy ofthis variable in existence, regardless of how manytimes the class has been instantiated. Home 41. Language BasicsKinds of Variables2) Class Variables (Static Fields) A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances.Home 42. Language BasicsKinds of Variables2) Class Variables (Static Fields) The code static int num Gears = 6 ; would create such a static field. Additionally, the keyword final could be added toindicate that the number of gears will never change. Home 43. Language BasicsKinds of Variables3) Local Variables Similar to how an object stores its state in fields, amethod will often store its temporary state in localvariables. The syntax for declaring a local variable is similar todeclaring a field (for example, int count = 0; ).Home 44. Language BasicsKinds of Variables3) Local Variables There is no special keyword designating a variable aslocal; that determination comes entirely from thelocation in which the variable is declared whichis between the opening and closing braces of amethod. As such, local variables are only visible to the methodsin which they are declared; they are not accessible fromthe rest of the class. Home 45. Language BasicsKinds of Variables4) Paramaters Youve already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the signature for the main method is publicstatic void main (String [ ] args). Here, the args variable is the parameter to this method.Home 46. Language BasicsKinds of Variables4) Paramaters The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs aswell (such as constructors and exception handlers).Home 47. Language BasicsVariables: Primitive Data Types A primitive type is predefined by the language and is names by a reserved keyword. Primitive values do not share state with other primitive values.Home 48. Language BasicsVariables: Primitive Data TypesNO PRIMITIVE MINMAXUSAGE DATA TYPEVALUEVALUE1 byte 8-bit signed -128 127 Saving twos(inclusive) memory in complement large arrays integer2 short16-bit signed -32, 768 32, 767 twos(inclusive) complement integer Home 49. Language BasicsVariables: Primitive Data TypesNO PRIMITIVE MIN MAXUSAGE DATA TYPEVALUE VALUE3int 32-bit signed -2,147, 2, 147, Generally, twos 483, 648 483, 647the default complement (inclusive) choice for integerintegral values4long16-bit signed -9, 223, 9, 223, Range of twos 372, 036,372, 036, values wider complement854, 775,854, 775, than those integer 808807 provided by(inclusive) int Home 50. Language BasicsVariables: Primitive Data TypesNO PRIMITIVEMINMAX USAGE DATA TYPE VALUEVALUE5float single beyond the scope of Never be used precision 32-this discussion for precise bit IEEE 754 values, such floating point as currency6doubledouble beyond the scope of Default precision 64-this discussion choice for bit IEEE 754 decimal values floating point Home 51. Language BasicsVariables: Primitive Data TypesNO PRIMITIVE MINMAXUSAGE DATA TYPEVALUEVALUE7boolean 2 possible values Simple flags truethat track false true/false conditions8CharSingle 16-bit u0000 uffff Unicode (or 0) (or 65,535 characterinclusive)Home 52. Language BasicsVariables: Arrays An array is a container object that holds a fixed number of values of a single type The length of an array is established when the array is created. After creation, its length is fixed. Home 53. Language BasicsVariables: Arrays Each item in an array is called an element, and each element is accessed by its numerical index. Home 54. Language BasicsVariables: Arrays Creating Arraysint[] anArray; //declares an array of integersanArray = new int[5];//allocates memory for 5 integersanArray[0] = 100; //initialize first elementanArray[1] = 200; //initialize second elementanArray[2] = 300; //etcanArray[3] = 400;anArray[4] = 500; Home 55. Language BasicsVariables: Arrays One way to create an array is with the new operator:anArray = new int[5]; //create an array of integers Shortcut syntax to create and initialize an array:int[] anArray = {100, 200, 300, 400, 500}; Home 56. Language BasicsVariables: Arrays Multidimensional ArraysString[][] names = {{Mr. , Mrs. , Ms. },{Smith, Jones}};System.out.println(names[0][0] + names[1][0]); //Mr. SmithSystem.out.println(names[0][2] + names[1][1]); //Ms. JonesHome 57. Language BasicsVariables: Arrays Copying Arrayschar[] copyFrom = {d, e, c, a, f, f, e, i,n, a, t, e, d };char[] copyTo = new char[7]; Start copying from index 2System.arraycopy(copyFrom, 2, copyTo, 0, 7);System.out.println(new String(copyTo));OUPUT: Start placing the copied char to thecaffeincopyTo array starting from index 0 The total number of char copied is 7Home 58. Language BasicsOperators Simple Assignment Operator = Simple Assignment Operator It assigns the value on its right to the operand on itsleftHome 59. Language BasicsOperators Arithmetic Operators + additive operator (also used for String concatenation) - subtraction operator * multiplication operator / division operator % remainder operatorHome 60. Language BasicsOperators Unary Operators +Unary plus operator; indicates positive value (numbers are positive without this, however) -Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 !Logical complement operator; inverts the value of a booleanHome 61. Language BasicsOperators Equality and Relational Operators ==equal to !=not equal to > greater than >=greater than or equal to < less than