100% found this document useful (1 vote)
5 views

Modern Programming Made Easy Using Java Scala Groovy and JavaScript Second Edition Adam L Davis instant download

The document is about the book 'Modern Programming Made Easy: Using Java, Scala, Groovy, and JavaScript, Second Edition' by Adam L. Davis, which covers various programming concepts and languages. It includes chapters on installation, basics of coding, data structures, conditionals, loops, methods, inheritance, design patterns, functional programming, refactoring, and utilities. The book aims to provide a comprehensive guide for learning modern programming techniques using these languages.

Uploaded by

civiceamonj3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
5 views

Modern Programming Made Easy Using Java Scala Groovy and JavaScript Second Edition Adam L Davis instant download

The document is about the book 'Modern Programming Made Easy: Using Java, Scala, Groovy, and JavaScript, Second Edition' by Adam L. Davis, which covers various programming concepts and languages. It includes chapters on installation, basics of coding, data structures, conditionals, loops, methods, inheritance, design patterns, functional programming, refactoring, and utilities. The book aims to provide a comprehensive guide for learning modern programming techniques using these languages.

Uploaded by

civiceamonj3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Modern Programming Made Easy Using Java Scala

Groovy and JavaScript Second Edition Adam L


Davis download

https://textbookfull.com/product/modern-programming-made-easy-
using-java-scala-groovy-and-javascript-second-edition-adam-l-
davis/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Modern Programming Made Easy: Using Java, Scala,


Groovy, and JavaScript 2nd Edition Adam L. Davis

https://textbookfull.com/product/modern-programming-made-easy-
using-java-scala-groovy-and-javascript-2nd-edition-adam-l-davis/

Learning concurrent programming in Scala learn the art


of building intricate modern scalable and concurrent
applications using Scala Second Edition Prokopec

https://textbookfull.com/product/learning-concurrent-programming-
in-scala-learn-the-art-of-building-intricate-modern-scalable-and-
concurrent-applications-using-scala-second-edition-prokopec/

Object Orientation Abstraction and Data Structures


Using Scala Second Edition Lacher

https://textbookfull.com/product/object-orientation-abstraction-
and-data-structures-using-scala-second-edition-lacher/

Beginning Functional JavaScript. Functional Programming


with JavaScript using EcmaScript 6 1st Edition Anto
Aravinth

https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth/
Beginning Functional JavaScript: Functional Programming
with JavaScript Using EcmaScript 6 1st Edition Anto
Aravinth

https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth-2/

Head First JavaScript Programming, 2nd Edition: A


Learner’s Guide to Modern JavaScript Eric Freeman

https://textbookfull.com/product/head-first-javascript-
programming-2nd-edition-a-learners-guide-to-modern-javascript-
eric-freeman/

Head First JavaScript Programming, 2nd Edition: A


Learner’s Guide to Modern JavaScript Eric Freeman

https://textbookfull.com/product/head-first-javascript-
programming-2nd-edition-a-learners-guide-to-modern-javascript-
eric-freeman-2/

U S Immigration Made Easy 19th Edition US Immigration


Made Easy Ilona Bray

https://textbookfull.com/product/u-s-immigration-made-easy-19th-
edition-us-immigration-made-easy-ilona-bray/

Eloquent Javascript A Modern Introduction to


Programming Marijn Haverbeke

https://textbookfull.com/product/eloquent-javascript-a-modern-
introduction-to-programming-marijn-haverbeke/
Modern
Programming
Made Easy
Using Java, Scala, Groovy,
and JavaScript

Second Edition

Adam L. Davis
Modern Programming
Made Easy
Using Java, Scala, Groovy,
and JavaScript
Second Edition

Adam L. Davis
Modern Programming Made Easy: Using Java, Scala, Groovy, and
JavaScript
Adam L. Davis
Oviedo, FL, USA

ISBN-13 (pbk): 978-1-4842-5568-1 ISBN-13 (electronic): 978-1-4842-5569-8


https://doi.org/10.1007/978-1-4842-5569-8

