100% found this document useful (2 votes)
9 views

Fundamentals Of Java Programming Ogihara Mitsunori instant download

The document is a promotional listing for the book 'Fundamentals of Java Programming' by Mitsunori Ogihara, which is designed for introductory Java programming courses. It includes links to download the book and other related Java programming resources. The book aims to cover essential programming concepts within a single semester, excluding advanced topics like graphical user interfaces.

Uploaded by

roulindoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
9 views

Fundamentals Of Java Programming Ogihara Mitsunori instant download

The document is a promotional listing for the book 'Fundamentals of Java Programming' by Mitsunori Ogihara, which is designed for introductory Java programming courses. It includes links to download the book and other related Java programming resources. The book aims to cover essential programming concepts within a single semester, excluding advanced topics like graphical user interfaces.

Uploaded by

roulindoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Fundamentals Of Java Programming Ogihara

Mitsunori download

https://ebookbell.com/product/fundamentals-of-java-programming-
ogihara-mitsunori-21896840

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Fundamentals Of Java Programming Mitsunori Ogihara

https://ebookbell.com/product/fundamentals-of-java-programming-
mitsunori-ogihara-59047274

Learn Java 17 Programming Learn The Fundamentals Of Java Programming


With This Updated Guide With The Latest Features 2nd Ed 2nd Edition
Nick Samoylov

https://ebookbell.com/product/learn-java-17-programming-learn-the-
fundamentals-of-java-programming-with-this-updated-guide-with-the-
latest-features-2nd-ed-2nd-edition-nick-samoylov-44467076

Java 17 For Absolute Beginners Learn The Fundamentals Of Java


Programming 2nd Edition Iuliana Cosmina

https://ebookbell.com/product/java-17-for-absolute-beginners-learn-
the-fundamentals-of-java-programming-2nd-edition-iuliana-
cosmina-48643530

Java Projects Learn The Fundamentals Of Java 11 Programming By


Building Industry Grade Practical Projects 2nd Edition Peter Verhas

https://ebookbell.com/product/java-projects-learn-the-fundamentals-of-
java-11-programming-by-building-industry-grade-practical-projects-2nd-
edition-peter-verhas-22964872
Java Projects Learn The Fundamentals Of Java 11 Programming By
Building Industry Grade Practical Projects 2nd Edition Verhas

https://ebookbell.com/product/java-projects-learn-the-fundamentals-of-
java-11-programming-by-building-industry-grade-practical-projects-2nd-
edition-verhas-55588322

Java For Beginners A Complete Guide To Learn The Fundamentals Of Java


And Start Programming Today Megane Noel

https://ebookbell.com/product/java-for-beginners-a-complete-guide-to-
learn-the-fundamentals-of-java-and-start-programming-today-megane-
noel-47526100

Fundamentals Of Java 4th Edition Kenneth Lambert Martin Osborne

https://ebookbell.com/product/fundamentals-of-java-4th-edition-
kenneth-lambert-martin-osborne-4336886

Fundamentals Of Computer Science Using Java 1st Edition David Hughes

https://ebookbell.com/product/fundamentals-of-computer-science-using-
java-1st-edition-david-hughes-1021582

Fundamentals Of Computer Graphics With Java Opengl And Jogl David J


Eck

https://ebookbell.com/product/fundamentals-of-computer-graphics-with-
java-opengl-and-jogl-david-j-eck-50195618
Mitsunori Ogihara

Fundamentals
of Java
Programming
Fundamentals of Java Programming
Mitsunori Ogihara

Fundamentals of Java
Programming

123
Mitsunori Ogihara
Department of Computer Science
University of Miami
Miami, FL, USA

ISBN 978-3-319-89490-4 ISBN 978-3-319-89491-1 (eBook)


https://doi.org/10.1007/978-3-319-89491-1

Library of Congress Control Number: 2018940440

© Springer Nature Switzerland AG 2018


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by
similar or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply,
even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and
therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true
and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, express or implied,
with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains
neutral with regard to jurisdictional claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
To my family
Preface

This book was born from the desire of having an introductory Java programming textbook whose
contents can be covered in one semester. The book was written with two types of audience in mind:
those who intend to major in computer science and those who want to get a glimpse of computer
programming. The book does not cover graphical user interfaces or the materials that are taught in a
data structure course. The book very quickly surveys the Java Collection Framework and the generics
in the penultimate chapter. The book also covers the concepts of online and recursive algorithms in
the last chapter. The instructors who choose to use this textbook are free to skip these chapters if
there is no sufficient time. Except for the code examples that receive parameters from the command
line, the code examples can be compiled and run in a command-line environment as well as in IDEs.
To execute those code examples in an IDE, the user must follow the step of provide args before
execution. The code examples appearing in the book have very few comments, since the actions of
the code are explained in the prose. The code examples with extensive comments are available for the
publisher. There are PDF lecture slides accompanying the book. They are prepared using the Beamer
environment of LATEX. The source codes of the lecture slides may be available through the publisher.

Acknowledgements I would like to take this opportunity to thank those who helped me in
writing this book: Paul Drougas (Springer), Victor Milenkovic (University of Miami), Ted Pawlicki
(University of Rochester), Ken Regan (University at Buffalo), Geoff Sutcliffe (University of Miami),
and Osamu Watanabe (Tokyo Institute of Technology). Huge thanks go to my daughter Ellen, who
painstakingly read through the draft and provided constructive criticisms.

Miami, FL, USA Mitsunori Ogihara

vii
Contents

Part I Programming Basics

1 “Hello, World!” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1 The Programming Environment for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 The Java Virtual Machine (JVM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Changing Folders in a Command Line Interface . . . . . . . . . . . . . . . . . . . . . . 4
1.1.3 Source Codes, Bytecodes, and Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 The First Program, “Hello, World!” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2.1 Methods and Their Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.2 System.out.println and System.out.print . . . . . . . . . . . . . . . . 10
1.2.3 Spacing in the Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2.4 Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2.5 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3 Using Multiple Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.3.1 System.out.println and System.out.print (Reprise) . . . . . . . 15
1.3.2 Printing Multiple-Line Texts on the Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.3.3 Escaping Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.3.4 Printing Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2 Using Data for Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.1 Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.1.1 Data and Their Taxonomy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.1.2 Number Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.1.3 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.1.4 Assigning Values to Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.2 The Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.3 Using Variables for Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.3.1 Quarterbacks Program (Reprise) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.3.2 Number Arithmetics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.3.3 Computing the Body-Mass Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.3.4 Sum of Integers from 1 to 100 à la Gauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.3.5 Simplified Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
2.4 An Introduction to the String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
2.4.1 The String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
2.4.2 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

ix
x Contents

3 Reading Keyboard Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69


3.1 Class Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.1.1 Importing Source Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.1.2 The Instantiation of a Scanner Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.2 Reading Data with a Scanner Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.3 Reading Input from the Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4 Decomposing Code into Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.1 Procedural Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.1.1 Printing Rectangles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.1.2 Printing Quadrangles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
4.1.3 “Old MacDonald Had a Farm” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.1.4 A General Strategy for Procedural Decomposition . . . . . . . . . . . . . . . . . . . . . 101
4.2 Using Multiple Program Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
5 Passing Values to and from Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.1 Passing Values to Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.1.1 Methods That Work with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.1.2 Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
5.2 Receiving a Value from a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
5.3 Class Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.3.1 Mathematical Functions in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
5.3.2 Mortgage Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
6 Conditions and Their Use for Controlling the Flow of Programs . . . . . . . . . . . . . . . . . . . 143
6.1 Condition and Its Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
6.2 The If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
6.2.1 If . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
6.2.2 Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
6.2.3 If-Else Inside If/Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
6.2.4 Truncation of Conditional Evaluations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Part II Loops

7 For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
7.1 Using For-Loops for Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
7.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
7.2.1 Simple Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
7.2.2 Iteration with an Auxiliary Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
7.3 Double For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
7.4 Computing the Maximum and Minimum in a Series of Numbers . . . . . . . . . . . . . . . . 193
7.5 A Betting Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
7.5.1 For-Loops with Skipped Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
7.5.2 The Statements continue and break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
7.6 Computing the Fibonacci Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
8 Formatted Printing Using printf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
8.1 General Rules for printf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
8.2 Formatted Printing of String Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
8.3 Formatted Printing of Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Contents xi

8.4 Formatted Printing of Floating Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216


8.5 Printing the Fibonacci Sequence (Reprise) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
9 Classes String and StringBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
9.1 Methods for Obtaining Information from String Data . . . . . . . . . . . . . . . . . . . . . . . 225
9.2 Methods for Comparing String Data with Another . . . . . . . . . . . . . . . . . . . . . . . . . . 228
9.2.1 The Equality Test and the Comparison in Dictionary Order . . . . . . . . . . . . . 228
9.2.2 The Prefix and Suffix Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9.3 Methods for Searching for a Pattern in a String Data . . . . . . . . . . . . . . . . . . . . . . . . 231
9.4 Methods for Creating New String Data from Another . . . . . . . . . . . . . . . . . . . . . . . 234
9.4.1 String.format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
9.5 Class StringBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10 The Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
10.1 The Syntax of Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
10.2 Using a char Data in a Switch-Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
10.3 Using a String Data in a Switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
11 While-Loops and Do-While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
11.1 Using While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
11.1.1 The Syntax of While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
11.1.2 Summing Input Numbers Until the Total Reaches a Goal . . . . . . . . . . . . . . . 265
11.1.3 Integer Overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
11.1.4 Vending Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
11.1.5 The Collatz Conjecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
11.1.6 Covnerting Decimal Numbers to Binary Numbers . . . . . . . . . . . . . . . . . . . . . 273
11.1.7 Infinite Loops and Their Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
11.2 Using Do-While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
11.2.1 The Syntax of Do-While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
11.2.2 “Waiting for Godot” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
11.2.3 Converting Decimal Numbers to Binary Numbers (Reprise) . . . . . . . . . . . . 278
11.3 CTRL-D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
11.4 Approximating the Square Root of a Real Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

Part III Arrays and Objects

12 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.1.1 The Structure of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.1.2 Computing the Number of Occurrences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
12.1.3 ArrayIndexOutOfBoundsException . . . . . . . . . . . . . . . . . . . . . . . . . 303
12.2 Relative Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
12.2.1 The Concept of Relative Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
12.2.2 Calculating the BMI for a Range of Weight Values . . . . . . . . . . . . . . . . . . . . 306
12.2.3 Counting the Occurrences of Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
12.3 Arrays of boolean Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
12.4 Using Multiple Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
12.5 String Methods That Return an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
xii Contents

13 The Class Arrays and Resizing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325


13.1 The Class Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
13.2 Reordering Elements in an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
13.2.1 Reversing the Order of Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
13.2.2 Cyclic Shifting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
13.3 Modifications of an Array That Require Resizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
13.3.1 Insertion and Deletion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
13.3.2 Adjoining Two Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
13.4 args . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
13.5 Searching for an Element in an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
13.5.1 Sequential Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
13.5.2 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
13.6 Arrays with Capacity and Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
14 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
14.1 Rectangular Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
14.1.1 Defining Multi-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
14.1.2 Summing the Elements in Subsequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
14.2 Jagged Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
15 Class File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
15.1 Class File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
15.1.1 The File Path and the Instantiation of a File Object . . . . . . . . . . . . . . . . . . 367
15.1.2 File Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
15.1.3 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
15.1.4 File Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
15.2 Using Scanner Objects to Read from Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
15.3 Using PrintStream to Write to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
16 Designing Object Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
16.1 Packaging a Group of Data as an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
16.1.1 The Position of a Game Piece . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
16.1.2 Private Instance Variables and the toString Method . . . . . . . . . . . . . . . . . 395
16.1.3 Using Constants in an Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
16.1.4 Information Hiding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
16.2 An Object Class Representing a Bank Account . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
16.3 Array with Capacity and Size (Reprise) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415

Part IV Advanced Concepts

17 Interfaces, Inheritance, and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427


17.1 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
17.1.1 The Structure of an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
17.1.2 A Simple Pizza Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
17.2 Subclasses and Superclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
17.2.1 Extending Existing Classes and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
17.2.2 Writing Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
17.3 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
Contents xiii

17.4 Boxed Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446


17.5 Interface Comparable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
18 Generic Class Parameters and the Java Collection Framework . . . . . . . . . . . . . . . . . . . . 457
18.1 ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
18.1.1 Maintaining a Collection of Merchandise Items . . . . . . . . . . . . . . . . . . . . . . . 457
18.1.2 The Class for Merchandise Item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
18.1.3 The Comparator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
18.1.4 The Collection of Merchandise Items That Uses ArrayList . . . . . . . . . . 459
18.1.5 The Main Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
18.2 The Dynamic Maintenance of the Largest K Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
18.3 The Java Collection Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
18.3.1 The Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
18.3.2 Some Classes from the Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
18.3.3 A Demonstration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
19 Online and Recursive Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
19.1 Online Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
19.1.1 The Definition of Online Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
19.1.2 Computing Recurrences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
19.1.3 Computing the Factorial Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
19.2 Recursive Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
19.2.1 Computing the Factorial Function Recursively . . . . . . . . . . . . . . . . . . . . . . . . 492
19.2.2 The Greatest Common Divisor of Two Integers . . . . . . . . . . . . . . . . . . . . . . . 497
19.2.3 The Tower of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
List of Figures

Fig. 1.1 The program layers, JVM, JRE, and JDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4


Fig. 1.2 A screen short of Terminal on a Mac OS X machine . . . . . . . . . . . . . . . . . . . . . . . 4
Fig. 1.3 An IDE screen of Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Fig. 1.4 The compilation and execution of HelloWorld.java . . . . . . . . . . . . . . . . . . . 6

Fig. 3.1 The results of five consecutive calls of next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73


Fig. 3.2 The results of executing a program that uses next and nextLine . . . . . . . . . . 77

Fig. 4.1 The method calls in Rectangle01 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91


Fig. 4.2 The method calls in Rectangle02 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Fig. 4.3 The decomposition of actions in the generation of the quadrant . . . . . . . . . . . . . . 94
Fig. 4.4 The dependency among methods in OldMacDonaldDecomposed.java . . 101
Fig. 4.5 The dependency among methods in the two source code . . . . . . . . . . . . . . . . . . . . 104

Fig. 5.1 The call-by-reference concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

Fig. 6.1 The execution diagram of an if-statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150


Fig. 6.2 The execution diagram of Temperature01.java . . . . . . . . . . . . . . . . . . . . . . 152
Fig. 6.3 The combinations of temperature and humidity considered in Temperature03
................................................................... 154
Fig. 6.4 The execution diagram of an if-else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Fig. 6.5 A hypothetical situation with interwoven conditions . . . . . . . . . . . . . . . . . . . . . . . 160

Fig. 7.1 A generic flow chart of for-loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176


Fig. 7.2 The code execution diagram of ForExample . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

Fig. 11.1 A diagram that represents the while-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264

Fig. 12.1 A view of an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296

Fig. 13.1 Swapping values between two array elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331


Fig. 13.2 Reversing the order of appearance of elements in an array . . . . . . . . . . . . . . . . . . 332
Fig. 13.3 The results obtained by executing cyclic shifts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Fig. 13.4 An algorithm for left cyclic shift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Fig. 13.7 An array with capacity and size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

xv
xvi List of Figures

Fig. 13.8 The concept of a array with capacity and size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

Fig. 14.1 The structure of a multi-dimensional array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

Fig. 15.1 The mechanism for handling run-time errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371

Fig. 16.1 An 8 × 8 game board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392


Fig. 16.3 A black box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402

Fig. 17.1 Two interfaces and their implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436


Fig. 17.2 A PizzaComplex object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438

Fig. 18.1 The Java Collection Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474


Fig. 18.2 A LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
Fig. 18.3 A hash table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477

Fig. 19.1 The value passing that occurs during the computation of the factorial (part 1) . . 495
Fig. 19.2 The value passing that occurs during the computation of the factorial (part 2) . . 495
Fig. 19.3 The value passing that occurs during the computation of the factorial (part 3) . . 495
Fig. 19.4 The value passing that occurs during the computation of the factorial (part 4) . . 495
Fig. 19.5 The value passing that occurs during the computation of the factorial (part 5) . . 495
Fig. 19.6 The value passing that occurs during the computation of the factorial (part 6) . . 496
Fig. 19.7 The value passing that occurs during the computation of the factorial (part 7) . . 496
Fig. 19.8 The value passing that occurs during the computation of the factorial (part 8) . . 496
Fig. 19.9 The value passing that occurs during the computation of the factorial (part 9) . . 496
Fig. 19.10 The value passing that occurs during the computation of the factorial (part 10) . 496
Fig. 19.11 The value passing that occurs during the computation of the factorial (part 11) . 497
Fig. 19.12 An example of the tower of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
Fig. 19.13 The solution to a small Tower of Hanoi problem . . . . . . . . . . . . . . . . . . . . . . . . . . 502
List of Tables

Table 1.1 A short list of commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5


Table 1.2 The list of meaningful symbols in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Table 2.1 The primitive data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


Table 2.2 The list of reserved words in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Table 2.3 The selection of number types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

Table 3.1 Selected methods of Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

Table 5.1 One-parameter functions in Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125


Table 5.2 Two-parameter functions in Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

Table 9.1 A list of String methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

Table 10.1 The output generated by the three examples of switch . . . . . . . . . . . . . . . . . . . 246

Table 15.1 A list of File methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

xvii
Part I
Programming Basics
“Hello, World!”
1

1.1 The Programming Environment for Java

1.1.1 The Java Virtual Machine (JVM)

Java is one of the most popular programming languages. It is a descendant of the programming
language C and is much related to C++. Java, like C++, embodies the concept of object-oriented
programming, which allows a programmer to define a type of data with its permissible set of
operations.
To execute a Java program on a machine, the machine needs an installation of the Java Running
Environment (JRE). A major part of JRE is the Java Virtual Machine (JVM). JVM creates an
environment where Java programs interact with the hardware.
A programmer creates a Java program by writing its source code. A source code is a text file that
describes the program according to the syntax of Java and has the file name extension .java. An
executable Java program generated from a source code is called Java bytecode, and has the file
name extension .class. To generate a Java program from a source code, the machine needs an
extension of JRE called the Java Development Kit (JDK) (see Fig. 1.1).
The Java language that comes with JDK consists of two parts. The first part, called java.lang,
is an essential component of Java. The second part is a collection of source codes that can be selected
and added to the Java program being written.
To write and edit a Java source code, a text editor is needed. Some editors understand the syntax of
Java and offer a variety of assistance. Popular text editors, which can be used for editing general text,
include: vim, emacs, and sublime.
The process of generating Java bytecode from a Java source code is called compilation. A primitive
way to compile a Java source code is to execute a compilation command in a command line interface.
Modern computers usually come with command line interfaces. For example, Mac OSX has Terminal
and Windows has cmd. There are other downloadable command line interfaces. A command line
interface is a program that interacts with the user on a text screen (see Fig. 1.2). The user types,
according to the syntax of the command line interface, a character sequence representing an action
he/she wishes to take. This sequence is called a command or a command line. On the interface screen,
the characters that the user types appear (or “echo”) as they are being typed. After completing the
command, the user hits the return key. The command line interface then attempts to parse the entered

© Springer Nature Switzerland AG 2018 3


M. Ogihara, Fundamentals of Java Programming,
https://doi.org/10.1007/978-3-319-89491-1_1
4 1 “Hello, World!”

Fig. 1.1 The program JDK


layers, JVM, JRE, and JDK Source Codes & Editing Tools,
IDE JRE Application
Byte Codes
Program
JVM
Other Layer
Applications

Operating
System
Operating System
Layer

Hardware
Hardware Program
Programs Layer

Hardware

Fig. 1.2 A screen shot of


Terminal on a Mac OS X
machine. The prompt is the
percent sign followed by
one white space

command according to its syntax. If the command is syntactically correct, the interface executes the
action represented by the command. When the action occurs, some characters may appear on the
screen after the command line. If there are many such characters, the text screen scrolls down to show
however many characters will fit on the screen, starting with the most recent. If the command is not
syntactically correct, the command line interface prints an error message. To inform the user that it is
ready to accept a new command, the command line interface prints a special sequence of characters,
called prompt, e.g., the “percent” symbol % followed by one white space, or the “greater than” symbol
>. Table 1.1 is a select list of commands.
An interactive development environment (IDE) is a program that combines a program editor and a
command line interface with many additional features that make it easy to write (in particular, large)
computer programs (see Fig. 1.3). The most famous IDEs for Java are Eclipse and Netbeans.

1.1.2 Changing Folders in a Command Line Interface

A command line interface (such as the program Finder for Mac and the program Folder for Windows)
works in one specific file folder. The specific folder is called the working folder (or the working
directory). In Finder and Folder, switching to a different folder is done by clicking icons. In a
1.1 The Programming Environment for Java 5

Table 1.1 A short list of commands available in the Terminal programs for Mac OSX and Linux, as well as their
counterparts in the Windows cmd
Terminal cmd Function
(Mac OSX/Linux) (Windows)
cd FOLDER cd FOLDER Change folder to FOLDER
cd cd Change to the home folder
cd .. cd .. Change to the parent folder
pwd chdir Print the working folder
ls dir Listing of all files in the folder
ls FILE ls FILE Listing of FILE in the folder
rm FILE del FILE Remove the file FILE
rmdir FOLDER del FOLDER Remove the folder FOLDER (must be empty)
mv FILE1 FILE2 move FILE1 FILE2 Rename FILE1 to FILE2
cp FILE1 FILE2 copy FILE1 FILE2 Copy FILE1 to FILE2
mkdir FOLDER mkdir FOLDER Create the folder FOLDER
cat FILE type FILE Show the contents of FILE
more FILE more FILE Show the contents of FILE in chunks

Fig. 1.3 An IDE screen of Eclipse

command line interface, this switch is made by typing a special command. The name of the command
is cd (which stands for “change directory”). The syntax of cd is:
cd FOLDER_PATH
6 1 “Hello, World!”

Here, FOLDER_PATH specifies how to get to the target folder from the working folder. In Chap. 15,
we study the general concept of file paths.
The folder moves are composed of two basic moves: moving to one of the folders that belong to
the present folder or moving to the parent (that is, the folder that the working folder belongs to as a
subfolder). To move to a child folder, the path that is specified is this child folder’s name. To move to
the parent, the path that is specified is .. (i.e., two periods).
It is possible to combine successive folder moves into one path. For a non-Windows system like
Mac OSX and Linux, this is done by inserting / between the individual moves. For Windows, \ is the
folder separator. For example, in Mac OSX,
cd ../foo/bar
changes the working folder to the parent, to a child of the parent named foo, and then to a child of
the child named bar. bar is thus a grandchild folder of the parent of the present working folder.
To check what the working folder directly is, the command pwd can be used for a non-Windows
system, and chdir for Windows. These commands print the path to the working folder, starting from
the “home” folder on the screen. It is also possible to take the inventory of the files in the working
folder using the command ls for a non-Windows system, and dir for Windows. This command
produces a list of all the files in the working folder.

1.1.3 Source Codes, Bytecodes, and Compilation

As mentioned earlier, all Java source files must have the file name extension .java. We call them
Java files. To compile the source code Foo.java in a command line interface, one must type the
command:
javac Foo.java
If the source code compiles without error, a file named Foo.class is created. This is the bytecode
of the program. We call it a class file. If the class file already exists, then the file is overwritten
upon successful compilation. In the case of IDE, .class files are generated only during the
execution process. If Foo.java has compiled successfully, the program can be executed by using
the command:
java Foo
after the prompt.
Here is an example of a user interaction with a command line interface, where the user tries to
compile and then execute a program whose source code is HelloWorld.java (Fig. 1.4). The
prompt of the command line interface is the percent symbol followed by one white space. The first
line is the compilation command, the second line is the execution command, the third line is the result
of executing the code, and the fourth line is the command prompt after the execution.

Fig. 1.4 The compilation


and execution of
HelloWorld.java
1.2 The First Program, “Hello, World!” 7

1.2 The First Program, “Hello, World!”

Let us start writing Java programs. Our first program is the popular Hello, World! program.

1 public class HelloWorld


2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " Hello , World ! " ) ;
6 }
7 }

