Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Similar documents
Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Java OOP (SE Tutorials: Learning the Java Language Trail : Object-Oriented Programming Concepts Lesson )

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Computer Components. Software{ User Programs. Operating System. Hardware

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

COMP 202 Java in one week

Java Programming. Atul Prakash

2 rd class Department of Programming. OOP with Java Programming

Introduction and Review of Java: Part 2

Computer Components. Software{ User Programs. Operating System. Hardware

Introduction to Programming Using Java (98-388)

Index COPYRIGHTED MATERIAL

Java Overview An introduction to the Java Programming Language

3. Java - Language Constructs I

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

Learning the Java Language. 2.1 Object-Oriented Programming

CSC 1214: Object-Oriented Programming

An Introduction to Processing

Program Fundamentals

Language Fundamentals Summary

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Operators. Java operators are classified into three categories:

Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CS 231 Data Structures and Algorithms, Fall 2016

Values and Variables 1 / 30

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Pace University. Fundamental Concepts of CS121 1

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CS260 Intro to Java & Android 02.Java Technology

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Java+- Language Reference Manual

13 th Windsor Regional Secondary School Computer Programming Competition

CS260 Intro to Java & Android 03.Java Language Basics

1 Shyam sir JAVA Notes

CS11 Java. Fall Lecture 1

WA1278 Introduction to Java Using Eclipse

Programming Lecture 3

Basics of Java Programming

Java Programming Tutorial 1

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Course Outline. Introduction to java

Java Bytecode (binary file)

CGS 3066: Spring 2015 JavaScript Reference

Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem

4 Programming Fundamentals. Introduction to Programming 1 1

Advanced Object-Oriented Programming Introduction to OOP and Java

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

CompSci 125 Lecture 02

Preview from Notesale.co.uk Page 9 of 108

Lexical Considerations

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

Chapter 3: Operators, Expressions and Type Conversion

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

Java Primer 1: Types, Classes and Operators

Control Flow Statements

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Lecture 1: Overview of Java

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects,

SECTION II: LANGUAGE BASICS

DEPARTMENT OF MATHS, MJ COLLEGE

JScript Reference. Contents

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Operators and Expressions

Notes of the course - Advanced Programming. Barbara Russo

Full file at

A variable is a name that represents a value. For

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

The Java Language Rules And Tools 3

Accelerating Information Technology Innovation

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

3. Java - Language Constructs I

1 Lexical Considerations

Introduction to Java & Fundamental Data Types

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Lexical Considerations

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

DM550 Introduction to Programming part 2. Jan Baumbach.

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

These two items are all you'll need to write your first application reading instructions in English.

CHAPTER 7 OBJECTS AND CLASSES

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Object-Oriented Programming

Transcription:

Introduction to Android Saturday Yanqiao ZHU Google Camp School of Software Engineering, Tongji University In courtesy of The Java Tutorials

Getting Started Introduction to Java

The Java Programming Language Java technology is both a programming language and a platform. Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers. It is intended to let application developers write once, run anywhere (WORA). Compiled Java code can run on all platforms that support Java without the need for recompilation. 3

Compilation Pipeline In the Java programming language, all source code is first written in plain text files ending with the.java extension. Those source files are then compiled into.class files by the javac compiler. A.class file does not contain code that is native to your processor; it instead contains bytecodes the machine language of the Java Virtual Machine (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine. 4

Compilation Pipeline (cont.) Because the Java VM is available on many different operating systems, the same.class files are capable of running on Microsoft Windows, Linux, or macos. Some virtual machines perform additional steps at runtime to give your application a performance boost. This includes various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code. Figure 1: An overview of the compilation process. 5

The Java Platform A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it s a software-only platform that runs on top of other hardwarebased platforms. The Java platform has two components: The Java Virtual Machine The Java Application Programming Interface (API) 6

The Java Platform (cont.) The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability. 7

What Can Java Technology Do? Every full implementation of the Java platform gives the following features: Development Tools: The development tools provide everything for compiling, running, monitoring, debugging, and documenting applications. Application Programming Interface (API): The API provides the core functionality of the Java programming language. It offers a wide array of useful classes ready for use in your own applications. It spans everything from basic objects, to networking and security, to XML generation and database access, and more. Deployment Technologies: The JDK software provides standard mechanisms such as the Java Web Start software and Java Plug-In software for deploying your applications to end users. 8

What Can Java Technology Do? (cont.) User Interface Toolkits: The JavaFX, Swing, and Java 2D toolkits make it possible to create sophisticated Graphical User Interfaces (GUIs). Integration Libraries: Integration libraries such as the Java IDL API, JDBC API, Java Naming and Directory Interface (JNDI) API, Java RMI, and Java Remote Method Invocation over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database access and manipulation of remote objects. 9

How Will Java Technology Change My Life? Get started quickly Java is easy to learn. Write less code Comparisons of program metrics (class counts, method counts, and so on) suggest that a program written in the Java programming language can be four times smaller than the same program written in C++. Write better code The Java programming language encourages good coding practices, and automatic garbage collection helps you avoid memory leaks. Develop programs more quickly The Java programming language is simpler than C++, and as such, your development time could be up to twice as fast when writing in it. 10

How Will Java Technology Change My Life? (cont.) Avoid platform dependencies You can keep your program portable by avoiding the use of libraries written in other languages. Write once, run anywhere Because applications written in the Java programming language are compiled into machine-independent bytecodes, they run consistently on any Java platform. Distribute software more easily With Java Web Start software, users will be able to launch your applications with a single click of the mouse. An automatic version check at startup ensures that users are always up to date with the latest version of your software. If an update is available, the Java Web Start software will automatically update their installation. 11

Hello World! in Java 1. /** 2. * The HelloWorldApp class implements an application that 3. * simply prints "Hello World!" to standard output. 4. */ 5. class HelloWorldApp { 6. public static void main(string[] args) { 7. System.out.println("Hello World!"); // Display the string. 8. } 9. } Listing 1: Hello World! In Java. 12

Hello World! in Java (cont.) Save the source file to HelloWorldApp.java. At the prompt, type the following command and press Return. javac HelloWorldApp.java The compiler has generated a bytecode file HelloWorldApp.class. In the same directory, enter at the prompt: java HelloWorldApp 13

Program Structure: Comments /* text */ The compiler ignores everything from /* to */. /** documentation */ This indicates a documentation comment (doc comment, for short). The javadoc tool uses doc comments when preparing automatically generated documentation. // text The compiler ignores everything from // to the end of the line. 14

Program Structure: Class Definition The most basic form of a class definition is: class name {... } The keyword class begins the class definition for a class named name, and the code for each class appears between the opening and closing curly braces marked in bold above. 15

Program Structure: The main Method In the Java programming language, every application must contain a main method whose signature is: public static void main(string[] args) The modifiers public and static can be written in arbitrary The convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose args or argv. Similar to the main function in C and C++. It s the entry point for your application and will subsequently invoke all the other methods required by your program. 16

Program Structure: The main Method (cont.) The main method accepts a single argument: an array of elements of type String. This array is the mechanism through which the runtime system passes information to your application. For example: java MyApp arg1 arg2 Each string in the array is called a command-line argument. Commandline arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this commandline argument: -descending. 17

Program Structure: The main Method (cont.) Finally, the line: System.out.println("Hello World!"); uses the System class from the core library to print the Hello World! message to standard output. Portions of this library (also known as the Application Programming Interface, or API ) will be discussed throughout the remainder of the tutorial. 18

OOP Overview Introduction to Java

Object-Oriented Programming Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which may contain data, in the form of fields, often known as attributes; code, in the form of procedures, often known as methods. A feature of objects is that an object s procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of this or self ). In OOP, computer programs are designed by making them out of objects that interact with one another. 20

OOP Terminology Object An object is a software bundle of related state and behavior. Class A class is a blueprint or prototype from which objects are created. Inheritance Inheritance provides a powerful and natural mechanism for organizing and structuring your software. Interface An interface is a contract between a class and the outside world. Package A package is a namespace for organizing classes and interfaces in a logical manner. 21

Objects Objects are key to understanding object-oriented technology. Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). 22

Objects (cont.) Methods operate on an object s internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object s methods is known as data encapsulation a fundamental principle of object-oriented programming. Figure 2: A bicycle modeled as a software object. 23

Objects (cont.) By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6. 24

Objects (cont.) Bundling code into individual software objects provides a number of benefits, including: Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. Information-hiding: By interacting only with an object s methods, the details of its internal implementation remain hidden from the outside world. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine. 25

Classes A class is the blueprint from which individual objects are created. In the real world, you ll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. 26

Inheritance Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. 27

Inheritance (cont.) In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses. Figure 3: A hierarchy of bicycle classes. 28

Inheritance (cont.) The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from. This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. 29

Interfaces Methods form the object s interface with the outside world. The buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. In its most common form, an interface is a group of related methods with empty bodies. 30

Interfaces (cont.) Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 31

Packages A package is a namespace that organizes a set of related classes and interfaces. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. 32

Packages (cont.) The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the Application Programming Interface, or API for short. Its packages represent the tasks most commonly associated with general-purpose programming. A String object contains state and behavior for character strings. A File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem. A Socket object allows for the creation and use of network sockets. Various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. 33

Java Language Basics Introduction to Java May 29, 2017 34

Variables An object stores its state in fields. The Java programming language defines the following kinds of variables: Instance Variables (Non-Static Fields) Class Variables (Static Fields) Local Variables Parameters 35

Instance Variables Technically speaking, objects store their individual states in non-static fields. Fields declared without the static keyword. 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). For example, the currentspeed of one bicycle is independent from the currentspeed of another. 36

Class Variables 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. 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. The code static int numgears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. 37

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;). 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. 38

Parameters You've 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. 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) that you ll learn about later in the tutorial. 39

Naming Conventions Variable names are case-sensitive. A variable s name can be any legal identifier an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign $, or the underscore character _. The convention is to always begin your variable names with a letter, not $ or _. Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it s technically legal to begin your variable's name with _, this practice is discouraged. White space is not permitted. 40

Naming Conventions (cont.) Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word. 41

Naming Conventions (cont.) If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearratio and currentgear are prime examples of this convention. If your variable stores a constant value, capitalize every letter and sparating subsequent words with the underscore character. Such as static final int NUM_GEARS = 6. By convention, the underscore character is never used elsewhere. 42

Java Language Keywords abstract continue for new switch assert *** default goto * package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum **** instanceof return transient catch extends int short try char final interface static void class finally long strictfp ** volatile const * float native super while true, false, and null might seem like keywords, but they are actually literals. * not used ** added in 1.2 *** added in 1.4 **** added in 5.0 43

Primitive Data Types The Java programming language is statically-typed. All variables must first be declared before they can be used. Java programming language supports eight primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. 44

Primitive Data Types (cont.) byte: The byte data type is an 8-bit signed two s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable s range is limited can serve as a form of documentation. 45

Primitive Data Types (cont.) short: The short data type is a 16-bit signed two s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. 46

Primitive Data Types (cont.) int: By default, the int data type is a 32-bit signed two's complement integer. It has a minimum value of -2 31 and a maximum value of 2 31-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2 32-1. Use the Integer class to use int data type as an unsigned integer. 47

Primitive Data Types (cont.) long: The long data type is a 64-bit two s complement integer. The signed long has a minimum value of -2 63 and a maximum value of 2 63-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2 64-1. Use this data type when you need a range of values wider than those provided by int. 48

Primitive Data Types (cont.) float: The float data type is a single-precision 32-bit IEEE 754 floating point. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. double: The double data type is a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. 49

Primitive Data Types (cont.) boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its size isn t something that s precisely defined. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). 50

