Introduction to Java and OOP PDF

Summary

This document provides an introduction to Java and object-oriented programming (OOP) concepts. It explores procedural programming, benefits of OOP, and its paradigm, including examples of representable objects. The document touches upon OOP concepts like encapsulation, abstraction, and polymorphism.

Full Transcript

Absolute Java Sixth Edition Chapter 1 Getting Started Modified by Dr. Zia Ud Din and Dr. Zara Hamid, WLU Copyright © 2016, 2013, 2010 Pear...

Absolute Java Sixth Edition Chapter 1 Getting Started Modified by Dr. Zia Ud Din and Dr. Zara Hamid, WLU Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Procedure Oriented Programming In a procedural language, the emphasis is on doing things(functions). A program is divided into functions and—ideally, at least—each function has a clearly defined purpose and a clearly defined interface to the other functions in the program. Procedural programs (functions and data structures) don’t model the real world very well. The real world does not consist of functions. Global data can be corrupted by functions that have no business changing it. To add new data items, all the functions that access the data must be modified so that they can also access these new items. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Object Oriented Programming Paradigm The fundamental idea behind object-oriented programming is: – The real world consists of objects. – Computer programs may contain computer world representations of the things (objects) that constitute the solutions of real world problems. Real world objects have two parts: – Properties (or state :characteristics that can change), – Behavior (or abilities :things they can do). To solve a programming problem in an object-oriented language, the programmer no longer asks how the problem will be divided into functions, but how it will be divided into objects. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Procedure Oriented vs Object Oriented Programming Global Data https://www.bloccoappunti.it/39-oop/ Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Object Oriented Programming Paradigm OOP allows you to describe the problem in terms of the problem, rather than in terms of the computer where the solution will run. Benefits of the object-oriented programming: Readability Understandability Low probability of errors Maintenance Reusability Teamwork Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Examples of things that can be represented as objects in object-oriented paradigm? Human entities: Employees, customers, salespeople, worker, manager Graphics program: Point, line, square, circle,... Mathematics: Complex numbers, matrix Computer user environment: Windows, menus, buttons Data-storage constructs: Customized arrays, stacks, linked lists Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Three Pillars of OOP From the programmer's point of view, an object-oriented language must support three very important explicit characteristics. We use these concepts extensively to model the real-world problems when we are trying to solve with our object-oriented programs. These three concepts are: – Encapsulation and data hiding, – Inheritance, – Polymorphism. The implicit characteristic is abstraction. We use it to specify new abstract data types, or ADT for short. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Encapsulation & Data Hiding Image from http://www.btechsmartclass.com/java/java- oop-concepts.html The concept of combining the data and the associated functions -that operate on that data- in a single unit called a class, or an object is called encapsulation. It is not possible to access the data directly. If you want to reach the data item in an object, you call a member function in the object. It will read the data item and return the value to you. The data is hidden, so it is considered as safe and far away from accidental alternation. This concept is called data hiding We use keywords public, private, and protected to control access Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Abstraction This is a thought process of hiding work style of an object and showing only those information which are required to understand the object. Or we can say, process of identifying the relevant qualities and behaviors of an object Abstraction is the specification of an abstract data type and includes a specification of the type’s data representation and behavior. It shows, what kind of data can be held in the new type of data, and all ways of manipulation of that data. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Example: Encapsulation & Abstraction Since a car was invented, the steering mechanism has not changed functionality. It presents the same interface to the users: everybody knows how to use this mechanism through its interface. If we turn the steering wheel clockwise, the car will turn to the right, if we turn it counterclockwise, our car will turn to the left. We can use it without having any idea about implementation — everything is hidden for us under the hood, only a few of us have more details. Image from https://www.linkedin.com/pulse/encapsulation-vs-abstraction-pawan-verma/ Car object Outside world Client interface color setColor() model Accelerate() Hidden/encapsulated speed applyBrake() data Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes and Objects (1 of 2) An object has the same relationship to a class that a variable has to a data type. An object is said to be an instance of a class. A class is a template to its objects. Class definition does not allocate any memory. Memory allocation is done for each instance (object) when it is instantiated (created). Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes and Objects (2 of 2) https://leetusman.com/intermediate-programming/posts/classes-and-objects/ Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects Give me 5 examples of classes and objects… Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects 1. Class: Car Attributes: model, brand, color, engineType, fuelLevel Methods: drive(), refuel(), park(), turnOn(), turnOff() Object (Instance): myCar = new Car("Model S", "Tesla", "Red", "Electric", 100%) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects 2. Class: Student Attributes: name, studentID, major, GPA, enrolledCourses Methods: enrollCourse(), dropCourse(), updateGPA(), attendClass() Object (Instance): student1 = new Student("Alice Smith", "S12345", "Computer Science", 3.8, ["CP104", “CP213"]) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects 3. Class: BankAccount Attributes: accountNumber, accountHolder, balance, accountType Methods: deposit(), withdraw(), transferFunds(), checkBalance() Object (Instance): myAccount = new BankAccount("123456789", "John Doe", 15000.00, "Checking") Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Inheritance Inheritance is one of the most powerful features of object- oriented programming Inheritance is the process of creating new classes, called subclasses, from existing or superclasses The derived class inherits all the capabilities of the base class but can add more capabilities of its own Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Polymorphism Derived from the Greek words: poly and morphs meaning many and forms. Polymorphism refers to the ability of a single object to take on multiple forms. This is achieved through inheritance, where a subclass can override the methods of its superclass. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Example: Inheritance Inherited properties Inherited/overridden behaviours http://www.btechsmartclass.com/java/java-oop-concepts.html Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Example: Polymorphism http://www.btechsmartclass.com/java/java-oop-concepts.html Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language – The syntax of expressions and assignments will be similar to that of other high-level languages – Details concerning the handling of strings and console output will probably be new Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Origins of the Java Language (1 of 3) Created by Sun Microsystems team led by James Gosling in 1991 (now owned by Oracle) Originally designed for programming home appliances – Difficult task because appliances are controlled by a wide variety of computer processors – Team developed a two-step translation process to simplify the task of compiler writing for each class of appliances Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Origins of the Java Language (2 of 3) Significance of Java translation process – Writing a compiler (translation program) for each type of appliance processor would have been very costly – Instead, developed intermediate language that is the same for all types of processors : Java byte-code – Therefore, only a small, easy to write program was needed to translate byte-code into the machine code for each processor Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Origins of the Java Language (3 of 3) Patrick Naughton and Jonathan Payne at Sun Microsystems developed a Web browser that could run programs over the Internet (1994) – Beginning of Java's connection to the Internet – Original browser evolves into HotJava Netscape made its Web browser capable of running Java programs (1995) – Other companies follow suit Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Objects and Methods Java is an object-oriented programming (OOP) language – Programming methodology that views a program as consisting of objects that interact with one another by means of actions (called methods) – Objects of the same kind are said to have the same type or be in the same class Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Terminology Comparisons Other high-level languages have constructs called procedures, methods, functions, and/or subprograms – These types of constructs are called methods in Java – All programming constructs in Java, including methods, are part of a class Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Java Application Programs Two common types of Java programs are applications and applets A Java application program or “regular” Java program is a class with a method named main – When a Java application program is run, the run-time system automatically invokes the method named main – All Java application programs start with the main method Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Applets A Java applet (little Java application) is a Java program that is meant to be run from a Web browser – Can be run from a location on the Internet – Can also be run with an applet viewer program for debugging – Applets always use a windowing interface In contrast, application programs may use a windowing interface or console (i.e., text) I/O Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved A Sample Java Application Program Display 1.1 A sample java Program Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved System.out.println (1 of 2) Java programs work by having things called objects perform actions – System.out: An object used for sending output to the screen The actions performed by an object are called methods – Print ln: The method or action that the System.out object performs Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved System.out.print ln (2 of 2) Invoking or calling a method: When an object performs an action using a method – Also called sending a message to the object – Method invocation syntax (in order): an object, a dot (period), the method name, and a pair of parentheses – Arguments: Zero or more pieces of information needed by the method that are placed inside the parentheses Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Variable declarations Variable declarations in Java are similar to those in other programming languages –Simply give the type of the variable followed by its name and a semicolon Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Using = and + In Java, the equal sign (=) is used as the assignment operator – The variable on the left side of the assignment operator is assigned the value of the expression on the right side of the assignment operator In Java, the plus sign (+) can be used to denote addition (as above) or concatenation – Using +, two strings can be connected together Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Computer Language Levels (1 of 2) High-level language: A language that people can read, write, and understand – A program written in a high-level language must be translated into a language that can be understood by a computer before it can be run Machine language: A language that a computer can understand Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Computer Language Levels (2 of 2) Low-level language: Machine language or any language similar to machine language Compiler: A program that translates a high-level language program into an equivalent low-level language program – This translation process is called compiling Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Byte-Code and the Java Virtual Machine (1 of 2) The compilers for most programming languages translate high-level programs directly into the machine language for a particular computer – Since different computers have different machine languages, a different compiler is needed for each one In contrast, the Java compiler translates Java programs into byte-code, a machine language for a fictitious computer called the Java Virtual Machine – Once compiled to byte-code, a Java program can be used on any computer, making it very portable Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Byte-Code and the Java Virtual Machine (2 of 2) Interpreter: The program that translates a program written in Java byte-code into the machine language for a particular computer when a Java program is executed – The interpreter translates and immediately executes each byte- code instruction, one after another – Translating byte-code into machine code is relatively easy compared to the initial compilation step Most Java programs today run using a Just-In-Time or JIT compiler which compiles a section of byte-code at a time Image from https://www.w3schools.in/java/java-virtual-machine into machine code Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Program terminology Code: A program or a part of a program Source code (or source program): A program written in a high-level language such as Java – The input to the compiler program Object code: The translated low-level program – The output from the compiler program, e.g., Java byte- code – In the case of Java byte-code, the input to the Java byte- code interpreter Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Class Loader Java programs are divided into smaller parts called classes – Each class definition is normally in a separate file and compiled separately Class Loader: A program that connects the byte-code of the classes needed to run a Java program – In other programming languages, the corresponding program is called a linker https://shishirkant.com/java-virtual-machine-jvm/ Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Compiling a Java Program or Class Each class definition must be in a file whose name is the same as the class name followed by.java – The class FirstProgram must be in a file named FirstProgram.java Each class is compiled with the command javac followed by the name of the file in which the class resides The result is a byte-code program whose filename is the same as the class name followed by.class Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Running a Java Program A Java program can be given the run command (java) after all its classes have been compiled – Only run the class that contains the main method (the system will automatically load and run the other classes, if any) – The main method begins with the line: – Follow the run command by the name of the class only (no.java or.class extension) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Syntax and Semantics Syntax: The arrangement of words and punctuations that are legal in a language, the grammar rules of a language Semantics: The meaning of things written while following the syntax rules of a Language Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Error Messages (1 of 2) Bug: A mistake in a program – The process of eliminating bugs is called debugging Syntax error: A grammatical mistake in a program – The compiler can detect these errors, and will output an error message saying what it thinks the error is, and where it thinks the error is Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Error Messages (2 of 2) Run-time error: An error that is not detected until a program is run – The compiler cannot detect these errors: an error message is not generated after compilation, but after execution Logic error: A mistake in the underlying algorithm for a program – The compiler cannot detect these errors, and no error message is generated after compilation or execution, but the program does not do what it is supposed to do Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Identifiers (1 of 2) Identifier: The name of a variable or other item (class, method, object, etc.) defined in a program – A Java identifier must not start with a digit, and all the characters must be letters, digits, or the underscore symbol – Java identifiers can theoretically be of any length – Java is a case-sensitive language:Rate, rate, and RATE are the names of three different variables Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Identifiers (2 of 2) Keywords and Reserved words: Identifiers that have a predefined meaning in Java – Do not use them to name anything else Predefined identifiers: Identifiers that are defined in libraries required by the Java language standard – Although they can be redefined, this could be confusing and dangerous if doing so would change their standard meaning Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Naming Conventions Start the names of variables, classes, methods, and objects with a lowercase letter, indicate “word” boundaries with an uppercase letter, and restrict the remaining characters to digits and lowercase letters Start the names of classes with an uppercase letter and, otherwise, adhere to the rules above Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Variable Declarations Every variable in a Java program must be declared before it is used – A variable declaration tells the compiler what kind of data (type) will be stored in the variable – The type of the variable is followed by one or more variable names separated by commas, and terminated with a semicolon – Variables are typically declared just before they are used or at the start of a block (indicated by an opening brace { ) – Basic types in Java are called primitive types Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Statements Display 1.2 Primitive Types Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Statements With Primitive Types (1 of 2) In Java, the assignment statement is used to change the value of a variable – The equal sign (=) is used as the assignment operator – An assignment statement consists of a variable on the left side of the operator, and an expression on the right side of the operator – An expression consists of a variable, number, or mix of variables, numbers, operators, and/or method invocations Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Statements With Primitive Types (2 of 2) – When an assignment statement is executed, the expression is first evaluated, and then the variable on the left-hand side of the equal sign is set equal to the value of the expression – Note that a variable can occur on both sides of the assignment operator – The assignment operator is automatically executed from right-to-left, so assignment statements can be chained Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Initialize Variables (1 of 2) A variable that has been declared but that has not yet been given a value by some means is said to be uninitialized In certain cases an uninitialized variable is given a default value – It is best not to rely on this – Explicitly initialized variables have the added benefit of improving program clarity Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Initialize Variables (2 of 2) The declaration of a variable can be combined with its initialization via an assignment statement – Note that some variables can be initialized and others can remain uninitialized in the same declaration Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Shorthand Assignment Statements (1 of 2) Shorthand assignment notation combines the assignment operator (=) and an arithmetic operator It is used to change the value of a variable by adding, subtracting, multiplying, or dividing by a specified value The general form is which is equivalent to – The Expression can be another variable, a constant, or a more complicated expression – Some examples of what Op can be are +, −, *, /, or % Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Shorthand Assignment Statements (2 of 2) Example: Equivalent To: Count plus equalto two Count = count plus two Sum minus equal to dicount Sum equal to sum minus discount semicolon Bonus astrich equal to two Bonus equal to bonus multiplied by two Time slash equal to rushfactor Time equal to time divided by rush factor Change percent equal to hundred semicolon Change equal to change percentage hundred Amount astrich equal to count one plus count two Amount equal to amount multiplied by open bracket count one plus semicolon count two close bracket semicolon Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Compatibility (1 of 3) In general, the value of one type cannot be stored in a variable of another type – The above example results in a type mismatch because a double value cannot be stored in an int variable However, there are exceptions to this – For example, an int value can be stored in a double type Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Compatibility (2 of 3) More generally, a value of any type in the following list can be assigned to a variable of any type that appears to the right of it – Note that as your move down the list from left to right, the range of allowed values for the types becomes larger Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Compatibility (3 of 3) An explicit type cast is required to assign a value of one type to a variable whose type appears to the left of it on the above list (e.g., double to int) Note that in Java an int cannot be assigned to a variable of type boolean, nor can a boolean be assigned to a variable of type int Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Constants (1 of 3) Constant (or literal): An item in Java which has one specific value that cannot change – Constants of an integer type may not be written with a decimal point (e.g.,10) – Constants of a floating-point type can be written in ordinary decimal fraction form (e.g., 367000.0 or 0.000589) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Constants (2 of 3) Constant of a floating-point type can also be written in scientific (or floating-point) notation (e.g., 3.67e 5or 5.89e -4 ) ▪ Note that the number before the e may contain a decimal point, but the number after the e may not Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Constants (3 of 3) Constants of type char are expressed by placing a single character in single quotes (e.g., ‘z’) Constants for strings of characters are enclosed by double quotes (e.g., “ Welcome to Java”) There are only two boolean type constants, true and false – Note that they must be spelled with all lowercase letters Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Arithmetic Operators and Expressions (1 of 3) As in most languages, expressions can be formed in Java using variables, constants, and arithmetic operators – These operators are + (addition), −(subtraction), * (multiplication), / (division), and % (modulo, remainder) – An expression can be used anyplace it is legal to use a value of the type produced by the expression Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Arithmetic Operators and Expressions (2 of 3) If an arithmetic operator is combined with int operands, then the resulting type is int If an arithmetic operator is combined with one or two double operands, then the resulting type is double If different types are combined in an expression, then the resulting type is the right-most type on the following list that is found within the expression Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Arithmetic Operators and Expressions (2 of 2) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Parentheses and Precedence Rules (1 of 2) An expression can be fully parenthesized in order to specify exactly what subexpressions are combined with each operator If some or all of the parentheses in an expression are omitted, Java will follow precedence rules to determine, in effect, where to place them – However, it's best (and sometimes necessary) to include them Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Parentheses and Precedence Rules (2 of 2) Display 1.3 Precedence Rules Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Precedence and Associativity Rules (1 of 2) When the order of two adjacent operations must be determined, the operation of higher precedence (and its apparent arguments) is grouped before the operation of lower precedence is evaluated as When two operations have equal precedence, the order of operations is determined by associativity rules Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Precedence and Associativity Rules (2 of 2) – Unary operators of equal precedence are grouped right-to-left +−+rate is evaluated as + (− (+ rate )) – Binary operators of equal precedence are grouped left-to-right base + rate + hours is evaluated as (base + rate) + hours – Exception: A string of assignment operators is grouped right-to-left – n1 = n2 = n3; is evaluated as n1 = (n2 = n3 ) ; Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Pitfall: Round-Off Errors in Floating-Point Numbers Floating point numbers are only approximate quantities – Mathematically, the floating-point number 1.0/3.0 is equal to 0.3333333 … – A computer has a finite amount of storage space ▪ It may store 1.0/3.0 as something like 0.3333333333, which is slightly smaller than one-third Computers actually store numbers in binary notation, but the consequences are the same: floating-point numbers may lose accuracy Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Integer and Floating-Point Division When one or both operands are a floating-point type, division results in a floating-point type 15.0 2 evaluates to 7.5 When both operands are integer types, division results in an integer type – Any fractional part is discarded – The number is not rounded 15 2 evaluates to 7 Be careful to make at least one of the operands a floating- point type if the fractional portion is needed Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved The % Operator The % operator is used with operands of type int to recover the information lost after performing integer division 15 2 evaluates to the quotient 7 15%2 evaluates to the remainder 1 The % operator can be used to count by 2’s, 3’s, or any other number – To count by twos, perform the operation number % 2, and when the result is 0, number is even Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Type Casting A type cast takes a value of one type and produces a value of another type with an “equivalent” value – If n and m are integers to be divided, and the fractional portion of the result must be preserved, at least one of the two must be type cast to a floating-point type before the division operation is performed – Note that the desired type is placed inside parentheses immediately in front of the variable to be cast – Note also that the type and value of the variable to be cast does not change Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved More Details About Type Casting When type casting from a floating-point to an integer type, the number is truncated, not rounded – (int)2.9 evaluates to 2, not 3 When the value of an integer type is assigned to a variable of a floating-point type, Java performs an automatic type cast called a type coercion In contrast, it is illegal to place a double value into an int variable without an explicit type cast Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Increment and Decrement Operators (1 of 2) The increment operator (++) adds one to the value of a variable – If n is equal to 2, then n++ or ++n will change the value of n to 3 The decrement operator (−−) subtracts one from the value of a variable – If n is equal to 4, then n−−or −−n will change the value of n to 3 Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Increment and Decrement Operators (2 of 2) When either operator precedes its variable, and is part of an expression, then the expression is evaluated using the changed value of the variable – If n is equal to 2, then 2 * (+ +n) evaluates to 6 When either operator follows its variable, and is part of an expression, then the expression is evaluated using the original value of the variable, and only then is the variable value changed – If n is equal to 2, then 2 * (n + + ) evaluates to 4 Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved The Class String There is no primitive type for strings in Java The class String is a predefined class in Java that is used to store and process strings Objects of type String are made up of strings of characters that are written within double quotes – Any quoted string is a constant of type String “Live long and prosper.” A variable of type String can be given the value of a String object String blessing = “Live long and prosper.”; Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Concatenation of Strings Concatenation: Using the + operator on two strings in order to connect them to form one longer string – If greeting is equal to “Hello”, and javaClass is equal to “class”, then greeting + javaClass is equal to “Hello class” Any number of strings can be concatenated together When a string is combined with almost any other type of item, the result is a string – “The answer is” + 42 evaluates to “The answer is 42” Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes, Objects, and Methods (1 of 2) A class is the name for a type whose values are objects Objects are entities that store data and take actions – Objects of the String class store data consisting of strings of characters The actions that an object can take are called methods – Methods can return a value of a single type and/or perform an action – All objects within a class have the same methods, but each can have different data values Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes, Objects, and Methods (2 of 2) Invoking or calling a method: a method is called into action by writing the name of the calling object, followed by a dot, followed by the method name, followed by parentheses – This is sometimes referred to as sending a message to the object – The parentheses contain the information (if any) needed by the method – This information is called an argument (or arguments) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (1 of 10) The String class contains many useful methods for string- processing applications – A String method is called by writing a String object, a dot, the name of the method, and a pair of parentheses to enclose any arguments – If a String method returns a value, then it can be placed anywhere that a value of its type can be used Always count from zero when referring to the position or index of a character in a string Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (2 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (3 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (4 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (5 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (6 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (7 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (8 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (9 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (10 of 10) Display 1.5 String Indexes Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Escape Sequences (1 of 2) A backslash (\) immediately preceding a character (i.e., without any space) denotes an escape sequence or an escape character – The character following the backslash does not have its usual meaning – Although it is formed using two symbols, it is regarded as a single character Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Escape Sequences (2 of 2) Display 1.6 Escape Sequences Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Processing A String object in Java is considered to be immutable, i.e., the characters it contains cannot be changed There is another class in Java called StringBuffer that has methods for editing its string objects However, it is possible to change the value of a String variable by using an assignment statement Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Character Sets ASCII: A character set used by many programming languages that contains all the characters normally used on an English-language keyboard, plus a few special characters – Each character is represented by a particular number Unicode: A character set used by the Java language that includes all the ASCII characters plus many of the characters used in languages with a different alphabet from English Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Naming Constants Instead of using “anonymous” numbers in a program, always declare them as named constants, and use their name instead – This prevents a value from being changed inadvertently – It has the added advantage that when a value must be modified, it need only be changed in one place – Note the naming convention for constants: Use all uppercase letters, and designate word boundaries with an underscore character Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Comments A line comment begins with the symbols //, and causes the compiler to ignore the remainder of the line – This type of comment is used for the code writer or for a programmer who modifies the code A block comment begins with the symbol pair – The compiler ignores anything in between – This type of comment can span several lines – This type of comment provides documentation for the users of the program Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Program Documentation Java comes with a program called javadoc that will automatically extract documentation from block comments in the classes you define – As long as their opening has an extra asterisk (/**) Ultimately, a well written program is self-documenting – Its structure is made clear by the choice of identifier names and the indenting pattern – When one structure is nested inside another, the inside structure is indented one more level Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Naming Constant Display 1.8 Comments and Named Constant Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Copyright Copyright © 2016,2013,2010 Pearson Education Inc. All Rights Reserved

Use Quizgecko on...
Browser
Browser