Listing 1.1 HelloWorld.java

Executing this program produces a single line of output:


Hello, World!

Using this code, we shall learn some important ingredients of Java programs.
The three words in the first line:
public class HelloWorld
state that:

(a) this is a program unit of type class,


(b) the unit is named HelloWorld, and
(c) the unit is accessible from all other Java program units.

There are four kinds of program units: class, interface abstract class, and enum. This
book covers class and interface only.
The keyword public specifies that the unit is accessible from other program units. A keyword
that specifies the accessibility of program units and their components is called a visibility attribute.
There are three explicit visibility types: public, private, and protected. The default visibility
type, when there is no explicit visibility attribute, is the package visibility.
The order of appearance of the three components,
VISIBILITY_TYPE UNIT_TYPE NAME
applies to all Java source code files.
Every source file in Java has the file extension .java. In a single .java file, multiple classes
can be defined, simply by concatenating their source codes. In such a case, at most one class may be
public. In addition, if a source file contains a unit with the public visibility, the name of the unit
must match the file name. For example,

1 class Foo
2 {
3 ...
4 }
5 class Bar
6 {
7 ...
8 }

is okay, but
8 1 “Hello, World!”

1 public class Foo


2 {
3 ...
4 }
5 public class Bar
6 {
7 ...
8 }

is not.

1 public class Foo


2 {
3 ...
4 }
5 class Bar
6 {
7 ...
8 }

is acceptable as well, but the source file must be Foo.java.


Let us do an experiment. If the class name is changed from HelloWorld to Hello while
preserving the file name HelloWorld.java:

1 public class Hello


2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " Hello , World ! " ) ;
6 }
7 }

attempting to compile the source code (that is, the command javac HelloWorld.java)
produces the following error message:

1 HelloWorld . java :1: error : class Hello is public , should be


2 declared in a file named Hello . java
3 public class Hello
4 {
5 ˆ
6 1 error

The first two lines of the error message state the nature of the error, which is that, to define a class by
the name of Hello, the file name must be Hello.java. The next three lines of the error message
specify the location of the error using the “caret” symbol ^. According to the marking, the error is
at the class declaration. The last line of the error message is the total number of errors found in the
source code.
If the source file name HelloWorld.java is retained but the public attribute is removed, like
this one:
1.2 The First Program, “Hello, World!” 9

1 class Hello
2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " Hello , World ! " ) ;
6 }
7 }

the code compiles, but the .class generated is Hello.class, not HelloWorld.class.

1.2.1 Methods and Their Declarations

In Java, curly brackets { } are used to enclose units, components, and code blocks. For example, the
declaration of each program unit (such as class and interface) should be followed by a matching pair
of curly bracket. Two matching pairs appear either one after the other or one inside the other; that is,
either { ... { ... } ... } or { ... } ... { ... }
For a source file to compile successfully, all of its curly brackets must have unique matching partners.
Thus, the depth of a text in a source code can be defined as the number of matching pairs enclosing
it. Multiple methods may appear in one source code.
In the source code of HelloWorld.java, the opening line public class HelloWorld
is at depth 0, public static void main( String[] args ) is at depth 1, and
System.out.println( ... ) is at depth 2. The component appearing between lines 3 and 6
is called a method.
A method has a name and defines a set of actions needs to be performed. Some methods process
information given to the in the form of parameters. Some methods report the results through the use
of return values. We cover this topic in Chap. 5.
A special kind of method is the method main. Each method main takes the form of:
public static void main( String[] args )
as its declaration. The term args appearing in the parentheses represents the sequence of characters
that the user types in the command line after the name of the program. We study args in Sect. 13.4.
Only Java classes with a method main can be executed.
The general method declaration consists of the following, where the parts in boxes are optional.

VISIBILITY static RETURN_TYPE NAME ( PARAMETERS ) THROWS

Optional Required for Required Required Required Optional


Static Methods

In the case of the method main, the attribute public states that the method is accessible from
outside, the attribute static states that the method is part of some executable program, the return
type void states that the method has no return value, and String[] args specifies that the
parameter is args and its data type is String[]. We study the meaning of square brackets in
Chap. 12. The last component is about handling errors that occur during the execution of the program.
We study this in Chap. 15.
10 1 “Hello, World!”

1.2.2 System.out.println and System.out.print

The method main has only one action:


System.out.println( "Hello, World!" );
This produces the output of Hello, World!. A sequence of characters that defines one unit of
action is called a statement.
Generally, a statement ends with a semicolon. The role of a statement is to perform a certain task.
A method can contain any number of statements, including none. The statements are executed in the
order they appear.
The period plays a special role in Java; it implies possession. System.out.println refers to a
method (by the name of println) associated with System.out, which is part of a group of virtual
hardware components named System. The siblings of System.out include: System.err, for
printing error messages, and System.in, for keyboard input.
The method println converts the data appearing inside its parentheses to a series of characters,
and then prints the series on the screen with the newline character (the equivalent of the return key) at
the end. The sequence "Hello, World!" is the thirteen character sequence:
’H’ ’e’ ’l’ ’l’ ’o’ ’,’ ’ ’ ’W’ ’o’ ’r’ ’l’ ’d’ ’!’
The double quotation mark " that surrounds the thirteen-character sequence is for marking the start
and the end of the sequence. A character sequence encased in a pair of double quotation marks is
called a String literal.
The method System.out.println automatically prints the newline character at the
end. Sometimes the attachment of the newline is not desirable, e.g., when a single line of
output is built by combining multiple outputs. The method System.out.print, a sibling of
System.out.println, is helpful in such an occasion. The method System.out.print does
the same as System.out.println, except that it does not append the newline character at the
end. Furthermore, System.out.println() has the effect of typing the return key (that is, going
to the next line without printing any other character), while System.out.print() is syntactically
incorrect because System.out.print() means “print nothing”.
If the method call is changed from System.out.println to System.out.print, how will
the output change? Here is the new code. The program has a new name HelloWorld01.

1 public class HelloWorld01


2 {
3 public static void main ( String [] args )
4 {
5 System . out . print ( " Hello , World ! " ) ;
6 }
7 }

Listing 1.2 A version of HelloWorld that uses System.out.print in place of System.out.println

The execution produces the following:


1 Hello, World!%

Listing 1.3 The result of executing HelloWorld.java

Note that the prompt % appears at the end line because of the use of System.out.print.
1.2 The First Program, “Hello, World!” 11

1.2.3 Spacing in the Source Code

In Java source code, the white space, the tab-stop, and the newline all serve as spacing characters. The
following spacing rules must be followed in Java:

• There should be some spacing between two consecutive occurrences of any of the following: type,
attribute, and name.
• Some mathematical and logical symbols run together to mean special operations. In this situation,
there should not be spacing between symbols.
• There should not be any newlines appearing inside a String literal (a character sequence within
a pair of double quotation marks).

Proper spacing makes Java source codes easy to read. For example, it is possible to write:

1 System . out . println ( " Hello , World ! "


2 )
3 ;

instead of the plain

System . out . println ( " Hello , World ! " ) ;

Although the Java compiler finds no problem in understanding this line of code, a human may find it
to be a bit difficult to parse.
It is advisable to limit the number of characters per line and work within that limit, breaking up long
lines into multiple smaller ones. The spacing, indentation, and the line width are up to the programmer.
Furthermore, indenting from the left end proportionally to the depth of code is good practice (recall
the discussion in Sect. 1.2.1). In other words, using some fixed quantity M, the code at depth D
receives an indentation of M ·D white spaces. The code in this book utilizes this scheme with M = 2.1
Most code examples that appear in this book present each curly bracket as a stand-alone in one line.

1.2.4 Commenting

