Java part 1


Published on

OOP Concepts & Language Basics

Published in: Technology
  • what is the problem with sending email this topic
    Are you sure you want to  Yes  No
    Your message goes here

Java part 1

  1. 1. Prepared by Abegail T. SoñasDecember 15, 2011
  2. 2. Table of Contents IntroductionI Java Definition | Language Features | Java Editions | Java Translation Process OOP ConceptsII Object | Class | Inheritance | Interface | Package Language BasicsIII Variables | Operators | Expressions, Statements, & Blocks | Control Flow Statements
  3. 3. Home
  4. 4. Java programming language originally developed by James Gosling Sun Microsystems (now part of Oracle Corporation) released in 1995 as a core component of Sun Microsystems Java platform Home
  5. 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 then simply a matter of writing a byte code interpreter to simulate a JVM. What this all means is that the same compiled byte code will run unmodified on any platform that supports Java.
  6. 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. 7. LANGUAGE FEATURES Rich Standard Library The Java environment includes hundreds of classes and methods in six major functional areas.
  8. 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. 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. 10. LANGUAGE FEATURES Garbage Collection Java does not require programmers to explicitly free dynamically allocated memory. This makes Java programs easier to write and less prone to memory errors.
  11. 11. Java Editions Java EditionsStandard Enterprise Micro Home
  12. 12. Java Editions Java Java Edition FormerlyAcronym calledJava SE Java Standard J2SE For building desktop small number of users applications and at one time Edition appletsJava EE Java Enterprise J2EE Tailored for more server based complex applications applications Edition to suit medium to multi-users large businessesJava ME Java Micro J2ME Used on Edition  mobile (e.g., cell phone, PDA)  embedded devices (e.g., TV tuner box, printers) Home
  13. 13. Java Translation Process Source Code ( Compiler (Javac) Byte Code (Hello.class) Interpreter Executable Program Home
  14. 14. Source Code vs. Byte Code SOURCE CODE  BYTE CODE  Has the .java extension  Has the .class extension  A series of  Compiled source code instructions that tells how the program will react or do in certain situations Home
  15. 15. Translator TypesCompiler Interpretertransforms transformssource code to byte code tobyte code executable program Home
  16. 16. JRE Java Runtime EnvironmentJVM Java Virtual MachineJDK Java Development KitAPI Java Application Programming InterfaceIDE Integrated Development Environment Home
  17. 17. JRE Java Runtime Environment When installed on a computer, the JRE provides the operating system with the means to run Java programs It provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE:  Java Plug-in - enables applets to run in popular browsers  Java Web Start - deploys standalone applications over a network Home
  18. 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 all platforms allows Java to be described as a "write once, run anywhere" programming language. Home
  19. 19. JDK Java Development Kit JDK is a collection of tools used by a programmer to create Java applications. Home
  20. 20. JAVA API Java API (Application Programming Interface) It is actually a huge collection of library routines that performs basic programming tasks such as looping, displaying GUI form etc. It is not but a set of classes and interfaces that comes with the JDK. Home
  21. 21. IDE Integrated Development Environment It is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of:  a source code editor  a compiler and/or an interpreter  build automation tools  a debugger Home
  22. 22. Home
  23. 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. 24. Object-Oriented Programming ConceptsObject entity, real-world objects 2 characteristics of Objects1) STATE  An object stores its state in fields (variables in some programming languages)2) BEHAVIOR  An object exposes its behavior through method (functions in some programming languages) Home
  25. 25. Object-Oriented Programming ConceptsObject Example Object Dog State Name, color, breed  Noun, Adjective Behavior Barking, fetching  Verb Home
  26. 26. Object-Oriented Programming ConceptsObject Data Encapsulation Hiding internal state and requiring all interaction to be performed through an objects methods  all statements are within the curly braces of a class {}  use of access modifier (define whether the attribute is accessible to other class – public, private) Home
  27. 27. Object-Oriented Programming ConceptsClass blueprint from which individual objects are created In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. Variable  a term, symbolic name given to some known or unknown quantity or information Field  represent the objects state Home
  28. 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. 29. Object-Oriented Programming ConceptsInheritance Superclass (Parent Class) Subclasses (Child Class) Home
  30. 30. Object-Oriented Programming ConceptsInheritance Keyword! SYNTAX:class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here} Home
  31. 31. Object-Oriented Programming ConceptsInterface group of related methods with empty bodies Home
  32. 32. Object-Oriented Programming ConceptsInterface SYNTAX: Creating the interface Bicycleinterface Bicycle { void changeCadence(int newValue); // wheel revolutions per minute void 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. 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 packages Home
  34. 34. Object-Oriented Programming Concepts Statement Method Interface (related methods with empty bodies) API (set of packages) Class Package ProjectHierarchy Home
  35. 35. Home
  36. 36. Language BasicsLanguage Basics1) Variables a) Primitive Data Types b) Arrays2) Operators a) Assignment, Arithmetic, and Unary Operators b) Equality, Relational, and Conditional Operators c) Bitwise and Bit Shift Operators3) Expressions, Statements, and Blocks4) Control Flow Statements a) The if-then and if-then-else Statements b) The switch Statement c) The while and do-while Statements d) The for Statement e) Branching Statements Home
  37. 37. Language BasicsKinds of Variables Instance Variables (Non-Static Fields) Class Variables (Static Fields) Local Variables Parameters Home
  38. 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. 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 from the currentSpeed of another. Home
  40. 40. Language BasicsKinds of Variables2) Class Variables (Static Fields) A class variable is any field declared with the static modifier  this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. Home
  41. 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. 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 to indicate that the number of gears will never change. Home
  43. 43. Language BasicsKinds of Variables3) Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0; ). Home
  44. 44. Language BasicsKinds of Variables3) Local Variables There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared – which is between the opening and closing braces of a method.  As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Home
  45. 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 public static void main (String [ ] args).  Here, the args variable is the parameter to this method. Home
  46. 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 as well (such as constructors and exception handlers). Home
  47. 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. 48. Language Basics Variables: Primitive Data TypesNO PRIMITIVE MIN MAX USAGE DATA TYPE VALUE VALUE1 byte 8-bit signed • -128 • 127 •Saving two’s (inclusive) memory in complement large arrays integer2 short 16-bit signed • -32, 768 • 32, 767 two’s (inclusive) complement integer Home
  49. 49. Language BasicsVariables: Primitive Data TypesNO PRIMITIVE MIN MAX USAGE DATA TYPE VALUE VALUE3 int 32-bit signed • -2,147, • 2, 147, • Generally, two’s 483, 648 483, 647 the default complement (inclusive) choice for integer integral values4 long 16-bit signed • -9, 223, • 9, 223, • Range of two’s 372, 036, 372, 036, values wider complement 854, 775, 854, 775, than those integer 808 807 provided by (inclusive) int Home
  50. 50. Language BasicsVariables: Primitive Data TypesNO PRIMITIVE MIN MAX USAGE DATA TYPE VALUE VALUE5 float single – • beyond the scope of •Never be used precision 32- this discussion for precise bit IEEE 754 values, such floating point as currency6 double double– • beyond the scope of •Default precision 64- this discussion choice for bit IEEE 754 decimal values floating point Home
  51. 51. Language BasicsVariables: Primitive Data TypesNO PRIMITIVE MIN MAX USAGE DATA TYPE VALUE VALUE7 boolean •2 possible values • Simple flags • true that track • false true/false conditions8 Char Single 16-bit • „u0000‟ • „uffff‟ • Unicode (or 0) (or 65,535 character inclusive) Home
  52. 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. 53. Language BasicsVariables: Arrays Each item in an array is called an element, and each element is accessed by its numerical index. Home
  54. 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. 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. 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. Jones Home
  57. 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 thecaffein copyTo array starting from index 0 The total number of char copied is 7 Home
  58. 58. Language BasicsOperators Simple Assignment Operator = Simple Assignment Operator It assigns the value on its right to the operand on its left Home
  59. 59. Language BasicsOperators Arithmetic Operators + additive operator (also used for String concatenation) - subtraction operator * multiplication operator / division operator % remainder operator Home
  60. 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 boolean Home
  61. 61. Language BasicsOperators Equality and Relational Operators == equal to != not equal to > greater than >= greater than or equal to < less than <= less than or equal to Home
  62. 62. Language BasicsOperators Conditional Operators && Conditional-AND || Conditional-OR Home
  63. 63. Language BasicsOperators Type Comparison Operator instanceof instanceof Operator compares an object to a specified type Home
  64. 64. Language BasicsExpressions, Statements, and Blocks EXPRESSIONS construct made up of  variables  operators  method invocations which are constructed according to the syntax of the language, that evaluates to a single value compute values part of statement Home
  65. 65. Language BasicsExpressions, Statements, and Blocks EXPRESSIONSint cadence = 0;anArray[0] = 100;System.out.println(“Element 1 at index 0: ” + anArray[0]); Home
  66. 66. Language BasicsExpressions, Statements, and Blocks STATEMENTS forms a complete unit of execution  roughly equivalent to sentences in natural language Home
  67. 67. Language BasicsExpressions, Statements, and Blocks STATEMENTS The ff. types of expressions can be made into a statement by terminating the expression with a semicolon (;)  Assignment expressions  Any use of ++ or --  Method invocations  Object creation expressions Home
  68. 68. Language BasicsExpressions, Statements, and Blocks Expression Statements Types Declaration Statements of Statements Control Flow Statements Home
  69. 69. Language BasicsExpressions, Statements, and Blocks BLOCKS group of zero or more statements between balanced braces can be used anywhere a single statement is allowedif (condition) { //begin block 1 System.out.println("Condition is true.");} //end block 1 Home
  70. 70. Language BasicsHierarchy Group of zero or more statements Blocks Complete unit of execution Statements Construct which computes values Expressions Home
  71. 71. Language BasicsControl Flow Statements Decision-Making Statements  if-then, if-then-else, switch Looping Statements  for, while, do-while Branching Statements  break, continue, return Home
  72. 72. Language BasicsControl Flow Statements:The if-then and if-then-else Statements if-then Statements most basic of all the control flow statements It tells your program to execute a certain section of code only if a particular test evaluates to true. Home
  73. 73. Language BasicsControl Flow Statements:The if-then and if-then-else Statements if-then Statementsvoid applyBrakes() { // the "if" clause: bicycle // must be moving if (isMoving){ // the "then" clause: decrease // current speed currentSpeed--; }} Home
  74. 74. Language BasicsControl Flow Statements:The if-then and if-then-else Statements if-then-else Statements provides a secondary path of execution when an "if" clause evaluates to false Home
  75. 75. Language BasicsControl Flow Statements:The if-then and if-then-else Statements if-then-else Statementsvoid applyBrakes() { if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has " + "already stopped!"); }} Home
  76. 76. Language BasicsControl Flow Statements:The switch Statement can have a number of possible execution paths It works with the byte, short, char, and int primitive data types. Home
  77. 77. Language BasicsControl Flow Statements:The switch Statementint month = 8;String monthString;switch (month) { case 1: monthString = "January"; break; Output: case 2: monthString = "February"; break; case 3: monthString = "March"; break; August case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break;} System.out.println(monthString); Home
  78. 78. Language BasicsControl Flow Statements:The while and do-while Statements while continually executes a block of statements while a particular condition is true Syntax: while (expression) { statement(s) } Home
  79. 79. Language BasicsControl Flow Statements:The while and do-while Statements while The while statement evaluates expression, which must return a boolean value.  If the expression evaluates to true, the while statement executes the statement(s) in the while block. Home
  80. 80. Language BasicsControl Flow Statements:The while and do-while Statements do-while evaluates its expression at the bottom of the loop instead of the top Syntax: do { statement(s) } while (expression); Home
  81. 81. Language BasicsControl Flow Statements:The for Statement General form: for (initialization; termination; increment) { statement(s) } Home
  82. 82. Language BasicsControl Flow Statements:The for Statements The initialization expression  initializes the loop;  its executed once, as the loop begins. When the termination expression evaluates to false,  the loop terminates. The increment expression  is invoked after each iteration through the loop;  it is perfectly acceptable for this expression to increment or decrement a value. Home
  83. 83. Language BasicsControl Flow Statements:Branching Statements Break Statement Unlabeled break  terminates the innermost  used to terminate  for  while  do-while loop Labeled break  terminates the outermost Home
  84. 84. Language BasicsControl Flow Statements:Branching Statements Continue Statement  skips the current iteration of a for, while , or do- while loop Unlabeled continue  unlabeled form skips to the end of the innermost loops body and evaluates the boolean expression that controls the loop Labeled continue  skips the current iteration of an outer loop marked with the given label Home
  85. 85. Index API  Java Definition Arrays  Java Editions Arithmetic Operators  Java Translation Process Assignment Operators  JDK Blocks  JRE Branching Statements  JVM Conditional Operators  Language Basics Control Flow Statements  Language Features Class  Object Compiler  OOP Concepts do-while Statement  Operators Equality and Relational Operators  Package Expressions  Primitive Data Types for Statement  Statements IDE  switch Statement if-then Statement  Translator if-then-else Statement  Type Comparison Operator Inheritance  Unary Operators Interface  Variables Interpreter  while Statement