Copyright © 2020 by Adam L. Davis


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.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the author nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Coordinating Editor: Mark Powers
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media, 1 New York Plaza,
New York, NY 10004, U.S.A.. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@
springer-­sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and
the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint, paperback, or
audio rights, please email [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book’s product page, located at www.apress.com/9781484255681. For
more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Dedicated to all teachers.
Thank you for teaching!
Table of Contents
About the Author��������������������������������������������������������������������������������xv
About the Technical Reviewer����������������������������������������������������������xvii

Chapter 1: Introduction������������������������������������������������������������������������1
Problem-Solving���������������������������������������������������������������������������������������������������1
About This Book����������������������������������������������������������������������������������������������������2

Chapter 2: Software to Install���������������������������������������������������������������3


Java/Groovy����������������������������������������������������������������������������������������������������������3
Trying It Out�����������������������������������������������������������������������������������������������������������4
Others�������������������������������������������������������������������������������������������������������������������5
Code on GitHub�����������������������������������������������������������������������������������������������������5

Chapter 3: The Basics���������������������������������������������������������������������������7


Coding Terms��������������������������������������������������������������������������������������������������������7
Primitives and Reference��������������������������������������������������������������������������������������8
Strings/Declarations���������������������������������������������������������������������������������������������9
Statements����������������������������������������������������������������������������������������������������������10
Assignment���������������������������������������������������������������������������������������������������������10
Class and Object�������������������������������������������������������������������������������������������������11
Fields, Properties, and Methods��������������������������������������������������������������������12
Groovy Classes����������������������������������������������������������������������������������������������13
JavaScript Prototypes������������������������������������������������������������������������������������14
Scala Classes������������������������������������������������������������������������������������������������14

v
Table of Contents

Creating a New Object�����������������������������������������������������������������������������������14


Comments�����������������������������������������������������������������������������������������������������������15
Summary������������������������������������������������������������������������������������������������������������15

Chapter 4: Math����������������������������������������������������������������������������������17
Adding, Subtracting, etc.�������������������������������������������������������������������������������������17
More Complex Math��������������������������������������������������������������������������������������������19
Random Numbers�����������������������������������������������������������������������������������������������20
Summary������������������������������������������������������������������������������������������������������������22

Chapter 5: Arrays, Lists, Sets, and Maps��������������������������������������������23


Arrays������������������������������������������������������������������������������������������������������������������23
Lists��������������������������������������������������������������������������������������������������������������������25
Groovy Lists���������������������������������������������������������������������������������������������������26
Scala Lists�����������������������������������������������������������������������������������������������������26
JavaScript Arrays������������������������������������������������������������������������������������������27
Sets���������������������������������������������������������������������������������������������������������������������28
Maps�������������������������������������������������������������������������������������������������������������������29
Groovy Maps��������������������������������������������������������������������������������������������������30
Scala Maps����������������������������������������������������������������������������������������������������30
JavaScript Maps��������������������������������������������������������������������������������������������30
Summary������������������������������������������������������������������������������������������������������������31

Chapter 6: Conditionals and Loops�����������������������������������������������������33


If, Then, Else��������������������������������������������������������������������������������������������������������33
Switch Statements����������������������������������������������������������������������������������������������34
Boolean Logic�����������������������������������������������������������������������������������������������������36
Looping���������������������������������������������������������������������������������������������������������������37
Summary������������������������������������������������������������������������������������������������������������39

vi
Table of Contents

Chapter 7: Methods����������������������������������������������������������������������������41
Call Me����������������������������������������������������������������������������������������������������������������41
Non-Java�������������������������������������������������������������������������������������������������������42
Break It Down�����������������������������������������������������������������������������������������������������43
Return to Sender�������������������������������������������������������������������������������������������������43
Static�������������������������������������������������������������������������������������������������������������������44
Varargs����������������������������������������������������������������������������������������������������������������45
Main Method�������������������������������������������������������������������������������������������������������45
Exercises�������������������������������������������������������������������������������������������������������������46
Summary������������������������������������������������������������������������������������������������������������46

Chapter 8: Inheritance������������������������������������������������������������������������47
Objectify��������������������������������������������������������������������������������������������������������������48
JavaScript������������������������������������������������������������������������������������������������������49
Parenting 101������������������������������������������������������������������������������������������������������49
JavaScript������������������������������������������������������������������������������������������������������51
Packages������������������������������������������������������������������������������������������������������������52
Public Parts���������������������������������������������������������������������������������������������������������53
JavaScript������������������������������������������������������������������������������������������������������53
Interfaces������������������������������������������������������������������������������������������������������������54
Abstract Class�����������������������������������������������������������������������������������������������������55
Enums�����������������������������������������������������������������������������������������������������������������56
Annotations���������������������������������������������������������������������������������������������������������57
Autoboxing����������������������������������������������������������������������������������������������������������58
Autoboxing�����������������������������������������������������������������������������������������������������58
Unboxing��������������������������������������������������������������������������������������������������������58
Summary������������������������������������������������������������������������������������������������������������58

vii
Table of Contents

Chapter 9: Design Patterns�����������������������������������������������������������������59


Observer�������������������������������������������������������������������������������������������������������������59
MVC���������������������������������������������������������������������������������������������������������������������61
DSL����������������������������������������������������������������������������������������������������������������������63
Closures���������������������������������������������������������������������������������������������������������63
Overriding Operators�������������������������������������������������������������������������������������65
Actors������������������������������������������������������������������������������������������������������������������66
Chain of Responsibility���������������������������������������������������������������������������������������67
Facade����������������������������������������������������������������������������������������������������������������68
Summary������������������������������������������������������������������������������������������������������������69

Chapter 10: Functional Programming������������������������������������������������71


Functions and Closures���������������������������������������������������������������������������������������72
Map, Filter, etc.����������������������������������������������������������������������������������������������������74
Immutability��������������������������������������������������������������������������������������������������������78
Java��������������������������������������������������������������������������������������������������������������������80
Groovy�����������������������������������������������������������������������������������������������������������������81
Scala�������������������������������������������������������������������������������������������������������������������82
Summary������������������������������������������������������������������������������������������������������������84

Chapter 11: Refactoring����������������������������������������������������������������������85


Object-Oriented Refactoring�������������������������������������������������������������������������������85
Functional Refactoring����������������������������������������������������������������������������������������86
Refactoring Examples�����������������������������������������������������������������������������������������86
Renaming a Method��������������������������������������������������������������������������������������87
Moving a Method from One Class to Another (Delegation)����������������������������87
Replacing a Bunch of Literals (Strings or Numbers)
with a Constant (Static Final)������������������������������������������������������������������������88

viii
Table of Contents

Renaming a Function�������������������������������������������������������������������������������������88
Wrapping a Function in Another Function and Calling It�������������������������������88
Inline a Function Wherever It Is Called����������������������������������������������������������89
Extract Common Code into a Function (the Opposite of the Previous)����������89

Chapter 12: Utilities����������������������������������������������������������������������������91


Dates and Times�������������������������������������������������������������������������������������������������91
Java Date-Time���������������������������������������������������������������������������������������������92
Groovy Date���������������������������������������������������������������������������������������������������92
JavaScript Date���������������������������������������������������������������������������������������������94
Java DateFormat�������������������������������������������������������������������������������������������94
Currency��������������������������������������������������������������������������������������������������������������96
TimeZone������������������������������������������������������������������������������������������������������������96
Scanner���������������������������������������������������������������������������������������������������������������97

Chapter 13: Building���������������������������������������������������������������������������99


Ant�����������������������������������������������������������������������������������������������������������������������99
Maven���������������������������������������������������������������������������������������������������������������100
Using Maven������������������������������������������������������������������������������������������������101
Starting a New Project��������������������������������������������������������������������������������101
Life Cycle�����������������������������������������������������������������������������������������������������102
Executing Code��������������������������������������������������������������������������������������������103
Gradle����������������������������������������������������������������������������������������������������������������105
Getting Started with Gradle�������������������������������������������������������������������������105
Projects and Tasks���������������������������������������������������������������������������������������105
Plugins���������������������������������������������������������������������������������������������������������106
Dependencies����������������������������������������������������������������������������������������������107
Do First and Last�����������������������������������������������������������������������������������������108

ix
Table of Contents

Chapter 14: Testing���������������������������������������������������������������������������111


Types of Tests����������������������������������������������������������������������������������������������������111
JUnit������������������������������������������������������������������������������������������������������������������112
Hamcrest�����������������������������������������������������������������������������������������������������113
Assumptions������������������������������������������������������������������������������������������������114
Spock����������������������������������������������������������������������������������������������������������������115
Spock Basics�����������������������������������������������������������������������������������������������115
A Simple Test�����������������������������������������������������������������������������������������������116
Mocking�������������������������������������������������������������������������������������������������������117
Lists or Tables of Data���������������������������������������������������������������������������������118
Expecting Exceptions����������������������������������������������������������������������������������119
Other Test Frameworks�������������������������������������������������������������������������������������120
Summary����������������������������������������������������������������������������������������������������������120

Chapter 15: Input/Output������������������������������������������������������������������121


Files������������������������������������������������������������������������������������������������������������������121
Reading Files����������������������������������������������������������������������������������������������������122
Writing Files������������������������������������������������������������������������������������������������������123
Downloading Files���������������������������������������������������������������������������������������������125
Summary����������������������������������������������������������������������������������������������������������126

Chapter 16: Version Control��������������������������������������������������������������127


Subversion��������������������������������������������������������������������������������������������������������128
Git����������������������������������������������������������������������������������������������������������������������128
Mercurial�����������������������������������������������������������������������������������������������������������130

Chapter 17: The Interweb�����������������������������������������������������������������131


Web 101������������������������������������������������������������������������������������������������������������132
My First Web App����������������������������������������������������������������������������������������������133

x
Table of Contents

The Holy Grails��������������������������������������������������������������������������������������������������135


Quick Overview��������������������������������������������������������������������������������������������135
Plug-ins�������������������������������������������������������������������������������������������������������139
Cloud�����������������������������������������������������������������������������������������������������������������140
The REST�����������������������������������������������������������������������������������������������������������141
Using Maven Archetypes�����������������������������������������������������������������������������142
Using Grails JSON Views�����������������������������������������������������������������������������142
Summary����������������������������������������������������������������������������������������������������������143

Chapter 18: Swinging Graphics��������������������������������������������������������145


Hello Window����������������������������������������������������������������������������������������������������145
Push My Buttons�����������������������������������������������������������������������������������������������148
Fake Browser����������������������������������������������������������������������������������������������������149
Griffon���������������������������������������������������������������������������������������������������������������152
Advanced Graphics�������������������������������������������������������������������������������������������153
Graphics Glossary���������������������������������������������������������������������������������������������154
Summary����������������������������������������������������������������������������������������������������������155

Chapter 19: Creating a Magical User Experience�����������������������������157


Application Hierarchy����������������������������������������������������������������������������������������157
Consider Your Audience������������������������������������������������������������������������������������158
Choice Is an Illusion������������������������������������������������������������������������������������������159
Direction������������������������������������������������������������������������������������������������������������159
Skeuomorphism������������������������������������������������������������������������������������������������160
Context Is Important������������������������������������������������������������������������������������������160
KISS������������������������������������������������������������������������������������������������������������������160
You Are Not the User�����������������������������������������������������������������������������������������161
Summary����������������������������������������������������������������������������������������������������������161

xi
Table of Contents

Chapter 20: Databases���������������������������������������������������������������������163


SQL (Relational) Databases�������������������������������������������������������������������������������164
SQL��������������������������������������������������������������������������������������������������������������165
Foreign Keys������������������������������������������������������������������������������������������������167
Connections�������������������������������������������������������������������������������������������������168
NoSQL (Non-relational) Databases��������������������������������������������������������������������169
Redis������������������������������������������������������������������������������������������������������������169
MongoDB�����������������������������������������������������������������������������������������������������170
Cassandra����������������������������������������������������������������������������������������������������170
VoltDB����������������������������������������������������������������������������������������������������������170
Summary����������������������������������������������������������������������������������������������������������171

Appendix A: Java/Groovy������������������������������������������������������������������173
No Java Analog�������������������������������������������������������������������������������������������������174

Appendix B: Java/Scala��������������������������������������������������������������������175
No Java Analog�������������������������������������������������������������������������������������������������176
Null, Nil, etc.������������������������������������������������������������������������������������������������������176

Appendix C: Java/JavaScript������������������������������������������������������������177
No Java Analog�������������������������������������������������������������������������������������������������178

Appendix D: Resources���������������������������������������������������������������������179

Appendix E: Free Online Learning�����������������������������������������������������181


The Death of College?���������������������������������������������������������������������������������������181
Sustainability����������������������������������������������������������������������������������������������������182
More Online Resources�������������������������������������������������������������������������������������182

xii
Table of Contents

Appendix F: Java������������������������������������������������������������������������������185

Afterword������������������������������������������������������������������������������������������187

Index�������������������������������������������������������������������������������������������������189

xiii
About the Author
Adam L. Davis makes software. He’s spent
many years developing in Java (since Java 1.2)
and has enjoyed using Spring and Hibernate
for more than a decade. Since 2006 he’s
been using Groovy, Grails, HTML, CSS, and
JavaScript, in addition to Java, to create SaaS
web applications that help track finances for
large institutions (among other things).
Adam has a master’s and a bachelor’s
degree in Computer Science from Georgia
Tech. He is also the author of Reactive Streams in Java (Apress, 2019) and
Learning Groovy 3, Second Edition (Apress, 2019). You can check out his
web site at https://github.adamldavis.com/.

xv
About the Technical Reviewer
Manuel Jordan Elera is an autodidactic
developer and researcher who enjoys learning
new technologies for his own experiments and
creating new integrations. Manuel won the
Springy Award—Community Champion and
Spring Champion 2013. In his little free time,
he reads the Bible and composes music on his
guitar. Manuel is known as dr_pompeii. He
has tech-reviewed numerous books for Apress,
including Pro Spring Boot 2 (2019), Rapid
Java Persistence and Microservices (2019), Java Language Features (2018),
Spring Boot 2 Recipes (2018), and Java APIs, Extensions and Libraries
(2018). Read his 13 detailed tutorials about many Spring technologies,
contact him through his blog at www.manueljordanelera.blogspot.com,
and follow him on his Twitter account, @dr_pompeii.

xvii
CHAPTER 1

Introduction
In my experience, learning how to program (in typical computer science
classes) can be very difficult. The curriculum tends to be boring, abstract,
and unattached to “real-world” coding. Owing to how fast technology
progresses, computer science classes tend to teach material that is very
quickly out of date and out of touch. I believe that teaching programming
could be much simpler, and I hope this book achieves that goal.

Note There’s going to be a lot of tongue-in-cheek humor


throughout this book, but this first part is serious. Don’t worry, it gets
better.

P
 roblem-Solving
Before you learn to program, the task can seem rather daunting, much like
looking at a mountain before you climb it. However, over time, you will
realize that programming is really about problem-solving.
On your journey toward learning to code, as with so much in life, you
will encounter many obstacles. You may have heard it before, but it really is
true: the path to success is to try, try, and try again. People who persevere
the most tend to be the most successful people.

© Adam L. Davis 2020 1


A. L. Davis, Modern Programming Made Easy,
https://doi.org/10.1007/978-1-4842-5569-8_1
Chapter 1 Introduction

Programming is fraught with trial and error. Although things will get
easier over time, you’ll never be right all the time. So, much as with most
things in life, you must be patient, diligent, and curious to be successful.

About This Book


This book is organized into several chapters, beginning with the most basic
concepts. If you already understand a concept, you can safely move ahead
to the next chapter. Although this book concentrates on Java, it also refers
to other languages, such as Groovy, Scala, and JavaScript, so you will gain a
deeper understanding of concepts common to all programming languages.

Tips Text styled like this provides additional information that


you may find helpful.

Info Text styled this way usually refers the curious reader to
additional information.

Warnings Text such as this cautions the wary reader. Many


have fallen along the path of computer programming.

Exercises This is an exercise. We learn best by doing, so it’s


important that you try these out.

2
CHAPTER 2

Software to Install
Before you begin to program, you must install some basic tools.

J ava/Groovy
For Java and Groovy, you will have to install the following:

• JDK (Java Development Kit), such as OpenJDK 11. You


can install OpenJDK by following the instructions at
adoptopenjdk.net.1
• IDE (Integrated Development Environment), such as
NetBeans 11.

• Groovy: A dynamic language similar to Java that runs


on the JVM (Java Virtual Machine).

1
https://adoptopenjdk.net/installation.html
© Adam L. Davis 2020 3
A. L. Davis, Modern Programming Made Easy,
https://doi.org/10.1007/978-1-4842-5569-8_2
Chapter 2 Software to Install

Install Java and NetBeans 11 or higher. Download and install the


Java JDK and NetBeans.2 Open NetBeans and select File ➤ New
Project… ➤ Java with Gradle, Java Application. When asked, provide
the group “test,” version “0.1,” and package such as “com.
gradleproject1”. Click “Finish,” then “OK.”
Install Groovy: Go to the Groovy web site and install Groovy.3

Trying It Out
After installing Groovy, you should use it to try coding. Open a command
prompt (or terminal), type groovyConsole, and hit Enter to begin.

In groovyConsole, type the following and then hit Ctrl+r to run


the code.
1 print “hello”

Because most Java code is valid Groovy code, you should keep the
Groovy console open and use it to try out all of the examples from this
book.
You can also easily try out JavaScript in the following way:

• Just open your web browser and go to jsfiddle.net.

2
h ttps://netbeans.apache.org/download/index.html
3
https://groovy.apache.org/download.html

4
Chapter 2 Software to Install

O
 thers
Once you have the preceding installed, you should eventually install the
following:
• Scala4: An object-oriented language built on the JVM
• Git5: A version control program

• Maven6: A modular build tool

Go ahead and install these, if you’re in the mood. I’ll wait.


To try out Scala, type scala in your command prompt or terminal once
you have installed it.

C
 ode on GitHub
A lot of the code from this book is available on github.com/modernprog.7
You can go there at any time to follow along with the book.

4
w ww.scala-lang.org/
5
https://git-scm.com/
6
https://maven.apache.org/
7
https://github.com/modernprog

5
CHAPTER 3

The Basics
In this chapter, we’ll cover the basic syntax of Java and similar languages.

C
 oding Terms
Source file refers to human-readable code. Binary file refers to computer-­
readable code (the compiled code). In Java, this binary code is called
bytecode which is read by the Java Virtual Machine (JVM).
In Java, the source files end with .java, and binary files end with
.class (also called class files). You compile source files using a compiler,
which gives you binary files or bytecode.
In Java, the compiler is called javac; in Groovy it is groovyc; and it is
scalac in Scala (see a trend here?). All three of these languages can be
compiled to bytecode and run on the JVM. The bytecode is a common
format regardless of which programming language it was generated from.
However, some languages, such as JavaScript, don’t have to be
compiled. These are called interpreted languages. JavaScript can run in
your browser (such as Firefox or Google Chrome), or it can run on a server
using Node.js, a JavaScript runtime built on Chrome’s V8 JavaScript engine.

© Adam L. Davis 2020 7


A. L. Davis, Modern Programming Made Easy,
https://doi.org/10.1007/978-1-4842-5569-8_3
Chapter 3 The Basics

Primitives and Reference


Primitive types in Java refer to different ways to store numbers and have
practical significance. The following primitives exist in Java:
• char: A single character, such as A (the letter A).

• byte: A number from -128 to 127 (8 bits1). Typically, a


way to store or transmit raw data.

• short: A 16 bits signed integer. It has a maximum of


about 32,000.

• int: A 32 bits signed integer. Its maximum is about 2 to


the 31st power.

• long: A 64 bits signed integer. Maximum of 2 to the 63rd


power.

• float: A 32 bits floating-point number. This format


stores fractions in base two and does not translate
directly to base ten numbers (how numbers are usually
written). It can be used for things such as simulations.

• double: Like float but with 64 bits.


• boolean: Has only two possible values: true and false
(much like 1 bit).

See Java Tutorial—Data Types2 for more information.

1
 bit is the smallest possible amount of information. It corresponds to a 1 or 0.
A
2
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.
html

8
Chapter 3 The Basics

GROOVY, SCALA, AND JAVASCRIPT

Groovy types are much the same as Java’s. In Scala, everything is an object,
so primitives don’t exist. However, they are replaced with corresponding value
types (Int, Long, etc.). JavaScript has only one type of number, Number,
which is similar to Java’s float.

A variable is a value in memory referred to by a name. In Java you can


declare a variable as a primitive by writing the type then any valid name.
For example, to create an integer named price with an initial value of 100,
write the following:

1  int price = 100;

Every other type of variable in Java is a reference. It points to some


object in memory. This will be covered later on.
In Java, each primitive type also has a corresponding class type: Byte
for byte, Integer for int, Long for long, and so on. Using the class type
allows the variable to be null (meaning no value). However, using the
primitive type can have better performance when handling a lot of values.
Java can automatically wrap and unwrap primitives in their corresponding
classes (this is called boxing and unboxing).

Strings/Declarations
A String is a list of characters (text). It is a very useful built-in class in Java
(and most languages). To define a string, you simply surround some text in
quotes. For example:

1   String hello = "Hello World!";

Here the variable hello is assigned the string "Hello World!".

9
Chapter 3 The Basics

In Java, you must put the type of the variable in the declaration. That’s
why the first word here is String.
In Groovy and JavaScript, strings can also be surrounded by single
quotes ('hello'). Also, declaring variables is different in each language.
Groovy allows you to use the keyword def, while JavaScript and Scala use
var. Java 10 also introduced using var to define local variables. For example:

1   def hello = "Hello Groovy!" //groovy


2   var hello = "Hello Scala/JS!" //Scala or JS

Statements
Almost every statement in Java must end in a semicolon (;). In many
other languages, such as Scala, Groovy, and JavaScript, the semicolon is
optional, but in Java, it is necessary. Much as how periods at the end of
each sentence help you to understand the written word, the semicolon
helps the compiler understand the code.
By convention, we usually put each statement on its own line, but this
is not required, as long as semicolons are used to separate each statement.

Assignment
Assignment is an extremely important concept to understand, but it can
be difficult for beginners. However, once you understand it, you will forget
how hard it was to learn.
Let’s start with a metaphor. Imagine you want to hide something
valuable, such as a gold coin. You put it in a safe place and write the
address on a piece of paper. This paper is like a reference to the gold. You
can pass it around and even make copies of it, but the gold remains in the
same place and does not get copied. On the other hand, anyone with the
reference to the gold can get to it. This is how a reference variable works.

10
Chapter 3 The Basics

Let’s look at an example:

1   String gold = "Au";


2   String a = gold;
3   String b = a;
4   b = "Br";

After running the preceding code, gold and a refer to the string "Au",
while b refers to "Br".

Class and Object


A class is the basic building block of code in object-oriented languages.
A class typically defines state and behavior. The following class is named
SmallClass:

1   package com.example.mpme;
2   public class  SmallClass  {
3   }

Class names always begin with an uppercase letter in Java. It’s


common practice to use CamelCase to construct the names. This means
that instead of using spaces (or anything else) to separate words, we
uppercase the first letter of each word.
The first line is the package of the class. A package is like a directory on
the file system. In fact, in Java, the package must actually match the path
to the Java source file. So, the preceding class would be located in the path
com/example/mpme/ in the source file system. Packages help to organize
code and allow multiple classes to have the same name as long as they are
in different packages.
An object is an instance of a class in memory. Because a class can have
multiple values within it, an instance of a class will store those values.

11
Chapter 3 The Basics

Create a Class

• Open your IDE (NetBeans).


• Note the common organizational structure of a typical
Java project in the file system:
• src/main/java: Java classes
• src/main/resources: Non-Java resources
• src/test/java: Java test classes
• src/test/resources: Non-Java test resources
• Right-click your Java project and choose New ➤
Java Class. Under “Class-Name” put “SmallClass”.
Put “com.example.mpme” for the package name.

Fields, Properties, and Methods


Next you might want to add some properties and methods to your class.
A field is a value associated with a particular value or object. A property is
essentially a field which has a “getter” or “setter” or both (a getter gets the
value and a setter sets the value of a property). A method is a block of code
on a class which can be called later on (it doesn’t do anything until called).

1   package  com.example.mpme;
2   public  class  SmallClass  {
3       String name; //field
4       String getName() {return  name;} //getter
5       void print() {System.out.println(name);} //method
6   }

12
Chapter 3 The Basics

In the preceding code, name is a property, getName is a special method


called a getter, and print is a method which does not return anything (this
is what void means). Here, name is defined to be a String. System.out is
built into the JDK and links to “standard out” which we discuss later, and
println prints text and appends a newline to the output.
Methods can have parameters (values passed into the method), modify
fields of the class, and can have return values (a value returned by the
method) using the return statement. For example, modify the preceding
method, print, to the following:

1   public String print(String value) {


2     name = "you gave me " + value;
3     System.out.println(name);
4     return name;
5   }

This method changes the name field, prints out the new value, and
then returns that value. Try this new method out in the groovyConsole by
defining the class and then executing the following:

1  new SmallClass().print("you gave me dragons")

Groovy Classes
Groovy is extremely similar to Java but always defaults to public (we will
cover what public means in a later chapter).

1   package com.example.mpme;
2   class SmallClass {
3       String name //property
4       def print() { println(name) } //method
5   }

13
Chapter 3 The Basics

Groovy also automatically gives you “getter” and “setter” methods for
properties, so writing the getName method would have been redundant.

JavaScript Prototypes
Although JavaScript has objects, it doesn’t have a class keyword (prior to
ECMAScript 2015). Instead, it uses a concept called prototype. For example,
creating a class can look like the following:

1   function SmallClass() {}
2   SmallClass.prototype.name = "name"
3   SmallClass.prototype.print = function() { console.log(this.
name) }

Here name is a property and print is a method.

Scala Classes
Scala has a very concise syntax, which puts the properties of a class in
parentheses. Also, types come after the name and a colon. For example:

1   class SmallClass(var name:String) {


2       def  print =  println(name)
3   }

Creating a New Object


In all four languages, creating a new object uses the new keyword. For
example:

1   sc = new  SmallClass();

14
Chapter 3 The Basics

Comments
As a human, it is sometimes useful for you to leave notes in your source
code for other humans—and even for yourself, later. We call these notes
comments. You write comments thus:

1   String gold = "Au"; // this is a comment


2   String a = gold; // a is now "Au"
3   String b = a; // b is now  "Au"
4   b = "Br";
5   /* b is now "Br".
6      this is still a comment */

Those last two lines demonstrate multiline comments. So, in summary:

• Two forward slashes denote the start of a single-line


comment.

• Slash-asterisk marks the beginning of a multiline


comment.

• Asterisk-slash marks the end of a multiline comment.

Comments are the same in all languages covered in this book.

Summary
In this chapter, you learned the basic concepts of programming:
• Compiling source files into binary files
• How objects are instances of classes
• Primitive types, references, and strings
• Fields, methods, and properties
• Variable assignment
• How source code comments work

15
Another Random Document on
Scribd Without Any Related Topics
The interior of the optical box at the Polytechnic—looking towards the
screen. The assistants are supposed to be showing the dissolving views.
CHAPTER XXI.
LIGHT, OPTICS, AND OPTICAL INSTRUMENTS.

Fig. 246.
"The moon shines bright:—In such a night as this."—The Merchant of Venice.

"To gild refined gold, to paint the lily,


To throw a perfume on the violet,
To smooth the ice, or add another hue
Unto the rainbow, or with taper light
To seek the beauteous eye of heaven to garnish,
Is wasteful and ridiculous excess."
Perfection admits of no addition, and it is just this feeling that might
check the most eloquent speaker or brilliant writer who attempted to
offer in appropriate language, the praises due to that first great
creation of the Almighty, when the Spirit of God moved upon the face
of the waters and said, "Let there be light." If any poet might be
permitted to laud and glorify this transcendant gift, it should be the
inspired Milton; who having enjoyed the blessing of light, and
witnessed the varied and beautiful phenomena that accompany it,
could, when afflicted by blindness, speak rapturously of its creation, in
those sublime strains beginning with—
"'Let there be light,' said God, and forthwith light
Ethereal, first of things, quintessence pure,
Sprung from the deep: and from her native east
To journey through the airy gloom began,
Sphered in a radiant cloud, for yet the sun
Was not; she in a cloudy tabernacle
Sojourn'd the while. God saw the light was good,
And light from darkness by the hemisphere
Divided: light the day, and darkness night,
He named."
There cannot be a more glorious theme for the poet, than the vast
utility of light, or a more sublime spectacle, than the varied and
beautiful phenomena that accompany it. Ever since the divine
command went forth, has the sun continued to shine, and to remain,
"till time shall be no more," the great source of light to the world, to be
the means of disclosing to the eye of man all the beautiful and varied
hues of the organic and inorganic world. By the help of light we enjoy
the prismatic colours of the rainbow, the lovely and ever changing and
ever varied tints of the forest trees, the flowers, the birds, and the
insects; the different forms of the clouds, the lovely blue sky, the
refreshing green fields; or even the graceful adornment of "the fair,"
their beautiful dresses of exquisite patterns and colours. Light works
insensibly, and at all seasons, in promoting marvellous chemical
changes, and is now fairly engaged and used for man's industrial
purposes, in the pleasing art of photography; just as heat, electricity,
and magnetism, (all imponderable and invisible agents,) are employed
usefully in other ways.
The sources from whence light is derived are six in number. The first is
the sun, overwhelming us with its size, and destroying life, sometimes,
with his intense heat and light, when the piercing rays are not
obstructed by the friendly clouds and vapours, which temper and
mitigate their intensity, and prevent the too frequent recurrence of that
quick and dire enemy to man, the coup de soleil.
The body of the sun is supposed to be a habitable globe like our own,
and the heat and light are possibly thrown out from one of the
atmospheric strata surrounding it. There are probably three of these
strata, the one believed to envelope the body of the sun, and to be
directly in contact with it, is called the cloudy stratum; next to, and
above this, is the luminous stratum, and this is supposed to be the
source of heat and light; the third and last envelope is of a transparent
gaseous nature. These ideas have originated from astronomers who
have carefully watched the sun and discovered the presence of certain
black spots called Maculæ, which vary in diameter from a few hundreds
of miles to 40 or 50,000 miles and upwards. There is also a greyish
shade surrounding the black spots called the Penumbra, and likewise
other spots of a more luminous character termed Faculæ; indeed the
whole disc of the sun has a mottled appearance, and is stippled over
with minute shady dots. The cause of this is explained by supposing
that these various spots represent openings or breaks in the
atmospheric strata, through which the black body of the sun is
apparent or other portions of the three strata, just as if a black ball was
covered with red, then with yellow, and finally with blue silk: on cutting
through the blue the yellow is apparent; by snipping out pieces of the
blue and yellow, the red becomes visible; and by slicing away a portion
of the three silk coverings the black ball at last comes into view. On a
similar principle it is supposed that the variety of spots and eruptions
on the sun's face or disc may be explained. The evolution of light is
not, however, confined to the sun, and it emanates freely from
terrestrial matter by mechanical action, either by friction, or in some
cases by mere percussion. Thus the axles of railway carriages soon
become red hot by friction if the oil holes are stopped up; indeed hot
axles are very frequent in railway travelling, and when this happens, a
strong smell of burning oil is apparent, and flames come out of the axle
box. The knife-grinder offers a familiar example of the production of
light by the attrition of iron or steel against his dry grindstone.
The same result on a much grander scale is produced by the apparatus
invented by the late Jacob Perkins; the combustion of steel ensues
under the action, viz., the friction of a soft iron disc revolving with
great velocity against a file or other convenient piece of hardened
steel. (Fig. 247)

Fig. 247.
Instrument for the combustion of steel.

The stand has a disc of soft iron fixed upon an axis, which revolves on
two anti-friction wheels of brass. The disc, by means of a belt worked
over a wheel immediately below it, is made to perform 5000
revolutions per minute. If the hardest file is pressed against the edge
of the revolving disc, the velocity of the latter produces sufficient heat
by the great friction to melt that portion of the file which is brought in
contact with it, whilst some particles of the file are torn away with
violence, and being projected into the air, burn with that beautiful
effect so peculiar to steel. If the experiment is performed in a darkened
room, the periphery of the revolving disc will be observed to have
attained a luminous red heat. Thirty years ago every house was
provided with a "tinder-box" and matches to "strike a light." Since the
advent of prometheans and lucifers, the flint and steel, the tinder, and
the matches dipped in sulphur, have all disappeared, and now the box
might be deposited in any antiquarian museum under the portrait of
Guy Fawkes, and labelled, "an instrument for procuring a light,
extensively used in the early part of the nineteenth century." (Fig. 248.)

Fig. 248.
c. The steel. b. The flint. e. The tinder. d. The matches of the old-
fashioned tinder-box, a.

The rubbing of a piece of wood (hardened by fire, and cut to a point)


against another and softer kind, has been used from time immemorial
by savage nations to evoke heat and light; the wood is revolved in the
fashion of a drill with unerring dexterity by the hands of the savage,
and being surrounded with light chips, and gently aided by the breath,
the latent fire is by great and incessant labour at last procured. How
favourably the modern lucifers compare with these laborious efforts of
barbarous tribes! a child may now procure a light with a chemically
prepared metal, and great merit is due to that person who first devised
a method of mixing together phosphorus and chlorate of potash and so
adjusted these dangerous materials that they are as safe as the "old
tinder-box," and have now become one of our domestic necessaries.
Ignition, or the increase of heat in a solid body, is another source of
light, and is well illustrated in the production of illuminating power from
the combustion of tallow, oil, wax, camphine or coal gas. The term
ignition is derived from the Latin (ignis, fire), and is quite distinct, and
has a totally different meaning from that of combustion. If a glass jar is
filled with carbonic acid gas, and a little tray placed in it containing
some gun cotton, it will be found impossible to fire the latter with a
lighted taper, i.e. by combustion (comburo, to burn), because the gas
extinguishes flame which is dependent on a supply of oxygen; whereas
if a copper or other metallic wire is made red hot or ignited, the
carbonic acid has no effect upon the heat, and the red hot wire being
passed through the gas, the gun cotton is immediately fired.
Flame consists of three parts—viz., of an outer film, which comes
directly in contact with the air, and has little or no luminosity; also of a
second film, where carbon is deposited, and, first by ignition, and
finally by combustion, produces the light; and thirdly, of an interior
space containing unburnt gas, which is, as it were, waiting its turn to
reach the external air, and to be consumed in the ordinary manner.
(Fig. 249.)

Fig. 249.
A candle flame. 1. Outer flame. 2. Inner flame, which is badly supplied
with oxygen, and where the carbon is deposited and ignited. 3. The
interior, containing unburnt gas.

Chemical action and electricity have been so frequently mentioned in


this work as a source of heat and light, that it will be unnecessary to
do more than to mention them here, whilst phosphorescence (the sixth
source of light) in dead and living matter, a spontaneous production of
light, is well known and exemplified in the "glow-worm," the "fire-fly,"
the luminosity of the water of the ocean, or the decomposing remains
of certain fish, and even of human bodies. Phosphorescence is still
more curiously exemplified by holding a sheet of white paper, a
calcined oyster-shell, or even the hand, in the sun's rays, and then
retiring quickly to a darkened room, when they appear to be luminous,
and visible even after the light has ceased to fall upon them.
For the purpose of examining the temporary phosphorescence of
various bodies, M. Becquerel has invented a most ingenious
instrument, called the "phosphorescope." It consists of a cylinder of
wood one inch in diameter and seven inches long, placed in the angle
of a black box with the electric lamp inside, so that three-fourths of the
cylinder are visible outside, and the remaining fourth exposed to the
interior electric light.
By means of proper wheels the cylinder, covered with any substance
(such as Becquerel's phosphori), is made to revolve 300 times in a
second, and by using this or a lesser velocity, the various phosphori are
first exposed to a powerful light and then brought in view of the
spectator outside the box.
It is understood that light is produced by an emanation of rays from a
luminous body. If a stone is thrown from the hand, an arrow shot from
a bow, or a ball from a cannon, we perfectly understand how either of
them may be propelled a certain distance, and why they may travel
through space; but when we hear that light travels from the sun, which
is ninety-five millions of miles away from the earth, in about seven
minutes and a half, it is interesting to know what is the kind of force
that propels the light through that vast distance, and also what is
supposed to be the nature of the light itself.
There are two theories by which the nature of light, and its
propagation through space, are explained; they are named after the
celebrated men who proposed them, as also from the theoretical
mechanism of their respective modes of propulsion: thus we have the
Newtonian or corpuscular theory of light, and the Huyghenian or
undulatory theory; the first named after Sir Isaac Newton, and the
second after Huyghens, another most learned mathematician. Many
years before Newton made his grand discovery of the composition of
light in the year 1672, mathematicians were in favour of the undulatory
theory, and it numbered amongst its supporters not only Huyghens,
but Descartes, Hook, Malebranche, and other learned men. Mankind
has always been glad to follow renowned leaders, it is so much easier,
and is in most cases perhaps the better course, to resign individual
opinion when more learned men than ourselves not only adopt but
insist upon the truth of their theories; and this was the case with the
corpuscular theory, which had been written upon systematically and
supported by Empedocles, a philosopher of Agrigentum in Sicily, who
lived some 444 years before the Christian era, and is said to have been
most learned and eloquent; he maintained that light consisted of
particles projected from luminous bodies, and that vision was
performed both by the effect of these particles on the eye, and by
means of a visual influence emitted by the eye itself. In course of time,
and at least 2000 years after this theory was advanced, philosophers
had gradually rejected the corpuscular theory, until the great Newton,
about the middle of the seventeenth century, advanced as a champion
to the rescue, and stamping the hypothesis with his approval, at once
led away the whole army of philosophers in its favour, so that till about
the beginning of the nineteenth century the whole of the phenomena
of light were explained upon this hypothesis.
The corpuscular theory, reduced to the briefest definition, supposes
light to be really a material agent, and requires the student to believe
that this agent consists of particles so inconceivably minute that they
could not be weighed, and of course do not gravitate; the corpuscles
are supposed to be given out bodily (like sparks of burning steel from a
gerb firework) from the sun, the fixed stars, and all luminous bodies; to
travel with enormous velocity, and therefore to possess the property of
inertia; and to excite the sensation of vision by striking bodily upon the
expanded nerve, the retina, the quasi-mind of the eye. Dr. Young
remarks, "that according to this projectile theory the force employed in
the free emission of light must be about a million million times as great
as the force of gravity at the earth's surface, and it must either act with
equal intensity on all the particles of light, or must impel some of them
through a greater space than others, if its action be more powerful,
since the velocity is the same in all cases—for example, if the projectile
force is weaker with respect to red light than with respect to violet
light, it must continue its action on the red rays to a greater distance
than on the violet rays. There is no instance in nature besides of a
simple projectile moving with a velocity uniform in all cases, whatever
may be its cause; and it is extremely difficult to imagine that such an
immense force of repulsion can reside in all substances capable of
becoming luminous, so that the light of decaying wood, or two pebbles
rubbed together, may be projected precisely with the same velocity as
the light emitted by iron burning in oxygen gas, or by the reservoir of
liquid fire on the surface of the sun." Now one of the most striking
circumstances respecting the propagation of light, is the uniformity of
its velocity in the same medium. These and other difficulties in the
application of the corpuscular theory aroused the attention of the late
Dr. Young, and in the year 1801 he again revived and supported the
neglected undulatory theory with such great ability that the attention of
many learned mathematicians was directed to the subject, and now it
may be said that the corpuscular theory is almost, if not entirely,
rejected, whilst the undulatory theory is once more, and deservedly,
used to explain the theory of light, and its propagation through space.
By this hypothesis it is assumed that the whole universe, including the
most minute pores of all matter, whether solid, fluid, or gaseous, are
filled with a highly elastic rare medium of a most attenuated nature,
called ether, possessing the property of inertia but not of gravitation.
This ether is not light, but light is produced in it by the excitation on
the part of luminous bodies of a vibratory motion, similar to the
undulation of water that produces waves, or the vibration of air
affording sound. Water set in motion produces waves. Air set in motion
produces waves of sound. Ether, i.e. the theoretical ether pervading all
matter, likewise set in motion, produces light. The nature of a vibratory
medium is indeed better understood by reference to that which we
know possesses the ordinary properties of matter—viz., the air; and by
tracing out the analogy between the propagation of sound and light,
the difficulties of the undulatory theory very quickly vanish. To illustrate
vibration it is only necessary to procure a finger glass, and having
supported a little ebony ball attached to a silk thread by a bent brass
wire directly over it, so that the ball may touch either the outside or the
inside of the glass, attention must be directed to the quiescence of the
ball when a violin bow is lightly moved over the edge of the glass
without producing sound, and to the contrary effect obtained by so
moving and pressing the bow that a sharp sound is emitted, when
immediately the little ball is thrown off from the edge, the repulsive
action being continued as long as the sound is produced by the
vibration of the glass. (Fig. 250.)

Fig. 250.
a.The finger glass. b. The violin bow. c. The ebony ball. The dotted ball
shows how it is repelled during the vibration of the glass.

Here the vibrations are first set up in the glass, and being
communicated to the surrounding air, a sound is produced; if the same
experiment could be performed in a vacuum, the glass might be
vibrated, but not being surrounded with air, no sound would be
produced. This fact is proved by first ringing a bell with proper
mechanism fixed under the receiver placed on the air-pump plate; the
sound of the bell is audible until the pump is put in motion and the
receiver gradually exhausted, when the ringing noise becomes fainter
and fainter, until it is perfectly inaudible. This experiment is made more
instructive by gradually admitting the air again into the exhausted
vessel, and at the same time ringing the bell, when the sound becomes
gradually louder, until it attains its full power. The sun and other
luminous bodies may be compared to the finger glass, and are
supposed to be endowed naturally with a vibratory motion (a sort of
perpetual ague), only instead of the air being set in motion, the ether
is supposed to be thrown into waves, which travel through space, and
convey the impression of light from the luminous object. Another
familiar example of an undulatory medium is shown by throwing a
stone into a pool of water; the former immediately forces down and
displaces a certain number of the particles of the latter, consequently
the surrounding molecules of water are heaped up above their level; by
the force of gravitation they again descend and throw up another
wave, this in subsiding raises another, until the force of the original and
loftier wave dies away at the edge of the pool into the faintest ripples.
It must however be understood that it is not the particles of water first
set in motion that travel and spread out in concentric circles; but the
force is propagated by the rising and falling of each separate particle of
water as it is disturbed by the momentum of the descending wave
before it. When standing at a pier-head, or on a rock against which the
sea dashes, it is usual to hear the observer cry out, if the weather is
stormy and the waves very high, "Oh! here comes a great wave!" as if
the water travelled bodily from the spot where it was first noticed,
whereas it is simply the force that travels, and is exerted finally on the
water nearest the rock. It is in fact a progressive action, just as the
wind sweeps over a wide field of corn, and bends down the ears one
after the other, giving them for the time the appearance of waves. The
principle of successive action is well shown by placing a number of
billiard balls in a row, and touching each other; if the first is struck the
motion is communicated through the rest, which remain immovable,
whilst the last only flies out of its place. The force travels through all
the balls, which simply act as carriers, their motion is limited, and the
last only changes its position. Progressive movement is also well
displayed by arranging six or eight magnetized needles on points in a
row, with all their north poles in one direction. (Fig. 252.)
Fig. 251.
Boy throwing stones into water and producing circular waves.

Fig. 252.
a b.Series of needles arranged as described. c. The bar magnet, with the
north pole n towards the needles. The dotted lines show the direction
gradually assumed by all the needles, commencing at d.

On approaching the north pole of a bar magnet to the same pole of


one end of the series of needles, it is very curious to see them turn in
the opposite direction progressively, one after the other, as the
repulsive power of the bar magnet gradually operates upon the similar
poles in the magnetic needles. The undulations of the waves of water
are also perfectly shown by using the apparatus consisting of the
trough with the glass bottom and screen above it, as described at page
10. The transmission of vibrations from one place to another is also
admirably displayed in Professor Wheatstone's Telephonic Concert (see
page picture), where the musical instruments, as at the Polytechnic,
were placed by the author in the basement, and the vibration only
conducted by wooden rods to the sounding-boards above, so that the
music was laid on like gas or water. These vibrations or undulations in
air, water, and the theoretical ether, have therefore been called waves
of water, waves of sound, and waves of light, just as if three clocks
were made of three different metals, the mechanism would remain the
same, though the material, or in this case the medium, be different in
each.
Any increase in the number of vibrations of the air produces acute,
whilst a decrease attends the grave sounds, and when the waves
succeed each other not less than sixteen times in a second, the lowest
sound is produced. Light and colours are supposed to be due to a
similar cause, and in order to produce the red ray, no less than 477
millions of millions of vibrations must occur in a second of time; the
orange, 506; yellow, 535; green, 577; blue, 622; indigo, 658; violet,
699; and white light, which is made up of these colours, numbers 541
millions of millions of undulations in a second.
Although light travels with such amazing rapidity, there is of course a
certain time occupied in its passage through space—there is no such
thing as instantaneity in nature. A certain period of time, however
small, must elapse in the performance of any act whatever, and it has
been proved by a careful observation of the time at which the eclipses
of the satellites of Jupiter are perceived, that light travels at the rate of
192,500 miles per second, and by the aberration of the fixed stars,
191,515, the mean of these two sets of observations would probably
afford the correct rate. Such a velocity is, however, somewhat difficult
to appreciate, and therefore, to assist our comprehension of their great
magnitude, Sir J. Herschel has given some very interesting comparative
calculations, and coming from such an authority we can readily believe
them to be correct.
"A cannon-ball moving uniformly at its greatest velocity would require
seventeen years to reach the sun. Light performs the same distance in
about seven minutes and a half.
"The swiftest bird, at its utmost speed, would require nearly three
weeks to make the tour of the earth, supposing it could proceed
without stopping to take food or rest. Light performs the same distance
in less time than is required for a single stroke of its wing."
Dismissing for the present the theory of undulations, it will be
necessary to examine the phenomena of light, regarding it as radiant
matter, without reference to either of the contending theories.
Light issues from the sun, passes through millions of miles to the earth,
and as it falls upon different substances, a variety of effects are
apparent. There is a certain class of bodies which obstruct the passage
of the rays of light, and where light is not, a shadow is cast, and the
substance producing the shadow is said to be opaque. Wood, stone,
the metals, charcoal, are all examples of opacity; whilst glass, talc, and
horn allow a certain number of the rays to travel through their
particles, and are therefore called transparent. Nature, however, never
indulges in sudden extremes, and as no substance is so opaque as not
(when reduced in thickness) to allow a certain amount of light to pass
through its substance, so, on the other hand, however transparent a
body may be, a greater or lesser number of the rays are always
stopped, and hence opacity and transparency are regarded as two
extremes of a long chain; being connected together by numerous
intermediate links, they pass by insensible gradations the one into the
other.
If a gold leaf, which is about the one two-hundredth part of an inch in
thickness, is fixed on a glass plate and held before a light, a green
colour is apparent, the gold appearing like a green, semi-transparent
substance. When plates of glass are laid one above the other, and the
flame of a candle observed through them, the light decreases
enormously as the number of glass-plates are increased. Even in the
air a considerable portion of light is intercepted. It has been estimated
that of the horizontal sunbeams passing through about two hundred
miles of air, one two-thousandth part only reaches us, and that no
sensible light can penetrate more than seven hundred feet deep into
the sea; consequently, the vast depths discovered in laying the Atlantic
telegraph must be in absolute darkness.
Light is thrown out on all sides from a luminous body like the spokes of
a cart-wheel, and in the absence of any obstruction, the rays are
distributed equally on all sides, diverging like the radii drawn from the
centre of a circle. As a natural consequence arising from the divergence
of each ray from the other, the intensity of light decreases as the
distance from the luminous source increases, and vice versâ. Perhaps
the best mechanical notion of this law is afforded by an ordinary fan;
the point from which the sticks radiate, and where they all meet, may
be termed the light; the sticks are the rays proceeding from it. (Fig.
253.)
The fan is held in one hand, and the first
finger of the other can be made to touch all
the sticks if placed sufficiently near to A; and
supposing the sticks are called rays of light,
the intensity must be great at that point,
because all the rays fall upon it; but if the
finger is removed towards the outer edge—
viz., to b, it now only touches some three or
four sticks; and pursuing the analogy, a very
few rays fall upon that point—hence the light
has decreased in intensity, or to speak
correctly, "Light decreases inversely as the
squares of the distance." This law has already
been illustrated at page 13; and as an
experiment, the rays from the oxy-hydrogen
lantern may be permitted to pass out of a
Fig. 253. square hole (say two inches square), and
should be thrown on to a transparent screen
divided into squares by dark lines, so that the light at a certain distance
illuminates one of them; then it will be found that at twice the
distance, four may be illuminated, at three times nine, and so on. (Fig.
254.)
Fig. 254.
Lantern at the three distances from the transparent screen, which is
divided into nine equal squares.

Upon this law is based the use of photometers, or instruments for


measuring light, and supposing it was required to estimate roughly the
illuminating power of any lamp, as compared with the light of a wax
candle six to the pound, the experiment should be conducted in a dark
room, from which every other light but that from the lamp and candle
under examination must be excluded.
The lamp, with the chimney only, is now placed say twelve feet from
the wall, and a stick or rod is placed upright and about two inches from
the latter, so that a shadow is cast on the wall; if the candle is now
lighted and allowed to burn up properly, two shadows of the stick will
be apparent, the one from the lamp being black and distinct, and the
other from the candle extremely faint, until it is approached nearer the
wall—say to within three feet—when the two shadows may be now
equal in blackness. (Fig. 255.) After this is apparent to one or more
persons, the distances of the lamp and candle from the wall are
carefully measured, and being squared, and the greater divided by the
lesser number, the quotient gives the illuminating power. For example:

The lamp was 12 feet from the wall 12 × 12 = 144.


The candle was 3 feet " 3 × 3 = 9.
9) 144
————
16
Therefore the illuminating power of the lamp is equal to 16 wax
candles six to the pound.