It is possible to insert texts that have no relevance to how the code runs. Such texts are called
comments. Comments are free-form texts. Java compilers ignore comments when producing class
files and so they exist only in the source file. A programmer can use comments to make notes to
him or herself. For example, comments can be about the expected behavior of the program and about
the underlying algorithms. To save space, the code examples presented in this book use comments
sparingly.
Java has three kinds of comment formats.
The first kind starts with two forward slashes // appearing outside String literals. If two side-by-
side forward slashes appear outside multiple-line comments (see below) and outside String literals,
the two characters and all the characters appearing after them are treated as comments.

1 Some people use M = 4 or M = 8. The latter is equivalent to the tab-stop; i.e., a tab-stop with a depth of 1.
12 1 “Hello, World!”

Because a programmer tends to limit the number of characters per line in the source code,
the comments that start with two forward slashes are naturally suitable for short comments. For
example, in

1 System . out . println ( " Hello ! " ) ; // first line


2 System . out . println ( " How are you ! " ) ; // second line

// first line and // second line are comments.


To place longer comments, multiple consecutive lines starting with two forward slashes after some
indentation can be used, e.g.,

1 // / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
2 // This program receives two numbers from
3 // the user and prints the result of performing
4 // addition , subtraction , multiplication , and
5 // subtraction on the two .
6 // / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

are long comment lines.


There is a special way of specifying multiple-line comments. If a line starts with /* after an
indentation, then all the characters starting from the /* and ending with the next */ are comments.
Using this option, a comment can be stated as:

1 /*
2 * This program receives two numbers from
3 * the user and prints the result of performing
4 * addition , subtraction , multiplication , and
5 * subtraction on the two .
6 */

The * appearing in the middle four lines are extraneous, but programmers tend to put that character
to make the vertical array of * look like the left border of the comments.
Be mindful of the following:

• /* appearing inside a matching pair of double quotation marks behaves as part of the String
literal. The same holds for */ and //.
• All characters appearing between /* and the matching */ are comments. Therefore, /* appearing
in a matching pair of /* and */ is part of the comment represented by the pair.

This means that the code

1 public class Foo


2 {
3 public static void main ( String [] args )
4 {
5 /* here is a comment
6 /* one more comment ? */
7 */
8 System . out . println ( " /*// " ) ;
9 }
10 }

has no matching /* for the */ in Line 7.


1.2 The First Program, “Hello, World!” 13

The last kind of comment is the Javadoc. The Javadoc is a variant of the aforementioned multiple-
line comment and uses a pair of /** and */ in place of /* and */. Javadocs are for publicizing
information about methods and classes and are written using a special syntax. IDEs such as Eclipse
are capable of presenting information available through Javadocs.
The following code shows some examples of commenting.

1 /*
2 * Class for showing comment examples
3 * Written by Mitsunori Ogihara
4 */
5 public class Comments
6 {
7 /* *
8 * main method
9 * @param args the arguments
10 */
11 public static void main ( String [] args )
12 {
13 // There are two lines in the program
14 System . out . println ( " A code needs comments ! " ) ;
15 }
16 }

Listing 1.4 Examples of comments. Lines 1–4 form a multiple-line comment. Lines 7–10 form a Javadoc comment.
Line 13 is a single-line comment

1.2.5 Errors

A syntax error is a part of source code that fails to conform to the Java syntax. If a source code
contains syntax errors, the Java compiler, instead of producing the bytecode, produces an error
message stating that there are syntax errors. If there is a bytecode generated from the prior successful
compilation, that code remains the same without being updated.
The syntax error that a compiler produces is a bit cryptic and takes some experience to comprehend.
Mainly because the compiler is not aware of the true intension of the programmer who wrote the
erroneous code, the stated number of syntax errors does not necessarily agree with the actual number
of syntax errors.
Consider the following code, which is intended to execute three println statements successively.

1 // ---- This is the class name


2 public class BuggyHelloWorld
3 /----
4 // ---- Main method of the code
5 // ----
6 public static void main ( String [] args )
7 {
8 System . out . pritnln ( " Hello , World ! ) ;
9 System . out . printin ( Hello , Class ! " ) ;
10 System . out . printin ( " Hello , its ’ me ! " ) :
11 }
12 }
13 }

Listing 1.5 A buggy version of the HelloWorld program. The intended class name is BuggyHelloWorld
14 1 “Hello, World!”

There are four syntax errors in the code:

1. the forward slash in line 3 should be a double forward slash,


2. the String literal in line 7 does not have a closing double quotation mark,
3. the colon at the end of line 7 should be a semicolon, and
4. There should be one more “}” at the end.

At the compilation step, we encounter the following error messages:


1 BuggyHelloWorld.java:2: error: ’{’ expected
2 public class BuggyHelloWorld
3 ^
4 BuggyHelloWorld.java:8: error: unclosed string literal
5 System.out.pritnln( "Hello, World! );
6 ^
7 BuggyHelloWorld.java:8: error: ’;’ expected
8 System.out.pritnln( "Hello, World! );
9 ^
10 BuggyHelloWorld.java:9: error: illegal start of expression
11 System.out.printin( Hello, Class!" );
12 ^
13 BuggyHelloWorld.java:9: error: ’;’ expected
14 System.out.printin( Hello, Class!" );
15 ^
16 BuggyHelloWorld.java:9: error: ’)’ expected
17 System.out.printin( Hello, Class!" );
18 ^
19 BuggyHelloWorld.java:9: error: unclosed string literal
20 System.out.printin( Hello, Class!" );
21 ^
22 BuggyHelloWorld.java:10: error: ’;’ expected
23 System.out.printin( "Hello, its’ me!" ):
24 ^
25 BuggyHelloWorld.java:10: error: ’;’ expected
26 System.out.printin( "Hello, its’ me!" ):
27 ^
28 BuggyHelloWorld.java:13: error: class, interface, or enum expected
29 }
30 ^
31 10 errors

Each error message consists of the source file name, the line number of the error, the nature of the
error, and the actual location of the error (indicated by the caret symbol). In the case of an IDE, instead
of presenting the errors in its command line interface screen, these errors are highlighted in the source
code editor screen.
As can be seen, the number of error messages is greater than the actual number of errors. Although
the number of error messages may exceed the number of true errors, it is always the case that the very
first error message corresponds to the very first syntax error. In the above example, “illegal start of
type” pointing to /--- is a true syntax error. Fixing the very first syntax error in the source code first
is a good strategy.
There are two other types of errors: run-time errors and logic errors. Runtime errors are those
that occur during the execution of code, interrupting the execution. They often result in a premature
termination of the program. Logic errors do not necessarily result in run-time errors, but occur due to
misconception or flaws in the logic of the programmer.
1.3 Using Multiple Statements 15

1.3 Using Multiple Statements

1.3.1 System.out.println and System.out.print (Reprise)

As mentioned earlier, a method can contain multiple statements. If multiple statements appear in a
method, they act in the order of appearance. Multiple statements can be used to write a program that
executes a complex task.
Consider the following program that prints the “ABC Song”:

1 public class MultiLines


2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " A B C D E F G " ) ;
6 System . out . println ( " H I J K L M N O P " ) ;
7 System . out . println ( " Q R S and T U V " ) ;
8 System . out . println ( " W X Y and Z " ) ;
9 System . out . println ( " Now I know my A B C " ) ;
10 System . out . println ( " Won ’t you sing along with me " ) ;
11 }
12 }

Listing 1.6 A source code with multiple println statements

The program executes the six System.out.println statements from top to bottom, and
produces the following six-line output.
1 A B C D E F G
2 H I J K L M N O P
3 Q R S and T U V
4 W X Y and Z
5 Now I know my A B C
6 Won’t you sing along with me

Recall that System.out.print is the version of System.out.println without the


newline at the end.
The next code is a variant of the previous code. We have changed the first, third, and fifth
System.out.println statements to System.out.print statements.

1 public class MultiLines01


2 {
3 public static void main ( String [] args )
4 {
5 System . out . print ( " A B C D E F G " ) ;
6 System . out . println ( " H I J K L M N O P " ) ;
7 System . out . print ( " Q R S and T U V " ) ;
8 System . out . println ( " W X Y and Z " ) ;
9 System . out . print ( " Now I know my A B C " ) ;
10 System . out . println ( " Won ’t you sing along with me " ) ;
11 }
12 }

Listing 1.7 A source code with multiple print and println statements
16 1 “Hello, World!”

The result of executing the code is as follows:


1 A B C D E F GH I J K L M N O P
2 Q R S and T U VW X Y and Z
3 Now I know my A B CWon’t you sing along with me

The use of System.out.print at three places has reduced the number of output lines from six to
three. In each of the three lines, two outputs appear side-by-side with no gaps in between. Thus, to
make the connections appear correct, some characters are needed in between. The next code example
fixes this spacing issue by appending the command and the space (i.e., ", ") to the first, third, and
fifth sequences.

1 public class MultiLines02


2 {
3 public static void main ( String [] args )
4 {
5 System . out . print ( " A B C D E F G , " ) ;
6 System . out . println ( " H I J K L M N O P " ) ;
7 System . out . print ( " Q R S and T U V , " ) ;
8 System . out . println ( " W X Y and Z " ) ;
9 System . out . print ( " Now I know my A B C , " ) ;
10 System . out . println ( " Won ’t you sing along with me " ) ;
11 }
12 }

Listing 1.8 A source code with multiple print and println statements with some punctuation

The result of executing the code is as follows:


1 A B C D E F G, H I J K L M N O P
2 Q R S and T U V, W X Y and Z
3 Now I know my A B C, Won’t you sing along with me

1.3.2 Printing Multiple-Line Texts on the Screen

In a manner similar to the code for the ABC song, we can write a program that produces some
selected texts on the screen, for example, the poem “Autumn” by an American poet Henry Wadsworth
Longfellow (February 27, 1807 to March 24, 1882).
Thou comest, Autumn, heralded by the rain
With banners, by great gales incessant fanne
Brighter than brightest silks of Samarcand,
And stately oxen harnessed to thy wain!
Thou standest, like imperial Charlemagne,
Upon thy bridge of gold; thy royal hand
Outstretched with benedictions o’er the land,
Blessing the farms through all thy vast domain!
Thy shield is the red harvest moon, suspended
So ‘long’ beneath the heaven’s o’er-hanging eaves;
Thy steps are by the farmer’s prayers attended;
Like flames upon an altar shine the sheaves;
And, following thee, in thy ovation splendid,
Thine almoner, the wind, scatters the golden leaves!

The code Autumn.java that appears next produces this poem on the screen by combining
System.out.print and System.out.println statements, where each line of the poem is
split into two statements.
1.3 Using Multiple Statements 17

1 public class Autumn


2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " Autumn , by Longfellow " ) ;
6 System . out . println () ;
7 System . out . print ( " Thou comest , Autumn , " ) ;
8 System . out . println ( " heralded by the rain " ) ;
9 System . out . print ( " With banners , " ) ;
10 System . out . println ( " by great gales incessant fanne " ) ;
11 System . out . print ( " Brighter than brightest " ) ;
12 System . out . println ( " silks of Samarcand , " ) ;
13 System . out . print ( " And stately oxen " ) ;
14 System . out . println ( " harnessed to thy wain ! " ) ;
15 System . out . print ( " Thou standest , " ) ;
16 System . out . println ( " like imperial Charlemagne , " ) ;
17 System . out . print ( " Upon thy bridge of gold ; " ) ;
18 System . out . println ( " thy royal hand " ) ;
19 System . out . print ( " Outstretched with benedictions " ) ;
20 System . out . println ( " o ’ er the land , " ) ;
21 System . out . print ( " Blessing the farms through " ) ;
22 System . out . println ( " all thy vast domain ! " ) ;
23 System . out . print ( " Thy shield is the red harvest moon , " ) ;
24 System . out . println ( " suspended " ) ;
25 System . out . print ( " So long beneath the heaven ’s " ) ;
26 System . out . println ( " o ’er - hanging eaves ; " ) ;
27 System . out . print ( " Thy steps are by the farmer ’s " ) ;
28 System . out . println ( " prayers attended ; " ) ;
29 System . out . print ( " Like flames upon an altar " ) ;
30 System . out . println ( " shine the sheaves ; " ) ;
31 System . out . print ( " And , following thee , " ) ;
32 System . out . println ( " in thy ovation splendid , " ) ;
33 System . out . print ( " Thine almoner , the wind , " ) ;
34 System . out . println ( " scatters the golden leaves ! " ) ;
35 }
36 }

Listing 1.9 A source code for Autumn.java

The program produces the following output:


1
2 Thou comest, Autumn, heralded by the rain
3 With banners, by great gales incessant fanne
4 Brighter than brightest silks of Samarcand,
5 And stately oxen harnessed to thy wain!
6 Thou standest, like imperial Charlemagne,
7 Upon thy bridge of gold; thy royal hand
8 Outstretched with benedictions o’er the land,
9 Blessing the farms through all thy vast domain!
10 Thy shield is the red harvest moon, suspended
11 So long beneath the heaven’s o’er-hanging eaves;
12 Thy steps are by the farmer’s prayers attended;
13 Like flames upon an altar shine the sheaves;
14 And, following thee, in thy ovation splendid,
15 Thine almoner, the wind, scatters the golden leaves!
18 1 “Hello, World!”

1.3.3 Escaping Characters

Suppose we wish to print the following character sequence:


abc"def
To print a character sequence directly with System.out.print and System.out.println,
we attach the double quotation mark before and after the sequence. What if the sequence were
abc"def and we wrote out the statement as follows?
System.out.println( "abc"def" );
This would produce a compilation error.
The next code is one that has triple double quotation marks.
1 public class TripleQuote
2 {
3 public static void main( String[] args )
4 {
5 System.out.println( "abc"def" );
6 }
7 }

Listing 1.10 A code that attempts to use a quotation mark inside a character sequence

The compiler produces the following error messages:


1 TripleQuote.java:3: error: ’)’ expected
2 System.out.println( "abc"def" );
3 ^
4 TripleQuote.java:3: error: unclosed string literal
5 System.out.println( "abc"def" );
6 ^
7 TripleQuote.java:3: error: ’;’ expected
8 System.out.println( "abc"def" );
9 ^
10 TripleQuote.java:5: error: reached end of file while parsing
11 }
12 ^
13 4 errors

What happened during the compilation attempt? The Java compiler tried to pair the first double
quotation mark with another. It chose, however, to pair the second quotation mark with the first.
The compiler then tried to make sense of the remainder def", but it could not.
To correct this problem, we need to tell the compiler that the middle double quotation mark is not
the end marker. Attaching a backslash \ before the quotation mark accomplishes this.
"abc\"def"
With this modification, the code looks like:
1 public class TripleQuoteCorrect
2 {
3 public static void main( String[] args )
4 {
5 System.out.println( "abc\"def" );
6 }
7 }

Listing 1.11 A code that prints a quotation mark inside a character sequence
1.3 Using Multiple Statements 19

and the code generates the output as intended:

abc " def

We call the action of attaching the backslash to relieve a symbol of its regular duties escaping.
With escaping, we can insert a newline character using the combination \n. To include a tab-stop
character, we can use \t instead of using of the actual tab-stop. The benefit of using the \t is that the
character is visible; if we use the tab-stop character as it is, it is difficult to tell later whether a gap we
see is indeed a tab-stop or just a series of the white space.
Finally, to escape the backslash character, we use the double backslash \\.
Assuming that the tab-stop positions of a terminal program are at every eighth position starting
from the left end, the statement:
System.out.println( "abcdefgh\n\"\\i\tj\nk" );
produces the following output:
1 abcdefgh
2 "\i j
3 k

We can use escaping to print texts with quotation marks and backward slashes. Listing 1.12 is a
program that prints a quotation from Mark Twain’s Adventures of Huckleberry Finn. In one line of
the quote, the addition of System.out.println and the indentation makes the line too long to
fit in the width of 72 characters. To solve this issue, we split the line into two: the first half with
System.out.print and the second half with System.out.println (Lines 17 and 18).

1 public class HuckleberryFinn


2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " \\ Quoted from Huckleberry Finn \\ " ) ;
6 System . out . println ( " I broke in and says : " ) ;
7 System . out . println ( " \" They ’ re in an awful peck of trouble , and \" " ) ;
8 System . out . println ( " \" Who is ?\" " ) ;
9 System . out . println ( " \" Why , pap and mam and sis and Miss Hooker ; " ) ;
10 System . out . println ( " \ tand if you ’d take your ferryboat and go up
there \" " ) ;
11 System . out . println ( " \" Up where ? Where are they ?\" " ) ;
12 System . out . println ( " \" On the wreck .\" " ) ;
13 System . out . println ( " \" What wreck ?\" " ) ;
14 System . out . println ( " \" Why , there ain ’t but one .\" " ) ;
15 System . out . println ( " \" What , you don ’t mean the Walter Scott ?\" " ) ;
16 System . out . println ( " \" Yes .\" " ) ;
17 System . out . print ( " \" Good land ! what are they doin ’ there , " ) ;
18 System . out . println ( " for gracious sakes ?\" " ) ;
19 System . out . println ( " \" Well , they didn ’t go there a - purpose .\" " ) ;
20 }
21 }

