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

Similar documents
KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Introduction to Java. CS 3: Computer Programming in Java

Java Interview Questions and Answers

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Java CPD (I) Frans Coenen Department of Computer Science

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

C Compiler Targeting the Java Virtual Machine

Object Oriented Software Design

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Object Oriented Software Design

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Habanero Extreme Scale Software Research Project

C++ INTERVIEW QUESTIONS

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Glossary of Object Oriented Terms

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Chapter 3: Restricted Structures Page 1

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Crash Course in Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Contents. 9-1 Copyright (c) N. Afshartous

Chapter 5 Functions. Introducing Functions

Introduction to Programming

CS 111 Classes I 1. Software Organization View to this point:

Object Oriented Software Design II

Interactive Applications (CLI) and Math

Lecture 5: Java Fundamentals III

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Java Crash Course Part I

Java Basics: Data Types, Variables, and Loops

Stack Allocation. Run-Time Data Structures. Static Structures

Moving from CS 61A Scheme to CS 61B Java

1.1 Your First Program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

The C Programming Language course syllabus associate level

AP Computer Science Java Subset

Java Programming Fundamentals

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

An Overview of Java. overview-1

CS 106 Introduction to Computer Science I

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Install Java Development Kit (JDK) 1.8

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Chapter 13 - Inheritance

Basic Object-Oriented Programming in Java

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Part I. Multiple Choice Questions (2 points each):

LAB4 Making Classes and Objects

Introduction to Java

Introduction: Abstract Data Types and Java Review

Chapter One Introduction to Programming

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Module 2 Stacks and Queues: Abstract Data Types

X86-64 Architecture Guide

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Chapter 5 Names, Bindings, Type Checking, and Scopes

7.1 Our Current Model

Stacks. Linear data structures

Stack vs. Heap. Introduction to Programming. How the Stack Works. Primitive vs. Reference Types. Stack

Chapter 1 Java Program Design and Development

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Java Application Developer Certificate Program Competencies

CMSC 202H. ArrayList, Multidimensional Arrays

objectives chapter Define classes that act like blueprints for new objects, made of variables and methods. Explain encapsulation and Java modifiers.

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Tutorial on Writing Modular Programs in Scala

- Applet java appaiono di frequente nelle pagine web - Come funziona l'interprete contenuto in ogni browser di un certo livello? - Per approfondire

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Variables, Constants, and Data Types

Chapter 7D The Java Virtual Machine

The Java Virtual Machine (JVM) Pat Morin COMP 3002

Object-Oriented Programming Lecture 2: Classes and Objects

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

J a v a Quiz (Unit 3, Test 0 Practice)

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

1 Abstract Data Types Information Hiding

Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings:

Database Programming with PL/SQL: Learning Objectives

Chapter 2: Elements of Java

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Semantic Analysis: Types and Type Checking

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Transcription:

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

Copyright 1992-2015 by Pearson

Best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. divide and conquer. Topics in this chapter static methods Method-call stack Simulation techniques with random-number generation. How to declare values that cannot change (i.e., constants) in your programs. Method overloading. Copyright 1992-2015 by Pearson

Java programs combine new methods and classes that you write with predefined methods and classes available in the Java Application Programming Interface and in other class libraries. Related classes are typically grouped into packages so that they can be imported into programs and reused. You ll learn how to group your own classes into packages in Section 21.4.10. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Divide and Conquer with Classes and Methods Classes and methods help you modularize a program by separating its tasks into self-contained units. Statements in method bodies Written only once Hidden from other methods Can be reused from several locations in a program Divide-and-conquer approach Constructing programs from small, simple pieces Software reusability Use existing classes and methods as building blocks to create new pro-grams. Dividing a program into meaningful methods makes the program easier to debug and maintain. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Hierarchical Relationship Between Method Calls Hierarchical form of management (Fig. 6.1). A boss (the caller) asks a worker (the called method) to perform a task and report back (return) the results after completing the task. The boss method does not know how the worker method performs its designated tasks. The worker may also call other worker methods, unbeknown to the boss. Hiding of implementation details promotes good software engineering. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Sometimes a method performs a task that does not depend on an object. Applies to the class in which it s declared as a whole Known as a static method or a class method It s common for classes to contain convenient static methods to perform common tasks. To declare a method as static, place the keyword static before the return type in the method s declaration. Calling a static method ClassName.methodName(arguments) Copyright 1992-2015 by Pearson