Fig. 255.
a.The lamp. b. The candle. c. The rod throwing the two shadows,
marked d and e, on a white wall or a sheet of paper.

There are other and more refined means of working out the same fact,
but for a rough approximation to the truth, the plan already described
will answer very fairly.
A most amusing effect can be produced on the principle that every
light casts its own shadow, called the "dance of death," or the "dance
of the witches;" either of these agreeable subjects are drawn, and the
outlines cut out of a sheet of cardboard. If a wet sheet is stretched or
hung on one side of a pair of folding doors partly open, and between
which the cardboard is tacked up, and the space left at the top and
bottom closed with a dark cloth, directly the room before the sheet is
darkened and a lighted candle held behind the figure cut out in the
cardboard, one shadow or image is thrown upon the sheet, and these
shadows may be increased according to the number of candles used,
and if they are held by two or three persons, and moved up and down,
or sideways, the shadows follow the direction of the candles, and
present the appearance of a dance. (Fig. 256.)

Fig. 256.
"Before the curtain."

Fig. 257.
"Behind the curtain."

Another very comic effect of shadow is that called "jumping up to the


ceiling," and when carried out on a large scale by the author on an
enormous sheet suspended in the centre transept of the Crystal Palace,
Sydenham, it had a most laughable effect, and caused the greatest
amusement to the children of all ages. (Fig. 258.)
Fig. 258.
The laughable effect of the shadows at the
Crystal Palace.