Listing 1.12 A program that prints a quotation from Mark Twain’s Adventures of Huckleberry Finn

Executing the code produces the following output.


20 1 “Hello, World!”

1 \Quoted from Huckleberry Finn\


2 I broke in and says:
3 "They’re in an awful peck of trouble, and"
4 "Who is?"
5 "Why, pap and mam and sis and Miss Hooker;
6 and if you’d take your ferryboat and go up there"
7 "Up where? Where are they?"
8 "On the wreck."
9 "What wreck?"
10 "Why, there ain’t but one."
11 "What, you don’t mean the Walter Scott?"
12 "Yes."
13 "Good land! what are they doin’ there, for gracious sakes?"
14 "Well, they didn’t go there a-purpose."

Using \n as the newline, we can print multiple short lines into single statements, as shown in
List 1.13. Note that most of the lines contain \n in the character sequence that needs to be printed.

1 public class HuckleberryFinn01


2 {
3 public static void main ( String [] args )
4 {
5 System . out . print ( " \\ Quoted from Huckleberry Finn \\\ n " ) ;
6 System . out . print ( " I broke in and says :\ n \" They ’ re in " ) ;
7 System . out . print ( " an awful peck of trouble , and \"\ n " ) ;
8 System . out . print ( " \" Who is ?\"\ n \" Why , pap and mam and " ) ;
9 System . out . print ( " sis and Miss Hooker ;\ n \ tand if you ’d " ) ;
10 System . out . print ( " take your ferryboat and go up there \" " ) ;
11 System . out . print ( " \ n \" Up where ? Where are they ?\"\ n " ) ;
12 System . out . print ( " \" On the wreck .\"\ n \" What wreck ?\"\ n " ) ;
13 System . out . print ( " \" Why , there ain ’t but one .\"\ n " ) ;
14 System . out . print ( " \" What , you don ’t mean the Walter " ) ;
15 System . out . print ( " Scott ?\"\ n \" Yes .\"\ n \" Good land ! " ) ;
16 System . out . print ( " what are they doin ’ there , for " ) ;
17 System . out . print ( " gracious sakes ?\"\ n \" Well , they " ) ;
18 System . out . print ( " didn ’t go there a - purpose .\"\ n " ) ;
19 }
20 }

Listing 1.13 A program that uses squeezed print statements to produce the same quotation from Mark Twain’s
Adventures of Huckleberry Finn as before

The execution produces exactly the same result as before.


Java uses many symbol sequences, including escaping. Table 1.2 summarizes all such symbol
sequences.

1.3.4 Printing Shapes

Previously, we used multiple System.out.println statements to produce multiple-line texts on


the terminal screen. Expanding on the idea, now we write Java programs that print shapes on the
terminal screen.
1.3 Using Multiple Statements 21

Table 1.2 The list of [] Arrays () Parameters


meaningful symbols in
{} Code block <> Type parameter
Java
. Class membership = Assignment
; Statement separator , Parameter separator
? If-then-else value selection : Case presentation
+ Addition/concatenation - Subtraction, negative sign
* Multiplication / Quotient
% Remainder, format type parameter
++ Increment - Decrement
+= Direct addition -= Direct subtraction
*= Direct multiplication /= Direct quotient
%= Direct remainder
== Equality != Inequality
> Greater than < Smaller than
>= Greater than or equal to >= Smaller than or equal to
&& Logical AND || Logical OR
! Negation
« Signed left shift » Signed right shift
«< Unsigned left shift »> Unsigned right shift
& Bit-wise AND | Bit-wise OR
^ Bit-wise XOR
&= Direct bit-wise AND |= Direct bit-wise OR
^= Direct bit-wise XOR
@ Javadoc keyword // Line comment
/* Multiple-line comment start /** Javadoc start
*/ Multiple-line comment/Java end
\ Escape \\ Backslash character
\n The newline character \t The tab-stop character
\’ Single quote in a char literal %% the % Character in format strings
%n The newline character in format strings

Suppose we want to print the figure of a right-angled triangle like the one appears next:
1 /|
2 / |
3 / |
4 / |
5 / |
6 / |
7 /______|

In the drawing, we use the forward slash / for the left side of the triangle, the vertical | for the right
side of the triangle, and the underscore _ for the bottom side.
22 1 “Hello, World!”

The following code will do the job:

1 // -- print a triangle
2 public class Triangle
3 {
4 public static void main ( String [] args )
5 {
6 System . out . println ( " /| " ) ;
7 System . out . println ( " / |" );
8 System . out . println ( " / |" );
9 System . out . println ( " / |" );
10 System . out . println ( " / |" );
11 System . out . println ( " / |" );
12 System . out . println ( " / ______ | " ) ;
13 }
14 }

Listing 1.14 The code for producing a right-angled triangle

How about an isosceles triangle, like this one?


1 /\
2 / \
3 / \
4 / \
5 / \
6 / \
7 /____________\

Using the \ for the right edge, we come up with the following code:

1 // -- print an isosceles
2 public class Isosceles
3 {
4 // -- main method
5 public static void main ( String [] args )
6 {
7 System . out . println ( " /\\ " ) ; // line 1
8 System . out . println ( " / \\ " ) ; // line 2
9 System . out . println ( " / \\ " ) ; // line 3
10 System . out . println ( " / \\ " ) ; // line 4
11 System . out . println ( " / \\ " ) ; // line 5
12 System . out . println ( " / \\ " ) ; // line 6
13 System . out . println ( " / ____________ \\ " ) ; // line 7
14 }
15 }

Listing 1.15 A code for printing on the screen an isosceles triangle

Let’s try printing an isosceles upside down, as shown next:


1 \------------/
2 \ /
3 \ /
4 \ /
5 \ /
6 \ /
7 \/
Summary 23

The shape looks a bit unwieldy, since we are using the dash to draw the top line. The triangle will
look better if we draw the top line using an over-line bar character, but unfortunately, such a character
does not exist in our standard character set, so the dash is our only option.

1 // -- print an isosceles upside down


2 public class U p s i d e D o w n I s o s c e l e s C o r r e c t
3 {
4 // -- main method
5 public static void main ( String [] args )
6 {
7 System . out . println ( " \\ - - - - - - - - - - - -/ " ) ; // line 7
8 System . out . println ( " \\ / " ) ; // line 6
9 System . out . println ( " \\ / " ) ; // line 5
10 System . out . println ( " \\ / " ) ; // line 4
11 System . out . println ( " \\ / " ) ; // line 3
12 System . out . println ( " \\ / " ) ; // line 2
13 System . out . println ( " \\/ " ) ; // line 1
14 }
15 }

Listing 1.16 The code for producing an upside-down isosceles triangle on the screen

Try writing programs that draw other interesting shapes!

Summary

A command line interface is an environment in which the user, through typing commands after a
prompt, interacts with the system.
In command line interfaces and programming environments, there exists a “working folder”.
The standard header of a Java class is public class CLASS_NAME. Its file name should be
CLASS_NAME.java.
An executable Java class has public static void main( String[] arg ).
To compile a Java program, use the command javac CLASS_NAME.java.
The Java compiler may produce compilation errors due to syntax errors.
The command to use when executing a Java bytecode by the name of CLASS_NAME is
java CLASS_NAME.
A code that compiles may produce terminating errors. Such terminating errors are called run-time
errors.
A code that compiles and is free of run-time errors may still not run correctly. Logical errors are
the culprits.
Java programs use pairs of curly braces to define code blocks.
Unless they are appearing in the source code for an object class, methods need to have the static
attribute.
Methods and classes may have a visibility attribute.
Method declarations must have both a return value specification and a parameter specification.
In a method, multiple statements may appear. Each statement ends with a semicolon.
System.out.println is a method that produces the value of its parameter on the screen and
then prints a newline.
System.out.print is a method that produces the value of its parameter on the screen.
24 1 “Hello, World!”

To print the double quotation mark, the escape sequence of \" is used.
To print the backslash as a character, the escape sequence of \\ is used.
There are three types of comments: single line comments, multiple-line comments, and Javadocs.

Exercises

1. Terminology Answer the following questions:


(a) What is the formal name of the process for creating an executable Java code from a .java file?
What about the command used in the Unix environment for creating such an executable code?
(b) What is the file extension of a Java byte code?
(c) What is the command used for executing a Java byte code?
(d) In a .java file two words usually appear before its class name. What are they?
(e) What are the three words that precede the main method in a .java file?
(f) State the differences between System .out.print and System.out.println.
(g) What are the three categories of errors in programming?
(h) In String literals, what sequences of characters must you use to print the double quote, the
backslash, and the newline?
2. Main Declaration Of the following possible declarations for the method main, which ones
will compile?
(a) public static void main( String[] args )
(b) static void main( String[] args )
(c) public static main( String[] args )
(d) public static void( String[] args )
(e) public static void main( )
(f) public static void main( String[] )
(g) public static void main( args )
3. Fixing errors The following code contains some errors and will not compile. State what we
must fix so that it will compile.

1 public class MyBuggyProgram {


2 public static main ( [] String args )
3 [
4 System . out . prink ( ’ Hello ! ’ ) :
5 ]
6 }

4. Escaping Which of the following require a backslash when being included in a String literal
(i.e., a series of characters flanked by a pair of double quotation marks)?
• A
• /
(i.e., the forward slash)
• \
(i.e, the backslash)
• "
• %
(i.e., the percentage symbol)
• @
(i.e., the at sign)
Exercises 25

Programming Projects
5. Alma Mater Write a program named AlmaMater that upon execution prints the Alma Mater
of your school. For the University of Miami, the output of the program should look like:
1 UM ALMA MATER
2
3 Southern suns and sky blue water,
4 Smile upon you Alma mater;
5 Mistress of this fruitful land,
6 With all knowledge at your hand,
7 Always just to honor true,
8 All our love we pledge to you.
9 Alma Mater, stand forever
10 On Biscayne’s wondrous shore.

6. Printing a Diamond Write a program named Diamond.java that prints the shape of a
diamond of height 10 and width 10 as shown:
1 /\
2 / \
3 / \
4 / \
5 / \
6 \ /
7 \ /
8 \ /
9 \ /
10 \/

7. Printing a Filled Diamond Write a program named DiamondFilled.java that prints the
shape of a diamond of height 10 and width 10 with the white space filled with forward slashes on
the left-hand side and backward slashes on the right-hand side, as shown:
1 /\
2 //\\
3 ///\\\
4 ////\\\\
5 /////\\\\\
6 \\\\\/////
7 \\\\////
8 \\\///
9 \\//
10 \/

8. Printing an X with ’X’


Write a program, XwithXs, that produces the following shape on the screen:
1 X X
2 X X
3 X X
4 X X
5 X
6 X X
7 X X
8 X X
9 X X

9. Cascaded printing Write a program, CascadedChildren, that prints the first two verses of
“Children” by Henry Wadsworth Longfellow with increasing indentations:
26 1 “Hello, World!”

1 Come to me, O ye children!


2 For I hear you at your play,
3 And the questions that perplexed me
4 Have vanished quite away.
5
6 Ye open the eastern windows,
7 That look towards the sun,
8 Where thoughts are singing swallows
9 And the brooks of morning run.

10. Slashes Write a program, Slashes, that produces the following shape on the screen:
1 / / / / / / / / / / / /
2 / / / / / / / / / / /
3 / / / / / / / / / / / /
4 / / / / / / / / / / /
5 / / / / / / / / / / / /
6 / / / / / / / / / / /
7 / / / / / / / / / / / /
8 / / / / / / / / / / /
9 / / / / / / / / / / / /
10 / / / / / / / / / / /

11. Backlashes Write a program, BackSlashes, that produces the following shape on the screen:
1 \ \ \ \ \ \ \ \ \ \ \ \
2 \ \ \ \ \ \ \ \ \ \ \
3 \ \ \ \ \ \ \ \ \ \ \ \
4 \ \ \ \ \ \ \ \ \ \ \
5 \ \ \ \ \ \ \ \ \ \ \ \
6 \ \ \ \ \ \ \ \ \ \ \
7 \ \ \ \ \ \ \ \ \ \ \ \
8 \ \ \ \ \ \ \ \ \ \ \
9 \ \ \ \ \ \ \ \ \ \ \ \
10 \ \ \ \ \ \ \ \ \ \ \

12. Tabstop You can use the tab-stop character \t to line things up (to improve the readability of
the text output). Consider the following code:
1 public class TestTabStop
2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " Abbie Zuckerman 23 yrs Soccer " ) ;
6 System . out . println ( " Brittany Ying 21 yrs Swimming " ) ;
7 System . out . println ( " Caty Xenakis 22 yrs Softball " ) ;
8 System . out . println ( " Dee Wick 20 yrs Basketball " ) ;
9 System . out . println ( " Eva Venera 19 yrs Polo " ) ;
10 }
11 }

The code produces the following output:


1 Abbie Zuckerman 23yrs Soccer
2 Brittany Ying 21yrs Swimming
3 Caty Xenakis 22yrs Softball
4 Dee Wick 20yrs Basketball
5 Eva Venera 19yrs Polo
Exercises 27

Revise the program so that it uses the same code, but replaces the whitespace (inside each pair
of double quotation marks) with the tab-stop. Run the program to see how it changes the way the
information appears on the screen.
13. Self introduction Write a program named SelfIntro that introduces yourself as follows:
1 My name is NAME.
2 I was born in PLACE.
3 My favorite television program is PROGRAM.
4 I woke up at HOUR:MINUTE today.
5 I own NUMBER books.
6 My target grade point average is GPA.

The uppercase words NAME, PLACE, PROGRAM, HOUR, MINUTE, NUMBER, and GPA, are
placeholders, so you must substitute them with appropriate text. PROGRAM must appear with
double quotation marks. For example,
1 My name is Mitsu Ogihara.
2 I was born in Japan.
3 My favorite television program is "Parks and Recreation".
4 I woke up at 6:30 today.
5 I own 1000 books.
6 My target grade point average is 4.0.
Using Data for Computation
2

2.1 Data

2.1.1 Data and Their Taxonomy

The previous chapter presented how to write programs using only System.out.println and
System.out.print statements. This chapter introduces how to store, modify, and retrieve
information. The medium in which information is stored is called data.1
In Java, every data has its type, which specifies how the data encodes its information, as well as
what operations can be performed on the data. There are two broad classifications of data types in
Java: primitive data types and object data types.
A primitive data type is one that uses only a predetermined number of bits in representation, where
a bit is the fundamental unit of information and has two possible values (0 and 1). There are eight
primitive data types: boolean for the logical values, char for the characters, byte, short, int,
and long for whole numbers of various capacities, and float and double for real numbers of
various capacities.
On the other hand, an object data type is a custom-designed data type. A programmer designs a
new object data type by putting together existing data types and defining the permissible operations
for acting on the information stored. Some object data types require an indefinite number of bits for
representation.
In addition to the major difference between primitive and object data types, the following
distinctions can be made among data.