Math Class Methods Class Math provides a collection of static methods that enable you to perform common mathematical calculations. Method arguments may be constants, variables or expressions. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Recall that each object of a class maintains its own copy of every instance variable of the class. There are variables for which each object of a class does not need its own separate copy (as you ll see momentarily). Such variables are declared static and are also known as class variables. When objects of a class containing static variables are created, all the objects of that class share one copy of those variables. Together a class s static variables and instance variables are known as its fields. You ll learn more about static fields in Section 8.11. Copyright 1992-2015 by Pearson

Math Class static Constants PI and E Math fields for commonly used mathematical constants Math.PI (3.141592653589793) Math.E (2.718281828459045) Declared in class Math with the modifiers public, final and static public allows you to use these fields in your own classes. A field declared with keyword final is constant its value cannot change after the field is initialized. Copyright 1992-2015 by Pearson

Why is method main declared static? The JVM attempts to invoke the main method of the class you specify at this point no objects of the class have been created. Declaring main as static allows the JVM to invoke main without creating an instance of the class. Copyright 1992-2015 by Pearson

Solve quadratic equation ax 2 + bx + c = 0. public class Quadratic { public static void main(string[] args) { double a,b,c,d; // input coefficient values.. } } // calculate roots d = Math.sqrt(b*b - 4.0*a*c); double root1 = (-b + d) / (2.0*a); double root2 = (-b - d) / (2.0*a); // print them out System.out.println(root1); System.out.println(root2); Dr. Amal Khalifa, 2012

public class Flip { public static void main(string[] args) { for (int i=0; i<1000; i++) if (Math.random() < 0.5) System.out.println("Heads"); else System.out.println("Tails"); } } % java Flip can produce only double values in the range of 0.0 and 1.0. Heads % java Flip Heads % java Flip Tails Dr. Amal Khalifa, 2014 22

A method declaration begins with a method header public class MyClass { static int min ( int num1, int num2 ) properties return type method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument

The header is followed by the method body: class MyClass { static int min(int num1, int num2) { int minvalue = (num1 < num2)? num1 : num2; return minvalue; } } Computer Science Department

The return type of a method indicates the type of value that the method sends back to the calling location The return statement specifies the value that will be returned Its expression must conform to the return type A method can return at most 1 value A method that does not return a value has a void return type Computer Science Department

Be careful!!

Each time a method is called, the values of the actual arguments in the invocation are assigned to the formal arguments int num = min(2, 3); static int min (int num1, int num2) { } int minvalue = (num1 < num2? num1 : num2); return minvalue; Computer Science Department

Example

Example

Write a method that prints the multiplication table of a given number. 32

Multiple parameters are specified as a commaseparated list. There must be one argument in the method call for each parameter (sometimes called a formal parameter) in the method declaration. Each argument must be consistent with the type of the corresponding parameter. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Implementing method maximum by reusing method Math.max Two calls to Math.max, as follows: return Math.max(x, Math.max( y, z )); The first specifies arguments x and Math.max(y, z). Before any method can be called, its arguments must be evaluated to determine their values. If an argument is a method call, the method call must be performed to determine its return value. The result of the first call is passed as the second argument to the other call, which returns the larger of its two arguments. Copyright 1992-2015 by Pearson

Assembling Strings with String Concatenation String concatenation Assemble String objects into larger strings with operators + or +=. When both operands of operator + are Strings, operator + creates a new String object characters of the right operand are placed at the end of those in the left operand Every primitive value and object in Java can be represented as a String. When one of the + operator s operands is a String, the other is converted to a String, then the two are concatenated. If a boolean is concatenated with a String, the boolean is converted to the String "true" or "false". All objects have a tostring method that returns a String representation of the object. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Three ways to call a method: Using a method name by itself to call another method of the same class Using a variable that contains a reference to an object, followed by a dot (.) and the method name to call a method of the referenced object Using the class name and a dot (.) to call a static method of a class Copyright 1992-2015 by Pearson

Non-static methods are typically called instance methods. A static method can call other static methods of the same class directly and can manipulate static variables in the same class directly. To access the class s instance variables and instance methods, a static method must use a reference to an object of the class. Copyright 1992-2015 by Pearson

Three ways to return control to the statement that calls a method: When the program flow reaches the method-ending right brace When the following statement executes return; When the method returns a result with a statement like return expression; Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Stack data structure Analogous to a pile of dishes A dish is placed on the pile at the top (referred to as pushing the dish onto the stack). A dish is removed from the pile from the top (referred to as popping the dish off the stack). Last-in, first-out (LIFO) data structures The last item pushed onto the stack is the first item popped from the stack. Copyright 1992-2015 by Pearson

When a program calls a method, the called method must know how to return to its caller The return address of the calling method is pushed onto the method-call stack. If a series of method calls occurs, the successive return addresses are pushed onto the stack in last-in, first-out order. The method call stack also contains the memory for the local variables (including the method parameters) used in each invocation of a method during a program s execution. Stored as a portion of the method call stack known as the stack frame (or activation record) of the method call. Copyright 1992-2015 by Pearson

When a method call is made, the stack frame for that method call is pushed onto the method call stack. When the method returns to its caller, the stack frame is popped off the stack and those local variables are no longer known to the program. If more method calls occur than can have their stack frames stored on the program-execution stack, an error known as a stack overflow occurs. Copyright 1992-2015 by Pearson

Argument promotion Converting an argument s value, if possible, to the type that the method expects to receive in its corresponding parameter. Conversions may lead to compilation errors if Java s promotion rules are not satisfied. Promotion rules specify which conversions are allowed. apply to expressions containing values of two or more primitive types and to primitive-type values passed as arguments to methods. Each value is promoted to the highest type in the expression. Figure 6.4 lists the primitive types and the types to which each can be promoted. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Converting values to types lower in the table of Fig. 6.4 will result in different values if the lower type cannot represent the value of the higher type In cases where information may be lost due to conversion, the Java compiler requires you to use a cast operator to explicitly force the conversion to occur otherwise a compilation error occurs. Copyright 1992-2015 by Pearson

Java contains many predefined classes that are grouped into categories of related classes called packages. Java programs combine new methods and classes that you write with predefined methods and classes available in the Java Application Programming Interface and in other class libraries. Copyright 1992-2015 by Pearson

A great strength of Java is the Java API s thousands of classes. Some key Java API packages that we use in this book are described in Fig. 6.5. Overview of the packages in Java: http://docs.oracle.com/javase/7/docs/api/ overview-summary.html http://download.java.net/jdk8/docs/api/ overview-summary.html Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Declarations introduce names that can be used to refer to such Java entities. The scope of a declaration is the portion of the program that can refer to the declared entity by its name. Such an entity is said to be in scope for that portion of the program. Copyright 1992-2015 by Pearson

Basic scope rules: The scope of a parameter declaration is the body of the method in which the declaration appears. The scope of a local-variable declaration is from the point at which the declaration appears to the end of that block. The scope of a local-variable declaration that appears in the initialization section of a for statement s header is the body of the for statement and the other expressions in the header. A method or field s scope is the entire body of the class. Any block may contain variable declarations. If a local variable or parameter in a method has the same name as a field of the class, the field is hidden until the block terminates execution this is called shadowing. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Method overloading Methods of the same name declared in the same class Must have different sets of parameters Compiler selects the appropriate method to call by examining the number, types and order of the arguments in the call. Used to create several methods with the same name that perform the same or similar tasks, but on different types or different numbers of arguments. Literal integer values are treated as type int, so the method call in line 9 invokes the version of square that specifies an int parameter. Literal floating-point values are treated as type double, so the method call in line 10 invokes the version of square that specifies a double parameter. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Distinguishing Between Overloaded Methods The compiler distinguishes overloaded methods by their signatures the methods name and the number, types and order of its parameters. Return types of overloaded methods Method calls cannot be distinguished by return type. Figure 6.10 illustrates the errors generated when two methods have the same signature and different return types. Overloaded methods can have different return types if the methods have different parameter lists. Overloaded methods need not have the same number of parameters. Copyright 1992-2015 by Pearson

Copyright 1992-2015 by Pearson

Chapter 6: Read: 6.1-6.8, 6.11 and 6.12 Copyright 1992-2015 by Pearson