This very telling result is produced by placing an oxy-hydrogen light


some feet behind a large sheet, and of course if any one passes
between the two a shadow of the individual is cast upon the sheet,
then by walking towards the light the figure diminishes in size, and by
jumping over it the shadow appears to go up to the ceiling, and to
come down when the jump is made in the opposite direction over the
light and towards the sheet. The rationale of this experiment is very
simple, and is another proof of the distribution of light from a luminous
source being in every direction. By jumping over the light the radii
projected from the candle over the sheet are crossed, and the shadow
rises or falls as the figure passes upwards or downward. (Fig. 259.)
Fig. 259.
The rays of light marked a b c d e proceeding from a lighted candle or
oxy-hydrogen light. The arrow pointing to the right shows how these
rays are crossed in jumping up to the ceiling; and the second arrow,
pointing to the left, shows the reverse.

A beam of light is defined to be a collection of rays, and it is a


convenient definition, because it prevents confusion to speak only of
one ray in attempting to explain how light is disposed of under peculiar
circumstances.
The smallest portion of light which it is supposed can be separated is
therefore called a ray, and it will pass through any medium of the same
density in a perfectly straight line; but if it passes out of that medium
into another of a different density, or into any other solid, fluid, or
gaseous matter, it may be disposed of in four different ways, being
either reflected, refracted, polarized, or absorbed.
The reflection of light is the first property that will be considered, and it
will be found that every substance in nature possesses in a greater or
lesser degree the power of throwing off the rays of light which fall
upon them. Thus if we go into a room perfectly darkened, containing
every kind of work produced by nature or art, such as flowers, birds,
boxes of insects, rich carpets, hangings, pictures, statuary, jewellery,
&c., they cannot excite any pleasure because they are invisible, but
directly a lighted lamp is brought into the chamber, then the rays fall
upon all the surrounding objects, and being reflected from their
surfaces enter the eye, and there produce the phenomena of vision.
This connexion between luminous and non-luminous bodies becomes
very apparent when we consider that the sun would appear only as an
intense light in a dark background, if the earth was not surrounded
with the various strata of air, in which are placed clouds and vapours
that collectively reflect and scatter the light, so as to cause it to be
endurable to vision. It is when the sky is very clear during July or
August that the heat becomes so intense, directly clouds begin to form
and float about, the heat is then moderated.
Many years ago, Baron Alexander Funk, visiting some silver mines in
Sweden, observed, that in a clear day it was as dark as pitch
underground in the eye of the pit at sixty or seventy fathoms deep;
whereas, on a cloudy or rainy day he could even see to read at 106
fathoms deep. Inquiring of the miners, he was informed that this is
always the case, and reflecting upon it he imagined very properly that
it arose from this circumstance—that when the atmosphere is full of
clouds, light is reflected from them into the pit in all directions, so that
thereby a considerable proportion of the rays are reflected
perpendicularly upon the earth; whereas when the atmosphere is clear
there are no opaque bodies to reflect the light in this manner, at least,
in a sufficient quantity, and rays from the sun itself can never fall
perpendicularly in Sweden. The use of reflecting surfaces has now
become quite common in all crowded cities, and especially in London,
where even the rays of light are too few to be lost, and flat or
corrugated mirrors are placed at various angles, either to throw the
light from the outside on the white-washed ceiling within, and thus
obtain a better diffused light through the apartment, or it is reflected
bodily to some back room, or rather dark brick box, where perhaps for
half a century candles have been required at an early hour in the
afternoon. The brilliant cut in diamonds is such an arrangement of the
posterior facets, or cut faces of the jewel, that all light reaching them
shall be thrown back and reflected, and thus impart an extraordinary
brilliancy to the gem.
The intense glare of snow in the Alpine regions has long been noticed,
and the reflected light is so powerful, that philosophers were even
disposed to believe that snow possessed a natural or inherent
luminosity, and gave out its own light. Mr. Boyle, however, disproved
this notion by placing a quantity of snow in a room from which all
foreign light was excluded, and neither he nor his companion could
observe that any light was emitted, although, on the principle of
momentary phosphorescence, it is quite possible to conceive that if the
snow was suddenly brought into a darkened room after exposure to
the rays of the sun, that it would give out for a few seconds a
perceptible light. In trying such an experiment, one person should
expose the snow to the sun, and bring it into a perfectly darkened
room to a second person, whose eyes would be ready to receive the
faintest impression of light, and if any phosphorescence existed, it
must be apparent.
The property of reflection is also illustrated on a grand scale in the
illumination of our satellite, the moon, and the various planetary bodies
which shine by light reflected from the sun, and have no inherent self-
luminosity. Aristotle was well aware that it is the reflection of light from
the atmosphere which prevents total darkness after the sun sets, and
in places where the sun's rays do not actually fall during the daytime.
He was also of opinion that rainbows, halos, and mock suns, were all
occasioned by the reflection of the sunbeams in different
circumstances, by which an imperfect image of the sun was produced,
the colour only being exhibited, but not the proper figure.
The image, Aristotle says, is not single, as in a mirror, for each drop of
rain is too small to reflect a visible image, but the conjunction of all the
images is visible. Aristotle ascribed all these effects to the reflection of
light, and it will be noticed when we come to the consideration of the
refraction of light, that of course his views must be seriously modified.
The reflection of light is affected rather by the condition of the surface
than the whole body of a substance, as a piece of coal may be covered
with gold or silver leaf and caused to shine, whilst the brightest mirror
is dimmed by the thinnest film of moisture.
From whatever surface light is reflected, it always takes place in
obedience to two fixed laws.