1. There are data with names referencing and data without these names.
(a) The former kind is a variable. A special variable is one whose value cannot be changed during
the course of program. Such a variable is called a constant
(b) The latter kind consists of literals and return values. A literal is a data whose value is exactly
specified. A return value is a value that a method returns.

1 The term data is used for both singular and plural forms. The original singular form of “data” is “datum”, but this is
rarely used nowadays.

© Springer Nature Switzerland AG 2018 29


M. Ogihara, Fundamentals of Java Programming,
https://doi.org/10.1007/978-3-319-89491-1_2
30 2 Using Data for Computation

2. Some variables and constants are accessible only inside the method in which they appear; others
are accessible from everywhere in the class. The former ones are local, and the latter ones are
global.
(a) Some global variables in an object class play the role of storing information for individual
objects of the class. Those variables are instance variables (or field variables).
(b) Each global constant, as well as each instance variable, has a specific visibility type (public,
private, protected, and package).

2.1.2 Number Literals

The sequence "Hello, World!" is a literal of the data type String. Literals are available not
only for String but also for all the primitive data types.
The following is an example of a code using literals:

1 public class Literals


2 {
3 public static void main ( String [] args )
4 {
5 System . out . print ( " Rank number " ) ;
6 System . out . print ( 1 ) ;
7 System . out . print ( " in my all - time favorite NFL QB list is " ) ;
8 System . out . print ( " Steve Young " ) ;
9 System . out . println ( " . " ) ;
10 System . out . print ( " His overall quarterback rating is " ) ;
11 System . out . print ( 96.8 ) ;
12 System . out . println ( " . " ) ;
13 }
14 }

Listing 2.1 A program that produces a comment about an NFL quarterback

In Lines 5, 7–9, and 12, String literals appear inside the parentheses. In Lines 6 and 11, literals
1 and 96.8 appear inside the parentheses. These are number literals (an int literal and a double
literal, to be precise).
When this program runs, System.out.print converts these two numbers to character
sequences, then prints those sequences on the screen.

1 Rank number 1 in my all-time favorite NFL quarterbacks is Steve Young.


2 His overall quarterback rating is 96.8.

By adding the same sequence of statements for two more quarterbacks, the following program is
obtained.
2.1 Data 31

1 public class Literals01


2 {
3 public static void main ( String [] args )
4 {
5 System . out . print ( " Rank number " ) ;
6 System . out . print ( 1 ) ;
7 System . out . print ( " in my all - time favorite NFL QB list is " ) ;
8 System . out . print ( " Steve Young " ) ;
9 System . out . println ( " . " ) ;
10 System . out . print ( " His overall QB rating is " ) ;
11 System . out . print ( 96.8 ) ;
12 System . out . println ( " . " ) ;
13

Listing 2.2 A program that produces comments about three NFL quarterbacks (part 1). The program header and the
part that produces comments about the first player

For these additional two players, number literals appear in Lines 15, 20, 24 and 29.

14 System . out . print ( " Rank number " ) ;


15 System . out . print ( 2 ) ;
16 System . out . print ( " in my all - time favorite NFL QB list is " ) ;
17 System . out . print ( " Peyton Manning " ) ;
18 System . out . println ( " . " ) ;
19 System . out . print ( " His overall QB rating is " ) ;
20 System . out . print ( 96.5 ) ;
21 System . out . println ( " . " ) ;
22
23 System . out . print ( " Rank number " ) ;
24 System . out . print ( 3 ) ;
25 System . out . print ( " in my all - time favorite NFL QB list is " ) ;
26 System . out . print ( " Tom Brady " ) ;
27 System . out . println ( " . " ) ;
28 System . out . print ( " His overall QB rating is " ) ;
29 System . out . print ( 97.0 ) ;
30 System . out . println ( " . " ) ;
31 }
32 }

Listing 2.3 A program that produces comments about three NFL quarterbacks (part 2). The part that produces
comments about the second and the third players

The program produces the following output2 :


1 Rank number 1 in my all-time favorite NFL quarterbacks is Steve Young.
2 His overall quarterback rating is 96.8.
3 Rank number 2 in my all-time favorite NFL quarterbacks is Peyton Manning.
4 His overall quarterback rating is 96.5.
5 Rank number 3 in my all-time favorite NFL quarterbacks is Tom Brady.
6 His overall quarterback rating is 97.0.

2 Jon Steven “Steve” Young (born October 11, 1961) is a former NFL quarterback and a sportscaster. He played 13
seasons with the San Francisco 49ers, and led the team to three Super Bowl wins. Peyton Williams Manning (born March
24, 1976) is a former NFL quarterback who played with the Indianapolis Colts and later with the Denver Broncos. He
led each team to one Super Bowl win. Thomas Edward Patrick Brady Jr. (born August 3, 1977) is an NFL quarterback
for the New England Patriots. He led the team to five Super Bowl wins.
32 2 Using Data for Computation

2.1.3 Variable Declarations

A variable is a type of data with a reference name. Simply by putting its name in the code, the value
of the data in that specific moment can be looked up.
Since each data has a unique type, a variable is specified with its name and its type. This is called
a declaration. A declaration takes the following form:
DATA_TYPE VARIABLE_NAME;
Remember that the tab-stop can be used in place of the white space, and adding more tab-stops or
white space after that is possible as well.
One example is the following:
1 public static ...
2 {
3 ...
4 int myInteger ;
5 ...
6 }

Here, int is the data type and myInteger is the name of the data. Notice the semicolon ;
appearing at the end. Each line of local/global variable/constant declarations requires a semicolon at
the end. The above is an instance in which the variable is a local variable. A local variable belongs to
a method and its declaration appears inside the method that it belongs to. The “locality” of variables
becomes important when multiple methods are written in a source code.
To declare a global variable, its declaration is placed outside the methods, at depth 1. For example,
the following declares a global variable named myInteger of data type int.
1 static int myInteger ;
2
3 public static ...
4 {
5 ...
6 }

The attachment of static is required for the declaration of a global variable.


It is possible to join declarations of multiple variables of the same type in one line via separating
the names with commas, as shown next:

int oneInteger , anotherInteger , y etAnotherInteger ;

Here, oneInteger, anotherInteger, and yetAnotherInteger are all of the int data
type. This single-line declaration is equivalent to:

1 int oneInteger ;
2 int anotherInteger ;
3 int yetAnotherInteger ;

To name a variable, a sequence of contiguous characters chosen from the alphabet, numerals, the
underscore _, and the dollar sign $ must be used. In addition, the first character of the sequence
must be a letter of the alphabet.3 Thus, according to this rule, 55 cannot be a variable name. The

3 Technically,
a variable name can start with the underscore or the dollar sign, but the convention is to start a variable
name with a lowercase letter.
2.1 Data 33

variable names, method names, and class names are all case-sensitive. The following conventions are
generally used:

• The name of a variable must start with a lowercase letter.


• The name of a constant must contain no lowercase letter.
• The name of a class must start with an uppercase letter.

2.1.4 Assigning Values to Variables

As mentioned earlier, variables (or constants) are places where information is stored. The action of
giving a value to a variable/constant is called an assignment.
The syntax for an assignment is:
VARIABLE = VALUE;

Here, the equal sign = appearing in the middle symbolizes the assignment. The left-hand side of the
assignment, VARIABLE, is the name of the variable in which a value is to be stored. The right-hand
side of an assignment, VALUE, is the value being stored. JVM can interpret this as a data having the
same type as the variable. The value in an assignment can be:

• a literal of the same type;


• a variable of the same type;
• a call to a method that returns with data of the same type; or
• a formula of the same type.

Next is an example of assigning a value to a variable:

1 int myInteger ;
2 myInteger = 55;

The first line here is a variable declaration. The type of the data is int and the name of the data is
myInteger. The second line is an assignment. The right-hand side of the assignment is an int
literal with the value of 55. This action stores the value of 55 into the variable myInteger.
It is possible to combine a declaration of a variable and an initial value assignment to the variable
all in a single statement, like this one:

int myInteger = 55;

It is also possible to combine multiple declarations and assignments of multiple variables in one line,
so long as they all have the same type. The following is an example of such combinations:

int oneInteger = 17 , anotherInteger , yetAnotherInteger = 23;

This single line of code declares int variables, oneInteger, anotherInteger, and
yetAnotherInteger, and assigns the value of 17 to oneInteger and the value of 23 to
yetAnotherInteger (note that 17 and 23 are literals).
Here, anotherInteger does not have an assignment. Does it have a value? Yes, the default
value of a variable of a primitive number type immediately after declaration is 0.
34 2 Using Data for Computation

This one-line code is equivalent to:

1 int oneInteger , anotherInteger , y etAnotherInteger ;


2 oneInteger = 17;
3 yetAnotherInteger = 23;

as well as to:

1 int oneInteger , anotherInteger , y etAnotherInteger ;


2 oneInteger = 17 , yetAnotherInteger = 23;

For the code to compile, the value assigned to a variable must match the data type of the variable.
In the above code fragment, an attempt to assign numbers with a decimal point,

1 int oneInteger , anotherInteger , y etAnotherInteger ;


2 oneInteger = 17.5;
3 yetAnotherInteger = 23.0;

results in a syntax error, because neither 17.5 nor 23.0 are integers.

The Attribute final


By attaching final in front of the data type specification in a variable declaration, any future value
assignments to the variable are prohibited. Thus, by the attachment of final, a variable becomes a
constant.

1 static final int YOUR_INTEGER = 20;


2
3 public static void main ( String [] args )
4 {
5 final int MY_NUMBER = 17;
6 ...
7 }

The first variable, YOUR_INTEGER, is a global constant and the second variable, MY_NUMBER, is
a local constant. Java requires that a value must be assigned to a constant using a combined declaration
and assignment. Therefore, in the above code example, splitting the declaration and assignment of
either constant into a standalone declaration and a standalone assignment is rejected as a syntax error.
A global constant may have an explicit visibility specification. As mentioned in Chap. 1, there are
three explicit visibility specifications: public, private, and protected. In the source code:

1 public class PubConstEx


2 {
3 public static final int COMMONINTEGER = 20;
4
5 public static void main ( String [] args )
6 {
7 final int MY_NUMBER = 17;
8 ...
9 }
10 }
2.2 The Primitive Data Types 35

COMMONINTEGER is a global constant accessible from outside and MY_NUMBER is declared


to be a local constant. By combining the class name and the global variable name, as in
PubConstEx.COMMONINTEGER, the value 20 can be accessed from other source codes.

Reassignment
If a variable is not a constant, the value of the variable can be updated any number of times. Consider
the next code:

1 int myInteger ;
2 myInteger = 63;
3 ...
4 myInteger = 97;
5 ...
6 myInteger = 20;

The dotted parts represent some arbitrary code. Assuming that no assignments to myInteger appear
in the dotted part, the value of myInteger changes from 63 to 97 in Line 4 and from 97 to 20 in
Line 6.

2.2 The Primitive Data Types

Java has eight primitive data types. They are boolean, byte, short, int, long, float, double, and char.
Table 2.1 shows the range of possible values for each type.

boolean
The boolean is a data type for storing a logical value. There are only two possible values for a
boolean data type: true and false. Here is an example of declaring boolean variables and
assigning values to them.

1 boolean logicA , logicB , logicC ;


2 logicA = true ;
3 logicB = false ;

Table 2.1 The primitive data type


Type No. bits Data representation
boolean 1 Logical value, true or false
byte 8 Integer, [−128, 127]
short 16 Integer, [−32,768, 32,767]
int 32 Integer, [−2,147,483,648, 2,147,483,647]
long 64 Integer, [−9,223,372,036,854,775,808, 9,223,372,036,854,775,807]
float 32 Floating point number, approximately
from 1.4013 · 10−45 to 3.4028 · 10+38 (positive or negative)
double 64 Floating point number, approximately
from 4.9407 · 10−324 to 1.7977 · 10+308 (positive or negative)
char 16 UNICODE character, [0, 65,535]
(unsigned)
36 2 Using Data for Computation

There are three operators available for boolean: the negation !, the conjunction &&, and the
disjunction ||. The boolean data type will be discussed in Chap. 6.

byte
The data type byte consists of eight bits, so there are 28 = 256 possible values. The value range
of byte is between −27 = −128 and 27 − 1 = 127. The hexadecimal encoding is an encoding
that is often used for specifying a byte literal. This is the encoding that divides the bits into groups
of four and uses a unique character to represent each of the 16 possible values for each group. The
value range of four bits is between 0 and 15, so naturally the numerals 0 through 9 are used for
representing numbers 0 through 9. For the numbers 10 through 15, the letters a through f (or their
upper case letters A through F) are used. In hexadecimal encoding, a byte must be represented with
two characters. The combination YZ represents

The number Y represents multiplied by 16, plus the number Z represents.

Thus, “5f” in hexadecimal is not 65 (= 5 ∗ 10 + 15) but 95 (= 16 ∗ 5 + 5) and “dc” in hexadecimal


is 220 in decimal (= 13∗16+12). Hexadecimal encoding makes it possible to represent bit sequences
compactly: four characters for sixteen bits, eight characters for 32 bits, and sixteen characters for 64
bits. In hexadecimal encoding, to indicate that a literal is presented, the prefix 0x must be attached.
For example, 0x33 is 33 in hexadecimal, which is equal to 51 in decimal.

byte myByteValue = 0 x3f ;

short
The data type short consists of sixteen bits. It has 65,536 possible values. The value range is
between −215 = −32,768 and 215 − 1 = 32,767.

int
int is a data type that consists of 32 bits. It has 4,294,967,296 possible values. The value range is
between −231 = −2,147,483,648 and 231 − 1 = 2,147,483,647. The default data type of a whole
number literal is int.

long
The data type long consists of 64 bits. It has 18,446,744,073,709,551,616 possible values. The value
range is between −263 = −9,223,372,036,854,775,808 and 263 − 1 = 9,223,372,036,854,775,807.
When presenting a literal in long, if the value that the literal represents goes beyond the range of
int, the letter L must be attached as a suffix at the end of the number sequence, like this one:

long myLongNumber = 1234567890987654321 L;

float and double


float and double are data types for real numbers. They use floating point representations.
Basically, a floating point representation divides the available bits into three parts: the sign, the
significand, and the exponent. Let S be the sign (+1 or −1). The number of bits for the sign is one,
and the bit is at the highest position of the bits allocated for the data type. The bits of the significand
represent a number between 0 and 1. If that part has m bits and the bit sequence is b1 · · · bm , that part
represents the sum of all 2−i such that bi = 1. Let C be this fractional number. Each floating point
2.3 Using Variables for Computation 37

encoding system uses a fixed “base” for exponentiation, which is either 2 or 10. Let B be this base. If
there are n bits in the exponent, that part encodes a number between −2n−1 and 2n−1 − 1 (for whole
number types). Let E be this number. Now, the bits of the floating number altogether represent

S · (1 + C) · B E .

To designate that a floating point number literal is a float, the letter F must be attached as a suffix.
Here is an example of declaring and assigning a literal value to one variable for each primitive
number type:

1 byte myByte ;
2 short myShort ;
3 int myInt ;
4 long myLong ;
5 float myFloat ;
6 double myDouble ;
7 myByte = 0 x3d ;
8 myShort = 1345;
9 myInt = 90909;
10 myLong = 1234567890123456789 L ;
11 myFloat = -3.145 F ;
12 myDouble = 1.7320504;

The numbers appearing after ’=’ in lines 7–12 are all literals.

char
The last primitive data type is char. The representation of char requires sixteen bits. By attaching
the apostrophe before and after of a character, a char literal is specified, as in ’A’ and ’x’.

1 char myChar1 = ’A ’;
2 char myChar2 = ’x ’;

The default value of a char type variable is \0. This is the character corresponding to the number
0. This must not be confused this with the numeral 0. There is no direct arithmetic operation that can
be applied to char data for producing another char, but if a char data appears in a mathematical
formula, it acts as if it were an int. Since the single quotation mark is used for a char literal, to
specify the single quotation mark itself as a char literal, attaching a backslash as is must be done to
represent the double quotation mark in String literals; that is, ’\” represents the single quotation
mark. Because of this special use of backslash, two backslashes are used to mean the backslash itself
as a literal, as in ’\\’. The other escape sequences, ’\t’ and ’\n’, are valid for char literals too.