Character Strings The Java programming language also provides special support for character strings via the java.lang.string class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you ll probably tend to think of it as such. 51

Operators Assignment, Arithmetic, and Unary Operators Equality, Relational, and Conditional Operators Bitwise and Bit Shift Operators 52

The Arithmetic Operators Operator Description + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator 53

The Unary Operators Operator + Description Unary plus operator; indicates positive value (numbers are positive without this) - 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 54

The Equality and Relational Operators == equal to!= not equal to > greater than >= greater than or equal to < less than <= less than or equal to 55

The Conditional Operators The && and operators perform Conditional- AND and Conditional-OR operations on two boolean expressions. These operators exhibit short-circuiting behavior, which means that the second operand is evaluated only if needed. Another conditional operator is?:, which can be thought of as shorthand for an if-then-else statement. This operator is also known as the ternary operator because it uses three operands. For example, result = somecondition? value1 : value2; this operator should be read as: If somecondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result. 56

The Type Comparison Operator The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. When using the instanceof operator, keep in mind that null is not an instance of anything. 57

Bitwise and Bit Shift Operators The bitwise & operator performs a bitwise AND operation. The bitwise ^ operator performs a bitwise exclusive OR operation. The bitwise operator performs a bitwise inclusive OR operation. 58

Expressions, Statements, and Blocks Now that you understand variables and operators, it s time to learn about expressions, statements, and blocks. Operators may be used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks. 59