First. The incident and reflected rays always lie in the same plane.
Second. The angle of incidence is equal to the angle of reflection.

With a single jointed two-foot rule, both of these laws are easily
illustrated. The rule may be held in the hand, and one end being
marked with a piece of white paper may be called the incident ray, i.e.,
the ray that falls upon the surface; and the other is the reflected ray,
the one cast off or thrown back. A perpendicular is raised by holding a
stick upright at the joint. (Fig. 260.)

Fig. 260.
a d. A two foot rule; the end a may be termed the incident ray, and the
end d the reflected ray. s. The stick held perpendicularly. The angle a b c
is equal to the angle d e f, and the whole may be moved in any direction
or plane, either horizontal or perpendicular, g g. The reflecting surface.

One of the most simple and pleasing delusions produced by the


reflection of light, is that afforded by cutting through the outline of a
vase, or statuette, or flower, drawn on cardboard, and if certain points
are left attached, so that the design may not fall out, all the effect of
solidity is given by bending back the edges of the cardboard, so that
the light from a candle placed behind it, may be reflected from the
back edge of one cardboard on to the design, which is bent back. The
light reflected from one surface on to the other, imparts a peculiarly
soft and marble-like appearance, and when the design is well drawn
and cut, and placed in a good position, the illusion is very perfect, and
it appears like a solid form instead of a mere design cut out of
cardboard. (Fig. 261.)