2.3 Using Variables for Computation

2.3.1 Quarterbacks Program (Reprise)

Using the fact that reassignments of values can be made to non-final variables, the previous three-
favorite-quarterback program can be rewritten using three variables:
• an int variable, rank, for specifying the rank in the list
• a String variable, name, for the name of the quarterback, and
• a double variable, qbr, for the quarterback rating.
38 2 Using Data for Computation

1 public class Literals02


2 {
3 public static void main ( String [] args )
4 {
5 int rank ;
6 String name ;
7 double qbr ;
8
9 rank = 1;
10 name = " Steve Young " ;
11 qbr = 96.8;
12 System . out . print ( " Rank number " ) ;
13 System . out . print ( rank ) ;
14 System . out . print ( " in my all - time favorite NFL QB list is " ) ;
15 System . out . print ( name ) ;
16 System . out . println ( " . " ) ;
17 System . out . print ( " His overall QB rating is " ) ;
18 System . out . print ( qbr ) ;
19 System . out . println ( " . " ) ;
20

Listing 2.4 A program that produces comments about three NFL quarterbacks using variables (part 1). The variable
declarations and the part that produced the comments about the first player

Note that the variable declarations appear in Lines 4, 5, and 7. The variable declarations are
followed by three blocks of the same format, each consisting of eleven lines. The first lines of each
block assign values to the variables. For example, the first lines of the first block are:

1 rank = 1;
2 name = " Steve Young " ;
3 qbr = 96.8;

The next eight lines of code make the presentation, with the three literals for rank, name, and rating
substituted with their respective names.
1 ...
2 System.out.print( rank );
3 ...
4 System.out.print( name );
5 ...
6 ...
7 System.out.print( qbr );
8 ...

In these three lines, the values of these variables substitute their respective locations into the print
statements. Note that the action order is:
declaration → assignment → reference
Since assignments can be made multiple times to non-final variables, a variable declaration is
effective until the end of the innermost pair of curly brackets that contains it. This means that two
declarations of the same variables cannot intersect. In the above program, the innermost matching
pair containing a variable declaration appears at Lines 4 and 44. Thus, the declarations are valid until
Line 44. Formally, the range of lines in which a variable declaration is valid is called the scope of the
variable.
Exploring the Variety of Random
Documents with Different Content
trusted helper of the Apostle. He was with Paul in the latter part of
the third missionary tour—so we learn from the Corinthian letters—
and therefore probably in the earlier part of the same journey, when
the Apostle paid his second visit to Galatia. He belonged to the
heathen mission, and was Paul's "true child after a common faith"
(Tit. i. 4), an uncircumcised man, of Gentile birth equally with the
Galatians. And now they read of his "going up to Jerusalem with
Paul," to the mother-city of believers, where are the pillars of the
Church—the Jewish teachers would say—the true Apostles of Jesus,
where His doctrine is preached in its purity, and where every
Christian is circumcised and keeps the Law. Titus, the unclean
Gentile, at Jerusalem! How could he be admitted or tolerated there,
in the fellowship of the first disciples of the Lord? This question
Paul's readers, after what they had heard from the Circumcisionists,
would be sure to ask. He will answer it directly.
But the Apostle goes on to say, that he "went up in accordance with
a revelation." For this was one of those supreme moments in his life
when he looked for and received the direct guidance of heaven. It
was a most critical step to carry this question of Gentile circumcision
up to Jerusalem, and to take Titus with him there, into the enemies'
stronghold. Moreover, on the settlement of this matter Paul knew
that his Apostolic status depended, so far as human recognition was
concerned. It would be seen whether the Jewish Church would
acknowledge the converts of the Gentile mission as brethren in
Christ; and whether the first Apostles would receive him, "the
untimely one," as a colleague of their own. Never had he more
urgently needed or more implicitly relied upon Divine direction than
at this hour.
"And I put before them (the Church at Jerusalem) the gospel which I
preach among the Gentiles—but privately to those of repute: am I
running (said I), or have I run, in vain?" The latter clause we read
interrogatively, along with such excellent grammatical interpreters as
Meyer, Wieseler, and Hofmann. Paul had not come to Jerusalem in
order to solve any doubt in his own mind; but he wished the Church
of Jerusalem to declare its mind respecting the character of his
ministry. He was not "running as uncertainly;" nor in view of the
"revelation" just given him could he have any fear for the result of
his appeal. But it was in every way necessary that the appeal should
be made.
The interjected words, "but privately," etc., indicate that there were
two meetings during the conference, such as those which seem to
be distinguished in Acts xv. 4 and 6; and that the Apostle's
statement and the question arising out of it were addressed more
pointedly to "those of repute." By this term we understand, here and
in ver. 6, "the apostles and elders" (Acts xv.), headed by Peter and
James, amongst whom "those reputed to be pillars" are
distinguished in ver. 9. Paul dwells upon the phrase οἱ δοκοῦντες,
because, to be sure, it was so often on the lips of the Judaizers, who
were in the habit of speaking with an imposing air, and by way of
contrast with Paul, of "the authorities" (at Jerusalem)—as the
designation might appropriately be rendered. These very men whom
the Legalists were exalting at Paul's expense, the venerated chiefs of
the mother Church, had on this occasion, Paul is going to say, given
their approval to his doctrine; they declined to impose circumcision
on Gentile believers. The Twelve were not stationary at Jerusalem,
and therefore could not form a fixed court of reference there; hence
a greater importance accrued to the Elders of the city Church, with
the revered James at their head, the brother of the Lord.
The Apostle, in bringing Titus, had brought up the subject-matter of
the controversy. The "gospel of the uncircumcision" stood before the
Jewish authorities, an accomplished fact. Titus was there, by the
side of Paul, a sample—and a noble specimen, we can well believe—
of the Gentile Christendom which the Jewish Church must either
acknowledge or repudiate. How will they treat him? Will they admit
this foreign protege of Paul to their communion? Or will they require
him first to be circumcised? The question at issue could not take a
form more crucial for the prejudices of the mother Church. It was
one thing to acknowledge uncircumcised fellow-believers in the
abstract, away yonder at Antioch or Iconium, or even at Cæsarea;
and another thing to see Titus standing amongst them in his
heathen uncleanness, on the sacred soil of Jerusalem, under the
shadow of the Temple, and to hear Paul claiming for him—for this
"dog" of a Gentile—equally with himself the rights of Christian
brotherhood! The demand was most offensive to the pride of
Judaism, as no one knew better than Paul; and we cannot wonder
that a revelation was required to justify the Apostle in making it. The
case of Trophimus, whose presence with the Apostle at Jerusalem
many years afterwards proved so nearly fatal (Acts xxi. 27-30),
shows how exasperating to the legalist party his action in this
instance must have been. Had not Peter and the better spirits of the
Church in Jerusalem laid to heart the lesson of the vision of Joppa,
that "no man must be called common or unclean," and had not the
wisdom of the Holy Spirit eminently guided this first Council of the
Church,[37] Paul's challenge would have received a negative answer;
and Jewish and Gentile Christianity must have been driven asunder.
The answer, the triumphant answer, to Paul's appeal comes in the
next verse: "Nay, not even[38] Titus who was with me, being a Greek,
was compelled to be circumcised." Titus was not circumcised, in
point of fact—how can we doubt this in view of the language of ver.
5: "Not even for an hour did we yield in subjection?" And he "was
not compelled to be circumcised"—a mode of putting the denial
which implies that in refusing his circumcision urgent solicitation had
to be withstood, solicitation addressed to Titus himself, as well as to
the leaders of his party. The kind of pressure brought to bear in the
case and the quarter from which it proceeded, the Galatians would
understand from their own experience (ch. vi. 12; comp. ii. 14).
The attempt made to bring about Titus' circumcision signally failed.
Its failure was the practical reply to the question which Paul tells us
(ver. 2) he had put to the authorities in Jerusalem; or, according to
the more common rendering of ver. 2b, it was the answer to the
apprehension under which he addressed himself to them. On the
former of these views of the connection, which we decidedly prefer,
the authorities are clear of any share in the "compulsion" of Titus.
When the Apostle gives the statement that his Gentile companion
"was not compelled to be circumcised" as the reply to his appeal to
"those of repute," it is as much as to say: "The chiefs at Jerusalem
did not require Titus' circumcision. They repudiated the attempt of
certain parties to force this rite upon him." This testimony precisely
accords with the terms of the rescript of the Council, and with the
speeches of Peter and James, given in Acts xv. But it was a great
point gained to have the liberality of the Jewish Christian leaders put
to the proof in this way, to have the generous sentiments of speech
and letter made good in this example of uncircumcised Christianity
brought to their doors.
To the authorities at Jerusalem the question put by the delegates
from Antioch on the one side, and by the Circumcisionists on the
other, was perfectly clear. If they insist on Titus' circumcision, they
disown Paul and the Gentile mission: if they accept Paul's gospel,
they must leave Titus alone. Paul and Barnabas stated the case in a
manner that left no room for doubt or compromise. Their action was
marked, as ver. 5 declares, with the utmost decision. And the
response of the Jewish leaders was equally frank and definite. We
have no business, says James (Acts xv. 19), "to trouble those from
the Gentiles that turn to God." Their judgement is virtually affirmed
in ver. 3, in reference to Titus, in whose person the Galatians could
not fail to see that their own case had been settled by anticipation.
"Those of repute" disowned the Circumcisionists; the demand that
the yoke of circumcision should be imposed on the Gentiles had no
sanction from them. If the Judaizers claimed their sanction, the
claim was false.
Here the Apostle pauses, as his Gentile readers must have paused
and drawn a long breath of relief or of astonishment at what he has
just alleged. If Titus was not compelled to be circumcised, even at
Jerusalem, who, they might ask, was going to compel them?—The
full stop should therefore be placed at the end of ver. 3, not ver. 2.
Vv. 1-3 form a paragraph complete in itself. Its last sentence
resolves the decisive question raised in this visit of Paul's to
Jerusalem, when he "took with him also Titus."
II. The opening words of ver. 4 have all the appearance of
commencing a new sentence. This sentence, concluded in ver. 5, is
grammatically incomplete; but that is no reason for throwing it upon
the previous sentence, to the confusion of both. There is a transition
of thought, marked by the introductory But,[39] from the issue of
Paul's second critical visit to Jerusalem (vv. 1-3) to the cause which
made it necessary. This was the action of "false brethren," to whom
the Apostle made a determined and successful resistance (vv. 4, 5).
The opening "But" does not refer to ver. 3 in particular, rather to the
entire foregoing paragraph. The ellipsis (after "But") is suitably
supplied in the marginal rendering of the Revisers, where we take it
was to mean, not "Because of the false brethren Titus was not (or
was not compelled to be) circumcised," but "Because of the false
brethren this meeting came about, or, I took the course aforesaid."
To know what Paul means by "false brethren," we must turn to ch. i.
6-9, iii. 1, iv. 17, v. 7-12, vi. 12-14, in this Epistle; and again to 2 Cor.
ii. 17-iii. 1, iv. 2, xi. 3, 4, 12-22, 26; Rom. xvi. 17, 18; Phil. iii. 2.
They were men bearing the name of Christ and professing faith in
Him, but Pharisees at heart, self-seeking, rancorous, unscrupulous
men, bent on exploiting the Pauline Churches for their own
advantage, and regarding Gentile converts to Christ as so many
possible recruits for the ranks of the Circumcision.
But where, and how, were these traitors "privily brought in?"
Brought in, we answer, to the field of the Gentile mission; and
doubtless by local Jewish sympathisers, who introduced them
without the concurrence of the officers of the Church. They "came in
privily"—slipped in by stealth—"to spy out our liberty which we have
in Christ Jesus." Now it was at Antioch and in the pagan Churches
that this liberty existed in its normal exercise—the liberty for which
our Epistle contends, the enjoyment of Christian privileges
independently of Jewish law—in which Paul and his brother
missionaries had identified themselves with their Gentile followers.
The "false brethren" were Jewish spies in the Gentile Christian camp.
We do not see how the Galatians could have read the Apostle's
words otherwise; nor how it could have occurred to them that he
was referring to the way in which these men had been originally
"brought into" the Jewish Church. That concerned neither him nor
them. But their getting into the Gentile fold was the serious thing.
They are the "certain who came down from Judæa, and taught the
(Gentile) brethren, saying, Except ye be circumcised after the
custom of Moses, ye cannot be saved;" and whom their own Church
afterwards repudiated (Acts xv. 24). With Antioch for the centre of
their operations, these mischief-makers disturbed the whole field of
Paul and Barnabas' labours in Syria and Cilicia (Acts xv. 23; comp.
Gal. i. 21). For the Galatian readers, the terms of this sentence,
coming after the anathema of ch. i. 6-9, threw a startling light on
the character of the Judean emissaries busy in their midst. This
description of the former "troublers" strikes at the Judaic opposition
in Galatia. It is as if the Apostle said: "These false brethren,
smuggled in amongst us, to filch away our liberties in Christ, wolves
in sheep's clothing—I know them well; I have encountered them
before this. I never yielded to their demands a single inch. I carried
the struggle with them to Jerusalem. There, in the citadel of
Judaism, and before the assembled chiefs of the Judean Church, I
vindicated once and for all, under the person of Titus, your
imperilled Christian rights."
But as the Apostle dilates on the conduct of these Jewish intriguers,
the precursors of such an army of troublers, his heart takes fire; in
the rush of his emotion he is carried away from the original purport
of his sentence, and breaks it off with a burst of indignation: "To
whom," he cries, "not even for an hour did we yield by subjection,
that the truth of the gospel might abide with you." A breakdown like
this—an anacoluthon, as the grammarians call it—is nothing strange
in Paul's style. Despite the shipwrecked grammar, the sense comes
off safely enough. The clause, "we did not yield," etc., describes in a
negative form, and with heightened effect, the course the Apostle
had pursued from the first in dealing with the false brethren. In this
unyielding spirit he had acted, without a moment's wavering, from
the hour when, guided by the Holy Spirit, he set out for Jerusalem
with the uncircumcised Titus by his side, until he heard his Gentile
gospel vindicated by the lips of Peter and James, and received from
them the clasp of fellowship as Christ's acknowledged Apostle to the
heathen.
It was therefore the action of Jewish interlopers, men of the same
stamp as those infesting the Galatian Churches, which occasioned
Paul's second, public visit to Jerusalem, and his consultation with the
heads of the Judean Church. This decisive course he was himself
inspired to take; while at the same time it was taken on behalf and
under the direction of the Church of Antioch, the metropolis of
Gentile Christianity. He had gone up with Barnabas and "certain
others"—including the Greek Titus chosen by himself—the company
forming a representative deputation, of which Paul was the leader
and spokesman. This measure was the boldest and the only
effectual means of combatting the Judaistic propaganda. It drew
from the authorities at Jerusalem the admission that "Circumcision is
nothing," and that Gentile Christians are free from the ritual law.
This was a victory gained over Jewish prejudice of immense
significance for the future of Christianity. The ground was already cut
from under the feet of the Judaic teachers in Galatia, and of all who
should at any time seek to impose external rites as things essential
to salvation in Christ. To all his readers Paul can now say, so far as
his part is concerned: The truth of the gospel abides with you.
CHAPTER VIII.
PAUL AND THE THREE PILLARS.
"But from those who were reputed to be somewhat (what they
once were, it maketh no matter to me: God accepteth not man's
person)—they, I say, who were of repute imparted nothing to
me: but contrariwise, when they saw that I had been intrusted
with the gospel of the uncircumcision, even as Peter with the
gospel of the circumcision (for he that wrought for Peter unto
the apostleship of the circumcision wrought for me also unto the
Gentiles); and when they perceived the grace that was given
unto me, James and Cephas and John, they who were reputed
to be pillars, gave to me and Barnabas the right hands of
fellowship, that we should go unto the Gentiles, and they unto
the circumcision; only they would that we should remember the
poor; which very thing I was also zealous to do."—Gal. ii. 6-10.