Expressions An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. 60

Statements Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). Expression statements: Assignment expressions Any use of ++ or -- Method invocations Object creation expressions In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. 61

Blocks A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. 62

Control Flow Statements The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (ifthen, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language. 63

If Statements 1. class IfElseDemo { 2. public static void main(string[] args) { 3. int testscore = 76; 4. char grade; 5. if (testscore >= 90) { grade = 'A'; } 6. else if (testscore >= 80) { grade = 'B'; } 7. else if (testscore >= 70) { grade = 'C'; } 8. else if (testscore >= 60) { grade = 'D'; } 9. else { grade = 'F'; } 10. System.out.println("Grade = " + grade); 11. } 12.} Listing 2: An example of branching: IfElseDemo assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on. 64

Switch Statements Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer. 65

Switch Statements (cont.) Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. 66

Using Strings in switch Statements In Java SE 7 and later, you can use a String object in the switch statement s expression. The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used. 67

While Loops The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { statement(s) } 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. The while statement continues testing the expression and executing its block until the expression evaluates to false. 68

For Loops The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the for loop because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (initialization; termination; increment) { statement(s) } When using this version of the for statement, keep in mind that: The initialization expression initializes the loop; it s 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. 69

Break Statements Unlabeled break: Control flow then transfers to the statement after the for loop. An unlabeled break statement terminates the innermost switch, for, while, or do-while statement. Labeled break: It terminates an outer statement. The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement. 70

Developers