Fig. 261.
Cardboard design in frame, cut and bent back. The lighted candle is
behind.

The leaf at the side of the above picture is intended to give an idea of
the mode of cutting out the designs, and in this case the leaf would be
cut and bent back, and a small attachment slip of cardboard left to
prevent it falling out.
The cardboard design is always bent toward the light, which is placed
behind it. As a good illustration of the importance of reflected light and
its connexion with luminous bodies, a beam of light from the oxy-
hydrogen lantern may be allowed to pass above the surface of a table,
when it will be noticed that the latter is lighted up only when the beam
is reflected downward by a sheet of white paper.
By reference to the two laws of reflection already explained, it is easy
to trace out on paper, with the help of compasses and rule, the effect
of plane, concave, and convex surfaces on parallel, diverging, or
converging rays of light, and it may perhaps assist the memory if it is
remembered that a plane surface means one that is flat on both sides,
such as a looking-glass: a convex surface is represented by the outside
of a watch-glass; a concave surface, by the inside of a watch-glass;
parallel rays are like the straight lines in a copy-book; diverging and
converging rays, are like the sticks of a fan spread out as the sticks
separate or diverge; the sticks of the fan come together, or converge at
the handle.
The reflection of rays from a plane surface may be better understood
by reference to the annexed diagram. (Fig. 262.)