We have dealt by anticipation, in Chapter VI., with several of the


topics raised in this section of the Epistle—touching particularly the
import of the phrase "those of repute," and the tone of
disparagement in which these dignitaries appear to be spoken of in
ver. 6. But there still remains in these verses matter in its weight and
difficulty more than sufficient to occupy another Chapter.
The grammatical connection of the first paragraph, like that of vv. 2,
3, is involved and disputable. We construe its clauses in the following
way:—(1) Ver. 6 begins with a But, contrasting "those of repute"
with the "false brethren" dealt with in the last sentence. It contains
another anacoluthon (or incoherence of language), due to the surge
of feeling remarked in ver. 4, which still disturbs the Apostle's
grammar. He begins: "But from those reputed to be something"—as
though he intended to say, "I received on my part nothing, no
addition or qualification to my gospel." But he has no sooner
mentioned "those of repute" than he is reminded of the studied
attempt that was made to set up their authority in opposition to his
own, and accordingly throws in this protest: "what they were
aforetime,[40] makes no difference to me: man's person God doth not
accept." But in saying this, Paul has laid down one of his favourite
axioms, a principle that filled a large place in his thoughts;[41] and its
enunciation deflects the course of the main sentence, so that it is
resumed in an altered form: "For to me those of repute imparted
nothing." Here the me receives a greater emphasis; and for takes
the place of but. The fact that the first Apostles had nothing to
impart to Paul, signally illustrates the Divine impartiality, which often
makes the last and least in human eyes equal to the first.
(2) Vv. 7-9 state the positive, as ver. 6 the negative side of the
relation between Paul and the elder Apostles, still keeping in view
the principle laid down in the former verse. "Nay, on the contrary,
when they saw that I have in charge the gospel of the
uncircumcision, as Peter that of the circumcision (ver. 7)—and when
they perceived the grace that had been given me, James and
Cephas and John, those renowned pillars of the Church, gave the
right hand of fellowship to myself and Barnabas, agreeing that we
should go to the Gentiles, while they laboured amongst the Jews"
(ver. 9).
(3) Ver. 8 comes in as a parenthesis, explaining how the authorities
at Jerusalem came to see that this trust belonged to Paul. "For," he
says, "He that in Peter's case displayed His power in making him
(above all others) Apostle of the Circumcision, did as much for me in
regard to the Gentiles." It is not human ordination, but Divine
inspiration that makes a minister of Jesus Christ. The noble Apostles
of Jesus had the wisdom to see this. It had pleased God to bestow
this grace on their old Tarsian persecutor; and they frankly
acknowledged the fact.
Thus Paul sets forth, in the first place, the completeness of his
Apostolic qualifications, put to proof at the crisis of the circumcision
controversy; and in the second place, the judgement formed
respecting him and his office by the first Apostles and companions of
the Lord.
I. "To me those of repute added nothing." Paul had spent but a
fortnight in the Christian circle of Jerusalem, fourteen years ago. Of
its chiefs he had met at that time only Peter and James, and them in
the capacity of a visitor, not as a disciple or a candidate for office. He
had never sought the opportunity, nor felt the need, of receiving
instruction from the elder Apostles during all the years in which he
had preached Christ amongst the heathen. It was not likely he would
do so now. When he came into conference and debate with them at
the Council, he showed himself their equal, neither in knowledge nor
authority "a whit behind the very chiefest." And they were conscious
of the same fact.
On the essentials of the gospel Paul found himself in agreement with
the Twelve. This is implied in the language of ver. 6. When one
writes, "A adds nothing to B," one assumes that B has already what
belongs to A, and not something different. Paul asserts in the most
positive terms he can command, that his intercourse with the
holders of the primitive Christian tradition left him as a minister of
Christ exactly where he was before. "On me," he says, "they
conferred nothing"—rather, perhaps, "addressed no communication
to me." The word used appears to deny their having made any
motion of the kind. The Greek verb is the same that was employed
in ch. i. 16, a rare and delicate compound.[42] Its meaning varies, like
that of our confer, communicate, as it is applied in a more or less
active sense. In the former place Paul had said that he "did not
confer with flesh and blood"; now he adds, that flesh and blood did
not confer anything upon him. Formerly he did not bring his
commission to lay it before men; now they had nothing to bring on
their part to lay before him. The same word affirms the Apostle's
independence at both epochs, shown in the first instance by his
reserve toward the dignitaries at Jerusalem, and in the second by
their reserve toward him. Conscious of his Divine call, he sought no
patronage from the elder Apostles then; and they, recognising that
call, offered him no such patronage now. Paul's gospel for the
Gentiles was complete, and sufficient unto itself. His ministry showed
no defect in quality or competence. There was nothing about it that
laid it open to correction, even on the part of those wisest and
highest in dignity amongst the personal followers of Jesus.
So Paul declares; and we can readily believe him. Nay, we are
tempted to think that it was rather the Pillars who might need to
learn from him, than he from them. In doctrine, Paul holds the
primacy in the band of the Apostles. While all were inspired by the
Spirit of Christ, the Gentile Apostle was in many ways a more richly
furnished man than any of the rest. The Paulinism of Peter's First
Epistle goes to show that the debt was on the other side. Their
earlier privileges and priceless store of recollections of "all that Jesus
did and taught," were matched on Paul's side by a penetrating logic,
a breadth and force of intellect applied to the facts of revelation, and
a burning intensity of spirit, which in their combination were unique.
The Pauline teaching, as it appears in the New Testament, bears in
the highest degree the marks of original genius, the stamp of a mind
whose inspiration is its own.
Modern criticism even exaggerates Paul's originality. It leaves the
other Apostles little more than a negative part to play in the
development of Christian truth. In some of its representations, the
figure of Paul appears to overshadow even that of the Divine Master.
It was Paul's creative genius, it is said, his daring idealism, that
deified the human Jesus, and transformed the scandal of the cross
into the glory of an atonement reconciling the world to God. Such
theories Paul himself would have regarded with horror. "I received of
the Lord that which I delivered unto you:" such is his uniform
testimony. If he owed so little as a minister of Christ to his brother
Apostles, he felt with the most sincere humility that he owed
everything to Christ. The agreement of Paul's teaching with that of
the other New Testament writers, and especially with that of Jesus in
the Gospels, proves that, however distinct and individual his
conception of the common gospel, none the less there was a
common gospel of Christ, and he did not speak of his own mind. The
attempts made to get rid of this agreement by postdating the New
Testament documents, and by explaining away the larger utterances
of Jesus found in the Gospels as due to Paulinist interpolation, are
unavailing. They postulate a craftiness of ingenuity on the part of
the writers of the incriminated books, and an ignorance in those who
first received them, alike inconceivable. Paul did not build up the
splendid and imperishable fabric of his theology on some speculation
of his own. Its foundation lies in the person and the teaching of
Jesus Christ, and was common to Paul with James and Cephas and
John. "Whether I or they," he testifies, "so we preach, and so ye
believed" (1 Cor. xv. 11). Paul satisfied himself at this conference
that he and the Twelve taught the same gospel. Not in its primary
data, but in their logical development and application, lies the
specifically Pauline in Paulinism. The harmony between Paul and the
other Apostolic leaders has the peculiar value which belongs to the
agreement of minds of different orders, working independently.
The Judaizers, however, persistently asserted Paul's dependence on
the elder Apostles. "The authority of the Primitive Church, the
Apostolic tradition of Jerusalem"—this was the fulcrum of their
argument. Where could Paul, they asked, have derived his
knowledge of Christ, but from this fountain-head? And the power
that made him, could unmake him. Those who commissioned him
had the right to overrule him, or even to revoke his commission.
Was it not known that he had from time to time resorted to
Jerusalem; that he had once publicly submitted his teaching to the
examination of the heads of the Church there? The words of ver. 6
contradict these malicious insinuations. Hence the positiveness of
the Apostle's self-assertion. In the Corinthian Epistles his claim to
independence is made in gentler style, and with expressions of
humility that might have been misunderstood here. But the position
Paul takes up is the same in either case: "I am an Apostle. I have
seen Jesus our Lord. You—Corinthians, Galatians—are my work in
the Lord." That Peter and the rest were in the old days so near to
the Master, "makes no difference" to Paul. They are what they are—
their high standing is universally acknowledged, and Paul has no
need or wish to question it; but, by the grace of God, he also is what
he is (1 Cor. xv. 10). Their Apostleship does not exclude or derogate
from his.
The self-depreciation, the keen sense of inferiority in outward
respects, so evident in Paul's allusions to this subject elsewhere, is
after all not wanting here. For when he says, "God regards not
man's person," it is evident that in respect of visible qualifications
Paul felt that he had few pretensions to make. Appearances were
against him. And those who "glory in appearance" were against him
too (2 Cor. v. 12). Such men could not appreciate the might of the
Spirit that wrought in Paul, nor the sovereignty of Divine election.
They "reckoned" of the Apostle "as though he walked according to
flesh" (2 Cor. x. 2). It seemed to them obvious, as a matter of
course, that he was far below the Twelve. With men of worldly
wisdom the Apostle did not expect that his arguments would prevail.
His appeal was to "the spiritual, who judge all things."
So we come back to the declaration of the Apostle in ch. i. 11: "I
give you to know, brethren, that my gospel is not according to man."
Man had no hand either in laying its foundation or putting on the
headstone. Paul's predecessors in Apostolic office did not impart the
gospel to him at the outset; nor at a later time had they attempted
to make any addition to the doctrine he had taught far and wide
amongst the heathen. His Apostleship was from first to last a
supernatural gift of grace.
II. Instead, therefore, of assuming to be his superiors, or offering to
bestow something of their own on Paul, the three renowned pillars
of the faith at Jerusalem acknowledged him as a brother Apostle.
"They saw that I am intrusted with the gospel of the
uncircumcision." The form of the verb implies a trust given in the
past and taking effect in the present, a settled fact. Once for all, this
charge had devolved on Paul. He is "appointed herald and apostle"
of "Christ Jesus, who gave Himself a ransom for all,—teacher of the
Gentiles in faith and truth" (1 Tim. ii. 6, 7). That office Paul still
holds. He is the leader of Christian evangelism. Every new
movement in heathen missionary enterprise looks to his teaching for
guidance and inspiration.
The conference at Jerusalem in itself furnished conclusive evidence
of Paul's Apostolic commission. The circumcision controversy was a
test not only for Gentile Christianity, but at the same time for its
Apostle and champion. Paul brought to this discussion a knowledge
and insight, a force of character, a conscious authority and unction
of the Holy Spirit, that powerfully impressed the three great men
who listened to him. The triumvirate at Jerusalem well knew that
Paul had not received his marvellous gifts through their hands. Nor
was there anything lacking to him which they felt themselves called
upon to supply. They could only say, "This is the Lord's doing; and it
is marvellous in our eyes." Knowing, as Peter at least, we presume,
had done for many years,[43] the history of Paul's conversion, and
seeing as they now did the conspicuous Apostolic signs attending his
ministry, James and Cephas and John could only come to one
conclusion. The gospel of the uncircumcision, they were convinced,
was committed to Paul, and his place in the Church was side by side
with Peter. Peter must have felt as once before on a like occasion: "If
God gave unto him a gift equal to that He gave to me, who am I,
that I should be able to hinder God?" (Acts xi. 17). It was not for
them because of their elder rank and dignity to debate with God in
this matter, and to withhold their recognition from His "chosen
vessel."
John had not forgotten his Master's reproof for banning the man that
"followeth not with us" (Luke ix. 49; Mark ix. 38). They "recognised,"
Paul says, "the grace that had been given me;" and by that he
means, to be sure, the undeserved favour that raised him to his
Apostolic office.[44] This recognition was given to Paul. Barnabas
shared the "fellowship." His hand was clasped by the three chiefs at
Jerusalem, not less warmly than that of his younger comrade. But it
is in the singular number that Paul speaks of "the grace that was
given me," and of the "trust in the gospel" and the "working of God
unto Apostleship."
Why then does not Paul say outright, "they acknowledged me an
Apostle, the equal of Peter?" Some are bold enough to say—Holsten
in particular—"Because this is just what the Jerusalem chiefs never
did, and never could have done."[45] We will only reply, that if this
were the case, the passage is a continued suggestio falsi. No one
could write the words of vv. 7-9, without intending his readers to
believe that such a recognition took place. Paul avoids the point-
blank assertion, with a delicacy that any man of tolerable modesty
will understand. Even the appearance of "glorying" was hateful to
him (2 Cor. x. 17; xi. 1; xii. 1-5, 11).
The Church at Jerusalem, as we gather from vv. 7, 8, observed in
Paul "signs of the Apostle" resembling those borne by Peter. His
Gentile commission ran parallel with Peter's Jewish commission. The
labours of the two men were followed by the same kind of success,
and marked by similar displays of miraculous power. The like seal of
God was stamped on both. This correspondence runs through the
Acts of the Apostles. Compare, for example, Paul's sermon at
Antioch in Pisidia with that of Peter on the Day of Pentecost; the
healing of the Lystran cripple and the punishment of Elymas, with
the case of the lame man at the Temple gate and the encounter of
Peter and Simon Magus. The conjunction of the names of Peter and
Paul was familiar to the Apostolic Church. The parallelism between
the course of these great Apostles was no invention of second-
century orthodoxy, set up in the interests of a "reconciling
hypothesis;" it attracted public attention as early as 51 A.D., while
they were still in their mid career. If this idea so strongly possessed
the minds of the Jewish Christian leaders and influenced their action
at the Council of Jerusalem, we need not be surprised that it should
dominate Luke's narrative to the extent that it does. The allusions to
Peter in 1 Corinthians[46] afford further proof that in the lifetime of
the two Apostles it was a common thing to link their names together.
But had not Peter also a share in the Gentile mission? Does not the
division of labour made at this conference appear to shut out the
senior Apostle from a field to which he had the prior claim? "Ye
know," said Peter at the Council, "how that a good while ago God
made choice among you, that by my mouth the Gentiles should hear
the word of the gospel, and believe" (Acts xv. 7). To Peter was
assigned the double honour of "opening the door of faith" both to
Jew and Gentile. This experience made him the readier to
understand Paul's position, and gave him the greater weight in the
settlement of the question at issue. And not Peter alone, but Philip
the evangelist and other Jewish Christians had carried the gospel
across the line of Judaic prejudice, before Paul appeared on the
scene. Barnabas and Silas were both emissaries of Jerusalem. So
that the mother Church, if she could not claim Paul as her son, had
nevertheless a large stake in the heathen mission. But when Paul
came to the front, when his miraculous call, his incomparable gifts
and wonderful success had made themselves known, it was evident
to every discerning mind that he was the man chosen by God to
direct this great work. Peter had opened the door of faith to the
heathen, and had bravely kept it open; but it was for Paul to lead
the Gentile nations through the open door, and to make a home for
them within the fold of Christ. The men who had laboured in this
field hitherto were Paul's forerunners. And Peter does not hesitate to
acknowledge the younger Apostle's special fitness for this wider
province of their common work; and with the concurrence of James
and John he yields the charge of it to him.
Let us observe that it is two different provinces, not different
gospels, that are in view. When the Apostle speaks of "the gospel of
the uncircumcision" as committed to himself, and that "of the
circumcision" to Peter, he never dreams of any one supposing, as
some of his modern critics persist in doing, that he meant two
different doctrines. How can that be possible, when he has declared
those anathema who preach any other gospel? He has laid his
gospel before the heads of the Jerusalem Church. Nothing has
occurred there, nothing is hinted here, to suggest the existence of a
"radical divergence." If James and the body of the Judean Church
really sympathised with the Circumcisionists, with those whom the
Apostle calls "false brethren," how could he with any sincerity have
come to an agreement with them, knowing that this tremendous gulf
was lying all the while between the Pillars and himself? Zeller argues
that the transaction was simply a pledge of "reciprocal toleration, a
merely external concordat between Paul and the original Apostles."
[47]
The clasp of brotherly friendship was a sorry farce, if that were
all it meant—if Paul and the Three just consented for the time to slur
over irreconcilable differences; while Paul in turn has glossed over
the affair for us in these artful verses! Baur, with characteristic
finesse, says on the same point: "The κοινωνία was always a
division; it could only be brought into effect by one party going εἰς
τὰ ἔθνη, the other εἰς τὴν περιτομήν. As the Jewish Apostles could
allege nothing against the principles on which Paul founded his
evangelical mission, they were obliged to recognise them in a certain
manner; but their recognition was a mere outward one. They left
him to work on these principles still further in the cause of the
gospel among the Gentiles; but for themselves they did not desire to
know anything more about them."[48] So that, according to the
Tübingen critics, we witness in ver. 9 not a union, but a divorce! The
Jewish Apostles recognise Paul as a brother, only in order to get rid
of him. Can misinterpretation be more unjust than this? Paul does
not say, "They gave us the right hand of fellowship on condition
that," but, "in order that we should go this way, they that." As much
as to say: The two parties came together and entered into a closer
union, so that with the best mutual understanding each might go its
own way and pursue its proper work in harmony with the other. For
Paul it would have been a sacrilege to speak of the diplomatic
compromise which Baur and Zeller describe as "giving the right hand
of fellowship."
Never did the Church more deeply realise than at her first Council
the truth, that "there is one body and one Spirit; one Lord, one faith,
one baptism; one God and Father of all, who is above all, and
through all, and in all" (Eph. iv. 4-6). Paul still seems to feel his hand
in the warm grasp of Peter and of John when he writes to the
Ephesians of "the foundation of the Apostles and prophets, with
Christ Jesus Himself for chief corner-stone; in whom the whole
building fitly framed together, groweth unto an holy temple in the
Lord" (ch. ii. 20, 21). Alas for the criticism that is obliged to see in
words like these the invention of second-century churchmanship,
putting into the mouth of Paul catholic sentiments of which in reality
he knew nothing! Such writers know nothing of the power of that
fellowship of the Spirit which reigned in the glorious company of the
Apostles.
"Only they would have us remember the poor"—a circumstance
mentioned partly by way of reminder to the Galatians touching the
collection for Jerusalem, which Paul had already set on foot amongst
them (1 Cor. xvi. 1). The request was prompted by the affectionate
confidence with which the Jewish chiefs embraced Paul and
Barnabas. It awakened an eager response in the Apostle's breast.
His love to his Jewish kindred made him welcome the suggestion.
Moreover every deed of charity rendered by the wealthier Gentile
Churches to "the poor saints in Jerusalem," was another tie helping
to bind the two communities to each other. Of such liberality
Antioch, under the direction of the Gentile missionaries, had already
set the example (Acts xi. 29, 30).