Fig. 262.
a i, a k. Two diverging rays incident on the plane surface, d. a d is
perpendicular, and is reflected back in the same direction. a i is
divergent, and is thrown off at i l. The incident and reflected rays
forming equal angles, as proved by the perpendicular, h. Any image
reflected in a plane mirror appears as far behind it as the object is
before it, and the dotted lines meeting at g show the apparent position
of the reflected image behind the glass, as seen at g. The same fact is
also shown in the second diagram, where the reflected picture, i m,
appears at the same distance behind the surface of the mirror as the
object, a b, is before it.

By the proper arrangement of plane mirrors, a number of amusing


delusions may be produced, one of which is sometimes to be met with
in the streets, and is called "the art of looking through a four-inch deal
board." The spectator is first requested to look into a tube, through
which he sees whatever may be passing the instrument at the time;
the operator then places a deal board across the middle of the tube,
which is cut away for that purpose, and to the astonishment of the
juveniles the view is not impaired, and the spectator still fancies he is
looking through a straight tube; this however is not the case, as the
deception is entirely carried out by reflection, and is explained in the
next cut. (Fig. 263.)

Fig. 263.
a a a a. The apertures through which the spectator first looks. b. The
piece of wood, four inches thick. c, d, e, f, are four pieces of looking-
glass, so placed that rays of light entering at one end of the tube are
reflected round to the other where the eye of the observer is placed.