James, Peter, John, and Paul—it was a memorable day when these
four men met face to face. What a mighty quaternion! Amongst
them they have virtually made the New Testament and the Christian
Church. They represent the four sides of the one foundation of the
City of God. Of the Evangelists, Matthew holds affinity with James;
Mark with Peter; and Luke with Paul. James clings to the past and
embodies the transition from Mosaism to Christianity. Peter is the
man of the present, quick in thought and action, eager, buoyant,
susceptible. Paul holds the future in his grasp, and schools the
unborn nations. John gathers present, past, and future into one,
lifting us into the region of eternal life and love.
With Peter and James Paul had met before, and was to meet again.
But so far as we can learn, this was the only occasion on which his
path crossed that of John. Nor is this Apostle mentioned again in
Paul's letters. In the Acts he appears but once or twice, standing
silent in Peter's shadow. A holy reserve surrounds John's person in
the earlier Apostolic history. His hour was not yet come. But his
name ranked in public estimation amongst the three foremost of the
Jewish Church; and he exercised, doubtless, a powerful, though
quiet, conciliatory influence in the settlement of the Gentile question.
The personality of Paul excited, we may be sure, the profoundest
interest in such a mind as that of John. He absorbed, and yet in a
sense transcended, the Pauline theology. The Apocalypse, although
the most Judaic book of the New Testament, is penetrated with the
influence of Paulinism. The detection in it of a covert attack on the
Gentile Apostle is simply one of the mare's nests of a super-subtle
and suspicious criticism. John was to be the heir of Paul's labours at
Ephesus and in Asia Minor. And John's long life, touching the verge
of the second century, his catholic position, his serene and lofty
spirit, blending in itself and resolving into a higher unity the
tendencies of James and Peter and Paul, give us the best assurance
that in the Apostolic age there was indeed "One, holy, catholic,
Apostolic Church."
Paul's fellowship with Peter and with James was cordial and
endeared. But to hold the hand of John, "the disciple whom Jesus
loved," was a yet higher satisfaction. That clasp symbolized a union
between men most opposite in temperament and training, and
brought to the knowledge of Christ in very different ways, but whose
communion in Him was deep as the life eternal. Paul and John are
the two master minds of the New Testament. Of all men that ever
lived, these two best understood Jesus Christ.
CHAPTER IX.
PAUL AND PETER AT ANTIOCH
"But when Cephas came to Antioch, I resisted him to the face,
because he stood condemned. For before that certain came
from James, he did eat with the Gentiles; but when they came,
he drew back and separated himself, fearing them that were of
the circumcision. And the rest of the Jews dissembled likewise
with him; insomuch that even Barnabas was carried away with
their dissimulation. But when I saw that they walked not
uprightly according to the truth of the gospel, I said unto
Cephas before them all, If thou, being a Jew, livest as do the
Gentiles, and not as do the Jews, how compellest thou the
Gentiles to live as do the Jews? We being Jews by nature, and
not sinners of the Gentiles, yet knowing that a man is not
justified by works of law, but only through faith in Jesus Christ,
even we believed on Christ Jesus, that we might be justified by
faith in Christ, and not by the works of the law: because by the
works of the law shall no flesh be justified. But if, while we
sought to be justified in Christ, we ourselves also were found
sinners, is Christ a minister of sin? God forbid. For if I build up
again those things which I destroyed, I prove myself a
transgressor."—Gal. ii. 11-18.

The conference at Jerusalem issued in the formal recognition by the


Primitive Church of Gentile Christianity, and of Paul's plenary
Apostleship. And it brought Paul into brotherly relations with the
three great leaders of Jewish Christianity. But this fellowship was not
to continue undisturbed. The same cause was still at work which had
compelled the Apostle to go up to Jerusalem, taking Titus with him.
The leaven of Pharisaic legalism remained in the Church. Indeed, as
time went on and the national fanaticism grew more violent, this
spirit of intolerance became increasingly bitter and active. The
address of James to Paul on the occasion of his last visit to the Holy
City, shows that the Church of Jerusalem was at this time in a state
of the most sensitive jealousy in regard to the Law, and that the
legalistic prejudices always existing in it had gained a strength with
which it was difficult to cope (Acts xxi. 17-25).
But for the present the Judaizing faction had received a check. It
does not appear that the party ever again insisted on circumcision as
a thing essential to salvation for the Gentiles. The utterances of
Peter and James at the Council, and the circular addressed
therefrom to the Gentile Churches, rendered this impossible. The
Legalists made a change of front; and adopted a subtler and
seemingly more moderate policy. They now preached circumcision as
the prerogative of the Jew within the Church, and as a counsel of
perfection for the Gentile believer in Christ (ch. iii. 3). To quote the
rescript of Acts xv. against this altered form of the circumcisionist
doctrine, would have been wide of the mark.
It is against this newer type of Judaistic teaching that our Epistle is
directed.[49] Circumcision, its advocates argued, was a Divine
ordinance that must have its benefit. God has given to Israel an
indefeasible pre-eminence in His kingdom.[50] Law-keeping children
of Abraham enter the new Covenant on a higher footing than
"sinners of the Gentiles:" they are still the elect race, the holy
nation. If the Gentiles wish to share with them, they must add to
their faith circumcision, they must complete their imperfect
righteousness by legal sanctity. So they might hope to enter on the
full heritage of the sons of Abraham; they would be brought into
communion with the first Apostles and the Brother of the Lord; they
would be admitted to the inner circle of the kingdom of God. The
new Legalists sought, in fact, to superimpose Jewish on Gentile
Christianity. They no longer refused all share in Christ to the
uncircumcised; they offered them a larger share. So we construe the
teaching which Paul had to combat in the second stage of his
conflict with Judaism, to which his four major Epistles belong. And
the signal for this renewed struggle was given by the collision with
Peter at Antioch.
This encounter did not, we think, take place on the return of Paul
and Barnabas from the Council. The compact of Jerusalem secured
to the Church a few years of rest from the Judaistic agitation. The
Thessalonian Epistles, written in 52 or 53 A.D., go to show, not only
that the Churches of Macedonia were free from the legalist
contention, but that it did not at this period occupy the Apostle's
mind. Judas Barsabbas and Silas—not Peter—accompanied the
Gentile missionaries in returning to Antioch; and Luke gives, in Acts
xv., a tolerably full account of the circumstances which transpired
there in the interval before the second missionary tour, without the
slightest hint of any visit made at this time by the Apostle Peter. We
can scarcely believe that the circumcision party had already
recovered, and increased its influence, to the degree that it must
have done when "even Barnabas was carried away"; still less that
Peter on the very morrow of the settlement at Jerusalem and of his
fraternal communion there with Paul would show himself so far
estranged.
When, therefore, did "Cephas come down to Antioch?" The Galatians
evidently knew. The Judaizers had given their account of the matter,
to Paul's disadvantage. Perhaps he had referred to it himself on his
last visit to Galatia, when we know he spoke explicitly and strongly
against the Circumcisionists (ch. i. 9). Just before his arrival in
Galatia on this occasion he had "spent some time" at Antioch (Acts
xviii. 22, 23), in the interval between the second and third
missionary journeys. Luke simply mentions the fact, without giving
any details. This is the likeliest opportunity for the meeting of the
two Apostles in the Gentile capital. M. Sabatier,[51] in the following
sentences, appears to us to put the course of events in its true light:
—"Evidently the Apostle had quitted Jerusalem and undertaken his
second missionary journey full of satisfaction at the victory he had
gained, and free from anxiety for the future. The decisive moment of
the crisis therefore necessarily falls between the Thessalonian and
Galatian Epistles. What had happened in the meantime? The violent
discussion with Peter at Antioch (Gal. ii. 11-21), and all that this
account reveals to us,—the arrival of the emissaries from James in
the pagan-Christian circle, the counter-mission organized by the
Judaizers to rectify the work of Paul. A new situation suddenly
presents itself to the eyes of the Apostle on his return from his
second missionary journey. He is compelled to throw himself into the
struggle, and in doing so to formulate in all its rigour his principle of
the abolishment of the Law."
The "troublers" in this instance were "certain from James." Like the
"false brethren"[52] who appeared at Antioch three years before, they
came from the mother Church, over which James presided. The
Judaizing teachers at Corinth had their "commendatory letters" (2
Cor. iii. 1), derived assuredly from the same quarter. In all likelihood,
their confederates in Galatia brought similar credentials. We have
already seen that the authority of the Primitive Church was the chief
weapon used by Paul's adversaries. These letters of commendation
were part of the machinery of the anti-Pauline agitation. How the
Judaizers obtained these credentials, and in what precise relation
they stood to James, we can only conjecture. Had the Apostle held
James responsible for their action, he would not have spared him
any more than he has done Peter. James held a quasi-pastoral
relation to Christian Jews of the Dispersion. And as he addressed his
Epistle to them, so he would be likely on occasion to send delegates
to visit them. Perhaps the Circumcisionists found opportunity to pass
themselves off in this character; or they may have abused a
commission really given them, by interfering with Gentile
communities. That the Judaistic emissaries in some way or other
adopted false colours, is plainly intimated in 2 Cor. xi. 13. James,
living always at Jerusalem, being moreover a man of simple
character, could have little suspected the crafty plot which was
carried forward under his name.
These agents addressed themselves in the first instance to the Jews,
as their commission from Jerusalem probably entitled them to do.
They plead for the maintenance of the sacred customs. They insist
that the Mosaic rites carry with them an indelible sanctity; that their
observance constitutes a Church within the Church. If this separation
is once established, and the Jewish believers in Christ can be
induced to hold themselves aloof and to maintain the "advantage of
circumcision," the rest will be easy. The way will then be open to
"compel the Gentiles to Judaize." For unless they do this, they must
be content to remain on a lower level, in a comparatively menial
position, resembling that of uncircumcised proselytes in the
Synagogue. The circular of the Jerusalem Council may have been
interpreted by the Judaists in this sense, as though it laid down the
terms, not of full communion between Jew and Gentile believers, but
only of a permissive, secondary recognition. At Antioch the new
campaign of the Legalists was opened, and apparently with signal
success. In Galatia and Corinth we see it in full progress.
The withdrawal of Peter and the other Jews at Antioch from the
table of the Gentiles virtually "compelled" the latter "to Judaize." Not
that the Jewish Apostle had this intention in his mind. He was made
the tool of designing men. By "separating himself" he virtually said
to every uncircumcised brother, "Stand by thyself, I am holier than
thou." Legal conformity on the part of the Gentiles was made the
condition of their communion with Jewish Christians—a demand
simply fatal to Christianity. It re-established the principle of salvation
by works in a more invidious form. To supplement the righteousness
of faith by that of law, meant to supplant it. To admit that the
Israelite by virtue of his legal observances stood in a higher position
than "sinners of the Gentiles," was to stultify the doctrine of the
cross, to make Christ's death a gratuitous sacrifice. Peter's error,
pushed to its logical consequences, involved the overthrow of the
Gospel. This the Gentile Apostle saw at a glance. The situation was
one of imminent danger. Paul needed all his wisdom, and all his
courage and promptitude to meet it.
It had been Peter's previous rule, since the vision of Joppa, to lay
aside Jewish scruples of diet and to live in free intercourse with
Gentile brethren. He "was wont to eat with the Gentiles. Though a
born Jew, he lived in Gentile fashion"—words unmistakably
describing Peter's general habit in such circumstances. This Gentile
conformity of Peter was a fact of no small moment for the Galatian
readers. It contravenes the assertion of a radical divergence
between Petrine and Pauline Christianity, whether made by Ebionites
or Baurians.
The Jewish Apostle's present conduct was an act of "dissimulation."
He was belying his known convictions, publicly expressed and acted
on for years. Paul's challenge assumes that his fellow-Apostle is
acting insincerely. And this assumption is explained by the account
furnished in the Acts of the Apostles respecting Peter's earlier
relations with Gentile Christianity (ch. x. 1-xi. 18; xv. 6-11). The
strength of Paul's case lay in the conscience of Peter himself. The
conflict at Antioch, so often appealed to in proof of the rooted
opposition between the two Apostles, in reality gives evidence to the
contrary effect. Here the maxim strictly applies, Exceptio probat
regulam.
Peter's lapse is quite intelligible. No man who figures in the New
Testament is better known to us. Honest, impulsive, ready of
speech, full of contagious enthusiasm, brave as a lion, firm as a rock
against open enemies, he possessed in a high degree the qualities
which mark out a leader of men. He was of the stuff of which Christ
makes His missionary heroes. But there was a strain of weakness in
Peter's nature. He was pliable. He was too much at the mercy of
surroundings. His denial of Jesus set this native fault in a light
terribly vivid and humiliating. It was an act of "dissimulation." In his
soul there was a fervent love to Christ. His zeal had brought him to
the place of danger. But for the moment he was alone. Public
opinion was all against him. A panic fear seized his brave heart. He
forgot himself; he denied the Master whom he loved more than life.
His courage had failed; never his faith. "Turned back again" from his
coward flight, Peter had indeed "strengthened his brethren" (Luke
xxii. 31, 32). He proved a tower of strength to the infant Church,
worthy of his cognomen of the rock. For more than twenty years he
had stood unshaken. No name was so honoured in the Church as
Peter's. For Paul to be compared to him was the highest possible
distinction.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like