During the siege of Sebastopol numbers of our best artillerymen were


continually picked off by the enemy's rifles, as well as by cannon shot,
and in order to put a stop to the foolhardiness and incautiousness of
the men, a very ingenious contrivance was invented by the Rev. Wm.
Taylor, the coadjutor of Mr. Denison in constructing the first "Big Ben"
bell. It was called the reflecting spy-glass, and by its simple
construction rendered the exposure of the sailors and soldiers, who
would look over the parapet or other parts of the works to observe the
effect of their shot, perfectly unnecessary; whilst another form was
constructed for the purpose of allowing the gunner to "lay" or aim his
gun in safety. The instruments were shown to Lord Panmure, who was
so convinced of the importance of the invention, that he immediately
commissioned the Rev. Wm. Taylor to have a number of these
telescopes constructed; and if the siege had not terminated just at the
time the invention was to have been used, no doubt a great saving of
the valuable lives of the skilled artillerymen would have been effected
in the allied armies. The principle of the reflecting spy-glass may be
comprehended by reference to the next cut. (Fig. 264.)

Fig. 264.
A picture of enemy's battery is supposed to be on the mirror, a, whence
it is reflected to b, and from that to the artilleryman at c.

By placing two mirrors at an angle of 45°, the reflected image of a


person gazing into one is thrown into the other, and of course the
effect is somewhat startling when a death's head and cross bones, or
other cheerful subject, is introduced opposite one mirror, whilst some
person who is unacquainted with the delusion is looking into the other.
Two adjoining rooms might have their looking-glasses arranged in that
manner, provided there is a passage running behind them. (Fig. 265.)
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like