The Java Learning Kit: Chapter 1 – Introduction Copyright 2015 by C. Herbert, all rights reserved. Last edited December, 2014 by C. Herbert This document is a chapter from a draft of the Java Learning Kit, written by Charles Herbert, with editorial input from Craig Nelson, Christopher Quinones, and Matthew Staley. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Spring 2015 semester. This material is protected by United States and international copyright law and may not be reproduced, distributed, transmitted, displayed, published or broadcast without the prior written permission of the copyright holder. You may not alter or remove any trademark, copyright or other notice from copies of the material. The Java Learning Kit: Chapter 1 – Introduction Lesson 1.1 – Computing and Computer Science
Lesson 1.2 – Algorithms and Objects Lesson 1.3 – Programming Languages Lesson 1.4 – The Java Programming Language Lab 1 – Getting Started with NetBeans and Java JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 2 Contents Computing and Computer Science .................................................................................. 5 What is computer science? ............................................................................................... .................. 6 What do computer scientists and software engineers actually do? ................................................... 7 CheckPoint 1.1 ............................................................................................... ..................................... 8 Professional Organizations ............................................................................................... ................... 9 Computer Science Specializations ................................................................................ ............... ...... 10
Algorithms and Objects ............................................................................................... .. 11 CheckPoint 1.2 ....................................................................................... ........ ................................... 12 Programming Languages ............................................................................................... 13 Machine Code ............................................................................................... .................................... 13 Assembly Language ............................................................................................... ............................ 13 High Level Languages ............................................................................................... ......................... 14 Compilers and Interpreters ............................................................................................... ................ 14 The Java Advantage ............................................................................................... ........................... 15 FORTRAN ............................................................................................... ............................................ 16
Who develops and regulates technology standards? ....................................................................... 17 Algol ....................................................................................... ........ ................................................... 18 COBOL ............................................................................................... ................................................ 19 Functional Programming: LISP and Lambda Calculus ........................................................................ 20 BASIC ............................................................................................... .................................................. 21 Pascal ............................................................................................... ................................................. 22 The C Programming Language ................................................................................ ............... ........... 23 Simula and Smalltalk ............................................................................................... .......................... 24 C++ ............................................................................................... ..................................................... 25 Perl ...............................................................................................
..................................................... 26 C# (C Sharp)..................................................................................... .................................................. 26 Python ............................................................................................... ................................................ 28 JavaScript ............................................................................................... ........................................... 30 PHP ............................................................................................... .................................................... 31 Ruby ............................................................................................... ................................................... 32 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0891 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0892 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0902
JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 3 CheckPoint 1.3 ............................................................................................... ................................... 33 Lesson 1.4 The Java Programming Language ........................................................................................ 34 History and Development of the Java Language ............................................................................... 34 A Look at Java Source Code ............................................................................................... ................ 35 Why Java? ............................................................................................... .......................................... 36 Versions of Java ............................................................................................... ................................. 38 CheckPoint 1.4 ............................................................................................... ................................... 38 Lab 1 – Getting Started with NetBeans and Java .................................................................................. 39 Hello World! ............................................................................................... ....................................... 39
Creating a New Java Project – Step-by-Step ..................................................................................... 40 CamelCase Names in Java ............................................................................................... .................. 43 Description of the Source Code in a New Java Project ...................................................................... 44 Hello World! – Step-by-Step (continued) ........................................................................................ 47 Closing NetBeans Properly ............................................................................................... ................. 50 Copying and Submitting NetBeans Projects .................................................................................. .... 51 Key Terms in Chapter 1 ............................................................................................... .......................... 52 Chapter 1 - Questions ............................................................................................... ............................ 53 Chapter 1 - Exercises ............................................................................................... .............................. 54
file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0927 JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 4 Chapter 1 – Introduction This chapter is a brief introduction to computers, programming, and using Java to create software. Section 1 provides a brief background in computers and computer science, some of which may be familiar to you. It also has information from the ACM and IEEE about what computer scientists do and specializations in the field of computer science. Links in the section lead to more detailed information from experts in the field. A discussion of algorithms and objects in section 1.2 provides a short introduction to these two topics that lie at the heart of modern software development. Section 1.3 has an overview of computer programming languages. The last part of the chapter – sections 1.4 and Lab 1 – focus on Java. Section 1.4 introduces the
Java language, while the lab will help you get started creating and editing Java software development projects using NetBeans, a widely used integrated development environments (IDE). The Lab introduces elements of Java projects, comments in Java source code, how to copy and move Java projects, and how to submit Java projects as homework assignments in Computer Science 111. Learning Outcomes Upon completion of this chapter students should be able to: electronic computer system; nce and common specializations within the field; in computer science; -oriented programming; ers do, and how they compare to one another; of each in the history of programming languages;
role of Java bytecode, the Java Virtual Machine and the Java Runtime Environment in that process; , zip the project, and transmit the project as an email attachment, via social networking, or in a learning management system. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 5 Computing and Computer Science Generally speaking, a computer is any device that can store and process information. Most modern computers include a processing unit, often called a central processing unit or CPU; internal memory; input units; output units; and external storage devices, which could be considered a special category of input and output units. Figure 1-1 shows a block diagram of such a system. The various parts of the
computer system are connected by one or more communication channels. Each communication channel is a set of wires called a bus. Usually, three separate busses carry data, instructions, and control signals throughout the computer. A Central Processing Unit can be thought of as the heart or the brain of a computer system. It usually has one or more Arithmetic Logic Units (ALU) that process data by performing binary arithmetic, registers to hold data temporarily during processing, and a control unit to control the flow of information throughout the computer. The control unit orchestrates the timing and coordination of all of the computer system’s components, both within and outside of the CPU.
Internal memory in a modern computer is chip-based electromagnetic memory, with no mechanical moving parts. It is usually much smaller and faster than external storage. The internal memory could be on the same chip as the CPU or in separate chips, depending on the sophistication and size of the system. There are generally two distinct types of internal memory – Random Access Memory (RAM) in which randomly selected memory cells can be written to, erased, and reused; and Read Only Memory (ROM) which has programs or data permanently burned into a chip that can read but not re-written. External storage includes larger and slower memory devices, such as hard disk drives. They are usually electromechanical, which means they have moving parts that slow things down, such as spinning disks. Some newer technologies used for external storage, such as Flash ROM, use no moving parts, but are still slower than internal memory because of the technology used and because of the distance to the CPU. Flash ROM is a slower, less expensive non-volatile electromagnetic version of RAM technology with
a limited number of access cycles. Commonly used USB flash ROM storage devices are convenient, but should not be relied upon for long-term storage of important data because the chips eventually wear out and because they could be damaged by environmental factors, such as magnetic fields or static electricity. Figure 1. A simple block diagram of the major components in a computer system. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 6 Input units bring data into the computer from the outside world. Output units send data from the computer to the outside world. Together, they are referred to by the term input/output, or I/O. Peripheral equipment, or just peripherals, are devices outside of the main part of the computer that communicate with the CPU through I/O controllers. Most people consider external storage devices to be included in the term peripherals, along with I/O and communication equipment, such as keyboards, screens, and network adapters. The field of human–computer
interaction (HCI) addresses how people interact with computers including hardware, software, and computing practices. HCI experts help design I/O devices that people will use to communicate with computer systems. Data — including both data to be processed and instruction sets (programs) for the CPU — are usually moved from slow external storage into fast internal memory when needed, then moved back again for long-term storage. There is a hierarchy of memory within a computer system, from smaller, faster (and more expensive) caches of memory located close to or within the CPU to larger, slower (and less expensive) memory located farther away from the CPU. The actual organization of a computer varies from system to system, but the simple diagram above still captures the essential organization of digital electronic computers. Today, the circuitry for a complete computer system can actually be placed on a single chip. The organization of computer systems and the transfer and control of data within a computer system are studied in greater detail in a Computer Organization and Architecture course – the equivalent of an
anatomy and physiology course for computers. Such courses are often required in Computer Science, Computer Engineering, and related degree programs. What is computer science? Computer Science is the scientific study of computation, theoretically and in practice, as the basis for modern information systems. Computation includes numerical calculation and processes related to calculation. This may sound a bit boring, but remember, Information isn’t just numbers; it can also be text, graphics, sound, or video – anything that can have meaning to people. Modern computer systems manipulate, communicate, and store information in its many forms. Modern personal computer systems, tablets, and cell phones are the convergence of many devices dealing with information – typewriters, calculators, telephones, cameras, radios, televisions, sound and video recording equipment, and so on. Modern computer science is really a convergence of many fields of study dealing with information in its many forms. Yet at heart, computers are always about numerical processing, since, all information in its
many forms is represented numerically inside a computer. It’s all done with numbers. Computer Science is the study of how it’s done. Computer scientists study the theoretical ideas underlying modern computer systems and the practical application of those ideas to make sure that computer systems do what they are supposed to do correctly and in an efficient manner. They also search for new and better ways to build and use computers. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 7 Programming is only important part of computer science. Today computer scientists who develop new software and maintain existing software are often known as software engineers, applying time-tested engineering concepts and practices to the modern discipline of computer programming. What do computer scientists and software engineers actually do? The layering of complex systems around simpler systems is one of the key aspects of computer science and modern computer systems. Some computer scientists and software engineers work directly with
algorithms for the fundamental processes found in the innermost layers of all computer systems, but most work with the outer layers, the application software that people see when they use computers. Let’s look at an example of this layering, and then see how it relates to what computer scientists and software engineers actually do, followed by a look at specializations in computer science. A typical task, or application, for which we would use a computer system is word processing – creating, editing and printing documents using a computer system, most often using a keyboard and screen. A word processing program manages all of this so that you don’t need to worry about how it’s actually done. This is an example of application software, which is software people use to complete a task in the world outside of the computer system, as opposed to system software used to manage the computer. The word processing program asks the operating system to tell it what keys the user is pressing, and translates this into instructions telling the operating system what to store in memory, what to display on the screen, and so on. An operating system is like a master program always running on a computer and
coordinating what the computer does. It also provides the interface between a user and the system. The operating system works with short specialized programs called system utilities to complete specific tasks. Device drivers are a type of utility software that allows an operating system to communicate with the circuitry controlling specific hardware– such as a video control unit, a memory management unit or a disk controller. Together, the application software, the operating system, and the device drivers carry Figure 2. A computer system is composed of layers of specialized software. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 8 out binary digital arithmetic manipulating billions of bits of data each second to complete all of the tasks that are part of word processing. Hardware engineers design the hardware, systems programmers develop the operating system and utility software, and applications programmers design the software that most people see and use
directly. All contribute to the development of systems for tasks such as word processing. Those who start out studying computer science may end up as pure computer scientists expanding the theoretical foundations of computing, but most will specialize in other areas, particularly software development, and the majority of software developers are application developers. Most application developers specialize in areas that overlap with other disciplines. Business programmers, for example, usually need to know something about business, most often accounting, or they need to work with specialists who have such knowledge. Game programmers often work with graphic artists and audio engineers. They sometimes work with physics programmers or use a physics engine written by physics programmers to create realistic movement and interactions between physical objects in games that mimic the real world. The expertise needed to design and create software is as varied as the software itself. The term computer engineering is related to computer science. Computer engineering usually refers to
the study and development of computer hardware and involves the study of physics, computer science, and engineering, especially electrical engineering. Hardware engineering and software engineering are distinct fields, but there is a great deal of overlap between the two, so the term computer engineering often includes both. Theoretical computer science provides a foundation for both hardware and software engineering, but is most closely linked to software engineering, especially focusing on the development of efficient algorithms and data structures for information processing. The study of advanced mathematics is important in both software engineering and hardware engineering. In summary, some computer scientists are theoretical computer scientists – the philosophers of the computer world. Others focus on low-level systems engineering and programming, but most are application developers working on the outer layers of software that carry out common processes in our everyday world – video games, word processing programs, business software, and so on. They often have additional knowledge in other fields or work with people who have such knowledge.
CheckPoint 1.1 1. What is a computer? 2. What is inside a CPU? 3. What field in computing addresses how people use I/O devices? 4. What is Computer Science? 5. How are the terms software engineering and computer engineering related to one another? JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 9 Professional Organizations The Computer Science Accreditation Board (CSAB) is the primary agency for accrediting Computer Science degree programs in the United States. They recognize several areas of specialization in computer science education, listed on the following page. (See their website at http://www.csab.org)
The CSAB is sponsored by two major computer science professional organizations – the Association for Computing Machinery (ACM) and the Institute of Electrical and Electronic Engineers (IEEE). Professional organizations are made up of members with qualifications in a specific area – usually a college degree in the field or professional licensing, such as the American Bar Association for lawyers and the American Medical Association for physicians. According to the ACM website: The ACM, the world’s largest educational and scientific computing society, delivers resources that advance computing as a science and a profession. ACM provides the computing field's premier Digital Library and serves its members and the computing profession with leading-edge publications, conferences, and career resources. Their website has listings for professional jobs in computer science and education. They have a large repository of professional literature about research and development in the field of computing.
The IEEE Website says: The IEEE is the world's largest professional association dedicated to advancing technological innovation and excellence for the benefit of humanity. IEEE and its members inspire a global community through IEEE's highly cited publications, conferences, technology standards, and professional and educational activities. The IEEE focuses on Electrical Engineering and related fields, including data communications and computing. They publish standards for these areas that are often the basis for ISO standards. Their website features job listing for professional engineers. See http://www.acm.org/ for more information about the ACM and http://www.ieee.org for more information about the IEEE. Both the ACM and the IEEE have student memberships. ACM student membership page: http://www.acm.org/membership/student IEEE student membership page: www.ieee.org/students
http://www.csab.org/ http://www.acm.org/ http://www.ieee.org/ http://www.acm.org/membership/student file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/ww w.ieee.org/students http://www.acm.org/ http://www.ieee.org/ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 10 Computer Science Specializations specializing in the spatial and temporal efficiency of software and the relationship between data formats and processing to manipulate data developing machines with intelligence, including decision making, perception, planning, and machine learning similar to human mental abilities the logical design and organization of computers and their components graphics creating and improving computer based imaging methods and technology improving the efficient transport and security of data between
systems mathematically-based efforts to improve the way people and enterprises store and access data computing across multiple platforms -computer interaction (HCI) how people use computer and how computers communicate with people e and security keeping data safe from harm and from loss or change due to technical factors the applied mathematics end of computing focus on software to coordinate and control computer systems, and to provide a bridge between the hardware and the user the execution of algorithms using multiple coordinated processors research into better ways to develop software an engineering approach to designing and building software
theoretical study of the limits and nature of computing The CSAB recognizes each of the above areas as sub-fields within computer science. For career information see: http://www.csab.org/career.html. ACM special interest groups (SIG) bring together computer scientists in these and other specializations, such as bioinformatics, computers and society, or embedded systems. See: http://www.acm.org/sigs http://www.csab.org/career.html http://www.acm.org/sigs JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 11 Algorithms and Objects At the heart of everything computer scientists study, at the core of computing, we find the concept of the algorithm. Simply put, an algorithm is a step-by-step process. Early in the ninth century of the Christian Era, a scholar named Muhammad ibn Musa al-
Khwarizmi (Arabic: ‫دمحم‬ ‫نب‬ ‫ىسوم‬ ‫)يمزراوخلا‬ came to live and work in the City of Baghdad. Al-Khwarizmi1 means from Khwarezm (Arabic: ‫مزراوخ‬, Russian: Хорезм, Uzbek: Xorazm), in what is now Uzbekistan, which was his ancestral homeland. He was one of many scholars brought to Baghdad by the Caliph to form one of the world’s first modern universities. Al-Khwarizmi wrote several important books on mathematics, geography, and astronomy, but perhaps his most important work was his second book, al-Kitab al-mukhtasar fi hisab al- jabr wa'l-muqabala (‫بات‬ ‫ك‬ ‫رص‬ ‫لا‬ ‫ت‬ ‫خم‬ ‫ي‬ ‫لا‬ ‫باس‬ ‫ف‬ ‫رب‬ ‫ح‬ ‫ج‬ ‫ةل‬ ‫لا‬ ‫ل‬ ‫)وا‬ (A ‫م‬ ‫اب‬ ‫ق‬ Compendium on Calculation by Completion and Balancing), in which he presented a method for solving math problems by balancing equations. His method came to be known as algebra. (Al-jabr = algebra.) This was only one part of his systematic approach to solving math and science problems, known in various
languages as the method of al-Khwarizmi, and from which we get the Latinized term algorithm2. According to the French writer and historian Andre Allard3, almost all Western ideas about mathematics, and hence much of modern science, technology, and engineering, were derived in part from seven critical texts written during the twelfth century and widely circulated through Europe in the centuries that followed. All seven of those books quote extensively from translations of al-Khwarizmi’s work. He stands with Euclid and a few others as one of the ancient founders of modern Science, Technology, Engineering and Mathematics – the STEM disciplines. A computer program is a step-by-step set of instructions telling a computer how to perform a specific task. As such, every computer program is an algorithm. Students in a good computer programming course are consciously learning about the logical structure of algorithms and techniques for organizing algorithms which have their roots in the work of al-Khwarizmi more than a thousand years ago. 1 For more about Al-Khwārizmī and his work see: http://www-groups.dcs.st-
andrews.ac.uk/history/Mathematicians/Al-Khwarizmi.html 2 From Donald Knuth’s Website at Stanford University: http://www-cs-faculty.stanford.edu/~uno/graphics.html 3 Allard, Andre (1992) Le calcul indien (Algorismus) / Muhammad ibn Musa al-Khwarizmi ; histoire des textes, Paris: Libraire scientifique et technique Albert Blanchard. Figure 3. A Soviet stamp from the 1980s marking al- Khwarizmi’s 1200th birthday. http://www-groups.dcs.st- andrews.ac.uk/history/Mathematicians/Al-Khwarizmi.html http://www-cs-faculty.stanford.edu/~uno/graphics.html JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 12 Of course, data and algorithms have evolved since the days of al-Khwarizmi, especially since the advent of computers in the twentieth century. Computer scientists developed the notion of objects and object- oriented programming to help manage the growing complexity of data and algorithms. Anything that can be represented by data in the computer’s memory and
manipulated by algorithms implemented as computer programs can be organized as an object. Objects can be things in the physical world or even just abstract ideas. An airplane, for example, is a physical object that can be manipulated by a computer. A student’s grade point average is an example of an object that is not a physical object. The data that represent an object are organized into a set of properties. Each property is a unit of data that describes the object in some way. The programs that manipulate the properties of an object are known as the object’s methods. In a modern computer system, an object is a collection of properties and the methods that are used to manipulate those properties. This modern approach to computer programming is known as object-oriented programming, or OOP for short. Objects with the same methods and properties
are instances of the same class of objects. A class definition is a like blueprint for new instances of the object. Figure 3 shows a Universal Modeling Language (UML) diagram for a BankAccount class of objects. Each instance of the object will have the same properties, but have its own values in those properties. Java is an object-oriented programming language. You will learn much more about objects and object- oriented programming as you study Java. CheckPoint 1.2 1. What is an algorithm and why are algorithms important in computer programming? 2. What is an object? 3. What is the difference between a class of objects and an instance of an object? 4. What is a property in object-oriented programming? 5. What is a method in object-oriented programming?
Figure 4. A UML diagram for a BankAccount class of objects. Each individual account is an instance of the class. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 13 Programming Languages All of a computer system’s data and instructions are processed in a CPU’s arithmetic logic units that perform binary arithmetic. Usually, the data and instructions come into a processor in separate streams – a data stream and an instruction stream. Some of the instructions in the instruction stream tell the processor which math operations to perform, while others direct the movement of data. Still others control the logic of programming – the branching and looping present in algorithms. At the level of the CPU, a computer’s instructions are in the form of binary numbers, just like the data itself. Programs written in languages like Java must somehow be converted into these ones and zeroes. Machine Code The set of binary numbers that the CPU understands as its instruction set is called the computer’s
machine code. Each CPU, or each family of CPUs, such as the Intel x86 family, has its own machine code. So, there are just as many different machine codes as there are families of processing units. Eventually, everything that a computer does must be translated into its machine code. Assembly Language When a new processor is first developed, it can only be programmed in machine code. Systems programmers use machine code to build an assembler, which is a program that translates assembly language into machine code. An assembly language is made up of very primitive instructions, just like machine code, but they can be written using numbers in bases other than base two and mnemonics, which are short words that sound like what they represent and are easy to remember, such as ADD for addition or SUB for subtraction. They can also use symbolic names instead of numbers to refer to memory locations. Assembly Language Machine Code Hexadecimal Equivalent mov ebx,mval
mov ecx,arraySize mov edi,arrayPtr L1: mov eax,ebx imul eax, DWORD PTR[edi] mov DWORD PTR[edi],eax add edi,TYPE DWORD loop L1 10001011 01011101 00001000 10001011 01001101 00010000 10001011 01111101 00001100 10001011 11000011 00001111 10101111 00000111 10001001 00001100 10000011 11000111 00000100 11100010 11110100 8B 5D 08
8B 4D 10 8B 7D 0C 8B C3 0F AF 07 89 07 83 C7 04 E2 F4 Figure 5. Part of an Intel x86 family assembly language program. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 14 Figure 5 shows the main body of a program written in x86 assembly language, the language for the Intel family of processors used in most personal computers, along with the code’s translation into binary x86 machine code and its hexadecimal (base 16) equivalent. This code multiplies each value in an array in memory by a scalar value. Hexadecimal numbers are often used in printouts of machine
code to make the code easier read. The translation from binary to hexadecimal is simple, because 16 = 24. Each hexadecimal digit represents four binary digits, as shown in the chart below. Hexadecimal and binary numbering are often covered in courses in Computer Math and Logic or Discrete Mathematics. Binary Equivalents of Hexadecimal Digits 1111 = F 1011 = B 0111 = 7 0011 = 3 1110 = E 1010 = A 0110 = 6 0010 = 2 1101 = D 1001 = 9 0101 = 5 0001 = 1 1100 = C 1000 = 8 0100 = 4 0000 = 0 High Level Languages Creating software can still be difficult and time consuming in assembly language. Eventually, computer scientists and software engineers build translators that can handle high-level languages, which are programming languages that are closer to human languages and easier for people to understand. Java, JavaScript, Visual BASIC, C++, and Python are all examples of modern high-level computer programming
languages. In contrast, machine code and assembly language are called low-level languages. Compilers and Interpreters There are two types of translators that convert high-level languages into machine code: compilers and interpreters. A compiler translates an entire program into machine code and stores the result. The programmer ends up with two stored copies of the program. The first, in the original high-level programming language, is called the source code. The second stored copy of the program, which is the same program after translation into a particular machine code, is called the object code. Even after translation into machine code, a program may still need to be linked with subroutines from the operating system so that it will run on a particular platform. This step is sometimes called linking and loading or making an executable program. Sometimes linking and loading happens when we try to run object code, and sometimes the compiler makes and stores an executable program as another step in the process of compiling. In either case, with a compiler, there are at least two stored copies of the program, the original source code along with the already-
translated the object code, and often a third copy called an executable program. An interpreter is much simpler than a compiler. An interpreter translates a program one instruction at a time as the program runs. It feeds each translated instruction to the CPU to be executed before translating the next instruction. The only stored copy of the program is the original source code. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 15 Often scripting languages, such as JavaScript or Visual BASIC for Applications (VBA), are interpreted. Scripting languages are simplified high-level languages that allow someone to program in a particular environment. JavaScript can be added to the HTML codes for Web pages to provide them with some primitive data processing capability. VBA allows someone to program features in Microsoft Office products, such as Word or Excel. Interpreters have also been used for teaching languages. Serious computer programming languages
such as Java and C# that are used by professional software developers are sometimes referred to as production languages. Teaching languages are languages that are not generally used in production environments, but are instead used to teach someone the logic of computer programming or the processes used in creating computer software before attempting to teach them to use production languages. The Pascal programming language was an example of a teaching language. The Java Advantage What about Java? Java is both compiled and interpreted. Portability and high performance were both design goals for the Java language. These goals are sometimes in conflict because of the differences from one platform to another. Java’s developers introduced the Java Virtual Machine to address this issue. The Java Virtual Machine (JVM) is basically an interpreter that can handle a simplified intermediate language called Java bytecode. Java bytecode is a set of one and two-byte codes representing an intermediate step between Java source code and a computer’s machine code. It is very similar to a generic machine code, which can be translated into
a specific machine code more quickly and easily than a high-level language. A Java compiler first translates Java source code into Java bytecode. This can be stored and moved from one platform to another. Java .class files are bytecode files. Each machine that needs to run Java is equipped with a Java Runtime Environment (JRE) that has everything needed to run Java software on Figure 6. All programs must be translated into machine code. Compilers, interpreters and assemblers perform this translation. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 16 that machine, including a JVM that translates and runs the Java bytecode as machine code for the host platform. The JVM’s rapid translation from bytecode to machine code provides high performance. The use of bytecode, combined with the widespread availability of JVMs for almost all processors, makes Java software very portable. Both Apple and Microsoft were highly critical of this approach,
but it proved successful, largely due to the Internet. Today, almost all Web browsers are Java-enabled – meaning that they can run Java bytecode – and most personal computers, tablets and smart phones are enabled with a Java Runtime Environment or its equivalent, which is free for all systems4. According to Oracle, there were over 1.1 billion PCs and over 3 billion smartphones running Java at the end of 20135. There are now more Java- enabled devices in the world than there are people. This portability for a powerful object-oriented language is what IBM calls “The Java advantage”. Let’s take a look at several other important and popular high- level languages that were developed over the years. FORTRAN FORTRAN, one of the first high level programming languages, was released in 1957 by IBM for use on their popular 701
computer. It was proposed by John Backus, a mathematician who specialized in writing programs to perform complex calculations. The name FORTRAN comes from the two words “formula translator”, and as the name implies, it was designed for use by scientists and engineers, with special instructions for math functions. 4 The JRE download page is online at: http://www.oracle.com/technetwork/Java/Javase/downloads/Java -se-jre-7-download-432155.html 5 See Oracle’s Lean About Java Technology page online at: http://www.Java.com/en/about/ According to the site, “31 times
more Java phones ship every year than Apple and Android combined.” ! FORTRAN 77 by C. Herbert ! code to find the roots of a quadratic equation PROGRAM ROOTS READ A,B,C D = B**2 - 4*A*C IF (D.GT.0.0) THEN D = S**0.5 X1 = (-B+D)/(2*A) X2 = (-B-D)/(2*A) PRINT *, 'TWO REAL ROOTS:' X1 'AND' X2 ELSE IF (D.GT.0.0) THEN X = -B/(2*A) PRINT 'ONE REAL ROOT:',X ELSE PRINT 'NO REAL ROOTS' END IF
END IF END Figure 7 – FORTRAN 77 http://www.oracle.com/technetwork/java/javase/downloads/java -se-jre-7-download-432155.html http://www.java.com/en/about/ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 17 Who develops and regulates technology standards? Technology standards are important in the modern world so that things like computers (or telephones, or even plumbing systems) are compatible with one another. They are also important to maintain public health and safety. Various governmental and private agencies are responsible for technology standards. es are part of the government or are backed by the government and have the force of law behind them. Their standards are often called regulations rather than standards. Sometimes they adopt standards from other agencies and give them the force of law. For example, The Federal Communications Commission (FCC) is a federal government agency in the U.S. responsible for regulating electronic communications. They can regulate the nature and amount of electromagnetic interference a computer generates, so that it
won’t interfere with cell phones. The Occupational Health and Safety Administration (OSHA) can regulate how computers and related equipment affect workers in business and industry. There are many such agencies. pendent organizations, but are sometimes supported by the government or are part of the government, depending on the country. The International Organization for Standardization, also named ISO, is an umbrella group responsible for international standards in a wide variety of areas. (The name ISO comes from the Greek for equal, and is not an acronym.) It is composed of national standards agencies from more than 160 countries around the world. The American National Standards Institute (ANSI) is the national standards agency in the United States. It is a private, non-profit voluntary organization composed of committees of experts in different fields. Some national standards agencies are government agencies, such as the Standardization Administration of the People's Republic of China (SAC), the Chinese equivalent of ANSI. The ISO has released standards for many programming languages. For more information on ISO and its members, see: http://www.iso.org/iso/home/about/iso_members.htm societies, such as the ACM and the IEEE mentioned earlier in this chapter, often release standards and guidelines. The IEEE has played an important role in developing standards for electronics and computing, such as the IEEE standards for
floating point numbers. common interest. The Electronics Industries Alliance (EIA), formerly known as the Electronics Industries Association, is an organization of computer and electronic equipment manufacturers. They often adopt standards so that equipment from different manufacturers is compatible. The Computer Technology Industry Association (CompTIA) publishes standards for certifying computer professionals, especially in networking and security. Sometimes a group of industry experts from industry, academia, and the government get together to address areas of common interest. This happened in Philadelphia in 1960 when CODASYL, the Conference on Data Systems Languages, was formed to discuss “the feasibility of establishing a common language for programming of computers in business data processing applications.” * Their work gave rise to the COBOL language. control their own standards. Technically, Java belonged to Sun Microsystems, but was designated as Free Open Source Software, and the current mechanism for proposing changes to the java standard is the Java Community Process (see http://www.jcp.org ). The .NET languages – (C#.NET, VB.NET, etc.) are owned by Microsoft. * from The History of Cobol, edited by William M. Klein, available online at:
http://home.comcast.net/~wmklein/DOX/History.pdf http://www.iso.org/iso/home/about/iso_members.htm http://www.jcp.org/ http://home.comcast.net/~wmklein/DOX/History.pdf JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 18 Versions of FORTRAN were soon created for IBM’s other computers, including the 1400 series, and then for most of the more popular computers from other vendors. This made FORTRAN the first portable programming language – one that is widely used across different computing platforms. The FORTRAN code had to be compiled for each specific platform, but the source code could be used on any computer with a FORTRAN compiler. IBM developed several versions, culminating in FORTRAN IV in 1962. The American National Standards Institute (ANSI) issued a definition for a standard FORTRAN language, called ANSI FORTRAN 66, in 1966 followed by ANSI FORTRAN 77 in 1977. In 1991, the ISO released an international standard for Fortran, with a parallel ANSI standard, which broadened the language and changed the name from all caps to simply Fortran. That version
is often called Fortran 90. Before FORTRAN almost all software was created using assembly language and machine code. Once FORTRAN appeared, people began to use it for much more than science and engineering. The increasing use of FORTRAN to process commercial business data led to problems for financial accountants and auditors. A bank auditor, for example, needs to be able to “follow the money” from one account to another. This was nearly impossible with FORTRAN, unless the auditor was also a trained computer programmer. In addition, even though FORTRAN contained functions for mathematics, it was not well suited for programming business and financial transactions. Other languages were needed. A list of free FORTRAN tutorials is available online at: http://www.fortran.com/fortran/market.html . This webpage is maintained by the Fortran Company, which provides Fortran products and professional consulting. Today Fortran is a rarely used programming language, but some applications based on old legacy code still use it. Algol
Soon after the development of FORTRAN, John Backus was also instrumental in the development of Algol, which was a language designed by an international group of mathematicians and programmers for use in describing and discussing algorithms. Some of the more important features of modern programming languages that first appeared in Algol include: -end pairs to mark blocks of code and limit the scope of variables rameters to implement their own data types. Algol was never commercially successful as a production language, nor was it intended to be. Burroughs was the only large computer company that provided an Algol compiler, and many of its features were additions to the Algol standard. Algol did not have the built-in specific tools for scientific or business programming like FORTRAN or COBOL, and it lacked a standard definition of input and output routines
for file handling, screen displays, and printing. Instead, it was the language used internationally by research computer scientists to publish algorithms, and created a foundation for more advanced programming languages, including most modern programming languages. C, C++, Java, Python and most http://www.fortran.com/fortran/market.html JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 19 other languages used widely today can trace their origins back to ideas implemented in Algol. In fact, even early languages, such as COBOL and BASIC, adopted features from Algol. Several early versions of Algol were defined, including Algol 58 (1958), Algol 60 (1960). COBOL The solution to the problem of using FORTRAN in the business world was solved with the introduction of the COBOL language in 1960. Like the name FORTRAN, COBOL is an acronym that comes from the words COmmon Business-Oriented Language. COBOL was developed by a team of people working for
the United States Navy under the direction of Grace Hopper, who went on to become an admiral (O-7) before she retired after a 40-year naval career. In April of 1959, The Conference on Data Systems Languages (CODASYL) held their first meeting at the University of Pennsylvania in Philadelphia. The conference, made up of representatives of major computer companies and several government agencies, was formed by the Defense Department to develop a standardized business programming language that could be used across all computing platforms. The first COBOL compilers were released in 1960. The first ANSI version of COBOL was COBOL 68, followed by COBOL 74 and COBOL 85, which was adopted as an ISO standard. procedure Findmax(a) Size:(n) Result:(b) Subscript:(k); value n, b,k; array a; integer n, b, k; comment Find the maximum value in an array of n integers, b is the minimum value, k is its index -- Algol 60 code by C. Herbert; begin integer i;
b := a[1]; k := 1; for i := 2 step 1 until n do if a[i] > b then begin b := a[i]; k := I; end end Findmax Figure 8 – Algol 60 JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 20 COBOL has functions and instructions that are more suited to commercial data processing than FORTRAN, and is a wordier language, which makes it easier for financial auditors to understand without extensive training. It was better suited for business recordkeeping and accounting than FORTRAN or almost any other language, which is what the language was designed to do. It was estimated that by the year 2000 there were more lines of
code written in COBOL than in any other computer programming language, and that more than 80 percent of the world’s business software was written in COBOL. The use of COBOL declined at the end of the twentieth century, coinciding with the rise of electronic spreadsheets, specialized accounting software, and relational database management systems. In 1990, the US Department of Labor estimated there were 500,000 professional COBOL programmers in the US. By 2010, that number had dropped to less than 75,000. Today, only a small percentage of new programmers are learning COBOL. Functional Programming: LISP and Lambda Calculus Another programming language that appeared around 1960 was LISP, developed at MIT by John McCarthy with some help from Marvin Minsky. The name LISP comes from “List Processing”. LISP is a functional language based on Lambda Calculus. As the name implies, the processing of lists, especially linked lists, is an important feature of the language. Princeton mathematician Alonzo Church developed Lambda Calculus in the 1930s as a formal system of logic for discussing mathematical functions. It is important in
computer science, especially as the basis for functional programming languages. Lambda Calculus is all about substituting one equivalent item for another. In standard algebra, for example, if we discover that Y = X+3, then we could substitute X+3 in place of Y to help solve for X in 2X+Y=12. It becomes 2X+(X+3) = 12 which reduces to 3X+3=12, then 3X=9, then X=3. Earlier in this chapter we discussed the ninth century work of al-Khwarizmi, from whom algorithms derive their name. He was one of the first to formalize a language for this kind of IDENTIFICATION DIVISION. PROGRAM-ID. Multiplier. AUTHOR. Michael Coughlan. * COBOL 68 sample program from The University of Limerick, Ireland * Example program using ACCEPT, DISPLAY and MULTIPLY to * get two single digit numbers from the user and multiply them together DATA DIVISION.
WORKING-STORAGE SECTION. 01 Num1 PIC 9 VALUE ZEROS. 01 Num2 PIC 9 VALUE ZEROS. 01 Result PIC 99 VALUE ZEROS. PROCEDURE DIVISION. DISPLAY "Enter first number (1 digit) : " WITH NO ADVANCING. ACCEPT Num1. DISPLAY "Enter second number (1 digit) : " WITH NO ADVANCING. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", Result. STOP RUN. Figure 9 – COBOL 68 JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 21 substitution to solve calculation problems. Professor Church developed lambda calculus as a theoretical model for computation, originally used to explore which
functions can and cannot be computed using algebra or any other system of calculation. It has become a cornerstone of theoretical computer science. LISP has been an important language, associated with research into artificial intelligence and functional programming, but otherwise rarely used as a production language for business, scientific, or systems programming. Today the two most common versions of LISP are Scheme and Common LISP. Scheme has been used in introductory computer science courses, but its use has declined in recent years. Haskell, ML, and CAML are other functional programming languages sometimes used in upper- level computer science courses and computer science research.
BASIC COBOL, like FORTRAN, takes a while to master. For College students, this often meant that a semester or more had to be spent learning programming before anything useful could be done with a computer. At the same time, computers were becoming smaller, less- expensive, and more accessible to the public. Personal computers were still some years away, but by the mid-1960s many colleges and universities had computers that students could use on campus. In 1965, in order to make programming accessible to students on the new “mini-computers” that had begun to appear, two professors at Dartmouth College in Hanover, New Hampshire, John Kemeny and Thomas Kurtz, invented the BASIC programming language. BASIC (Beginner’s All-Purpose Symbolic Instruction Code) was an interpreter-based language rather than a
compiled language like FORTRAN or COBOL. It was designed to be easy to learn and easy to use. ;;; sample Lisp function ;;; from The University of Michigan Language Guide ;;; This function, given a specific degree in Farhrenheit, ;;; presents the user with equivalent Celsius degree. (defun convert () (format t "Enter Fahrenheit ") (LET (fahr) (SETQ fahr (read fahr)) (APPEND '(celsisus is) (*(- fahr 32)(/ 5 9)) ) ) ) 10 REM BASIC SAMPLE CODE BY C. HERBERT 20 REM 1 TO 100 GUESSING GAME 30 LET X = INT(RND * 99 + 1)
30 PRINT “I AM THINKING OF A NUMBER FROM 1 TO 100.” 40 PRINT “TRY TO GUESS WHAT IT IS.’ 50 PRINT “YOUR GUESS” 60 INPUT G 70 IF G = X THEN GOTO 200 100 IF G < X THEN PRINT “LOWER” 110 ELSE PRINT “HIGHER” 120 PRINT “TRY AGAIN” 130 PRINT 140 GOTO 50 200 PRINT “CORRECT” Figure 10 – Lisp Figure 11 – BASIC JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 22 BASIC caught on quickly. When personal computers began to appear in the late 1970s almost every
machine was equipped with a BASIC interpreter, so, at the time, more people learned BASIC than any other language. Over the years there have been many versions of BASIC, including GW-BASIC, Quick BASIC, True BASIC, and Visual Basic, just to name a few. Today the most common version of Basic is Microsoft’s Visual Basic.NET (VB.NET), which appears to be declining in popularity and professional use. The newest version of Visual Basic is part of Microsoft’s Visual Studio 2013. Pascal BASIC and FORTRAN both had a GOTO command, which is sometimes referred to as an unconditional branching command. Each line in a BASIC or FORTRAN program was numbered, and at any point in the program the GOTO instruction could suddenly re-direct the flow of control to a line number in another part of the program. The command was intended to let users set up
branching and looping, but it was so flexible to use that programmers often ended up with poorly designed logic that jumped repeatedly back and forth throughout the code, leading to what was referred to as spaghetti code. People other than the original programmer often had to spend hours trying to figure out how such a program worked. In response to this problem, Swiss computer scientist Niklaus Wirth released the Pascal programming language in 1970. He named the language after the seventeenth century French Mathematician and Philosopher, Blaise Pascal, one of the first people to ever build a working mechanical calculator. Wirth’s Pascal was widely used as a teaching language and for prototyping - designing algorithms in one language for implementation
in another. in the late 1970s and 1980s. It was based on concepts from Algol, but had built-in commands for looping and branching that forced the user to write programs according to good principles of structured logical design. In Pascal, it became natural for programmers to code with a logical flow of instructions and (* Pascal sample code by C. Herbert *) (* 1 to 100 guessing game *) program Guess; begin var pick: integer = random(100); guess: integer; writeln('I am thinking of a number from 1 to 100.’); writeln('Try to guess what it is.’); repeat writeln();
writeln(‘Your guess?); readln(guess); if guess > pick begin writeln(‘Lower.’); writeln(‘Try again.’); end else begin writeln(‘Higher.’); writeln(‘Try again.’); end until pick = guess; writeln(‘correct’) end. Figure 12 – Pascal JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg.
23 almost impossible for them to end up with spaghetti code as they did in BASIC. Pascal was a simple interpreter-based language that was easy to learn and use. Pascal code could also be compiled for production of commercial software. It did see some professional use, particularly by Apple from 1978 into the mid1980s, but was never on a par with FORTRAN, COBOL, or newly emerging object-oriented languages. Niklaus Wirth went on to develop Modula and Modula 2, languages designed around the concept of modular programming, and Oberon, a true object-oriented language. The C Programming Language The C programming language was developed at Bell Labs by Dennis Ritchie for use as a systems programming language. C is a simple high-level language that incorporates many of the Algol features, but it has a fairly simple compiler, and uses a small amount of memory compared to more complex languages. This provides C with two advantages: first, it is relatively easy for a
team of good assembly language programmers to build a C compiler quickly, and second, the language can run in a small amount of memory, such as on small embedded processors. C is often the first language high-level language developed for a new processor, and is often used for developing system software, such as parts of operating systems, device drivers, and compilers and interpreters for other languages. It was used to write the original Unix operating system, and has been closely linked with Unix and Linux systems. C is also an important language on which many more advanced languages are based, such as C++, Java, and Python. There is a direct connection from Algol through C to many modern languages. In 1978, The C Programming Language, a book by Brian Kernighan and Dennis Ritchie, appeared on the market. 6 It was the definitive book on C programming with a very simple straightforward style teaching experienced programmers how to use the language. It became one of the most widely read and
influential programming books of all time. Many C compilers were written using specifications based on K&R, as the book is called. In 1989 ANSI adopted a standard for the C programming language, which became the ISO standard the following year. ANSI C, ISO C, C 89 and C 90 are all fundamentally the same language. ISO revisions of the C standard appeared in 1994, 1999 and 2011. Today many people write C code using a C++ compiler, as C is a subset of the newer, object-oriented C++. 6 Kernighan, Brian W.; Ritchie, Dennis M. (February 1978). The C Programming Language (1st edition.). Englewood Cliffs, NJ: Prentice Hall. ISBN 0-13-110163-3. Figure 13. The C Programming Language by Kernighan and Ritchie. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 24 Simula and Smalltalk
In the 1960s two Norwegian computer scientists, Kristen Nygaard and Ole-Johan Dahl, developed a language for programming discrete event simulations, which they called Simula. A discrete event simulation simulates a system in which distinct events change the state of a system. It differs from a continuous real-time simulation in which variables are constantly changing. For example, a game of American football could be viewed as a discrete event simulation if we only see the results of each play and not the plays themselves. The state of the system could include which team has the ball, on what yard line, what down it is, how far to go for a first down, and the score. Each play could be considered a discrete event that changes the state of the system. The defense picks a formation, the offense picks a play, and the simulation shows the result. Many games and real world processes can be viewed in this way. Most discrete event simulations in business and industry are much more complicated, such as modeling a manufacturing process or a transportation system. Nygaard and Dahl needed a programming language to simulate discrete systems and interactions between multiple systems. They came up with an Algol-based
language that had objects with properties, along with distinct methods to manipulate those properties – the basis for modern object oriented programming. Objects communicated with each other by passing messages back and forth to each other. The language was defined by the International Federation for Information Processing in 1967 as Simula 67. Simula was a language for a very specific purpose, but the ideas in Simula inspired others. At the Xerox Palo Alto Research Center in California, computer scientists led by Alan Kay developed the Smalltalk programming language, which was highly influenced by the innovations in Simula. Smalltalk, released in 1980,
is a true object-oriented programming language in which every bit of data and every method must be part of an object. Objects communicate with each other only through message passing between objects. The properties of each object are fully encapsulated, meaning that no object can see the properties of another object except through messages from that object. “Smalltalk example from Clemson University” “Prof. Joe Turner, 1998” ApplicationModel subclass: #TalkInterface instanceVariableNames: 'talk message ' classVariableNames: '' poolDictionaries: '' category: 'UIApplications-New'! !TalkInterface methodsFor: 'initialization'!
initialize "Initialize an interface instance." talk := TalkBox new! ! !TalkInterface methodsFor: 'actions'! goodbye "Action when the Goodbye button is selected." message value: talk goodbye! hello "Action when the Hello button is selected." message value: talk hello! ! Figure 14 – Smalltalk JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 25 After several years of research, Smalltalk-80 was released in 1980. ANSI Smalltalk (1998), Apple Smalltalk, Squeak, and VisualWorks are just a few of the many versions of Smalltalk. Smalltalk is rarely
used for modern production programming compared to languages like Java, and C++. C++ The C++ programming language is a revision of C influenced by Simula and Smalltalk. (The name C++, comes from the fact that the ++ operator indicates iteration in the C language.) C++ is an object- oriented language in the sense that it can be used to implement objects and message passing, but it does not require that programmers use objects and message passing. In fact, the C language is a subset of C++ and many C programs will work with a C++ compiler with little or no change.
C++ was developed at Bell labs by Dr. Bjarne Stroustrup, a Danish- born computer scientist with a PhD. in Computer Science from Cambridge University. He merged the object features from Smalltalk into the C programming language to create a language that was practical and versatile like C, but that could support object- oriented development. Dr. Stroustrup viewed C++ as a good tool for developing large software systems. C++ was released in 1983. ISO standards for C++ were released in 1998 and revised in 2003, 2007 and 2011. Today C++ is among the most widely used programming languages, and has spawned several spinoffs,such as C#, and Objective C. Many game development systems use a programming language
based on C++. Java syntax was based on on C++. // C++ program to display a pattern of stars on the screen // CIS 106 - Spring 2012 #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int size = 3; int row; int column; int space = size*2; for(row = 1 ; row <= size ; row++) { for(column = 1 ; column < space ; column++) { printf(" "); } for(column = 1 ; column <= 2 * row - 1 ; column++) { printf("*"); } space--; printf("n"); } system("PAUSE"); return EXIT_SUCCESS;
} Figure 15 – C / C++ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 26 Perl Perl was developed by Larry Wall in 1987 as a language for extracting data and creating reports on Unix computers. The language was well suited to preforming similar tasks for Web and Network programming and increased in popularity with the rise of the Internet. Perl is also well-suited for tying together applications and for writing very short (often online) scripts for Unix and Linux systems administrators. Perl scripts are sometimes used by systems administrators when installing software. Wall originally named the language Pearl after
“the pearl of great price”, mentioned in the Bible’s book of Matthew. He changed it to Perl when he found that an older obscure language named Pearl existed. Today some people say the Perl stands for Program Extraction and Reporting Language. Perl 5 has been around since 1994. The most recent version, released in May 2014, is Perl 5.20. Perl 6 has been developed as a different language related to Perl 5. Both are freely available software. For more about Perl 5, see: http://www.perl.org For more about Perl 6, see: http://perl6.org C# (C Sharp) C# was developed as a proprietary part of Microsoft’s .NET Framework. Anders Hejlsberg was the lead developer. The C# programming language was released by Microsoft following their failed attempt to implement the J++ language, a version of the Java programming language.
From its inception, Java was intended to be a freely available language for use on any computer system. Sun Microsystems (and later Oracle) allowed others companies to develop their own Java compilers and software development systems, provided they agreed to make their versions of Java conform to Sun’s standards for Java compatibility. Microsoft developed a version of Java under such a license, but began to add proprietary features to their “J++” language, which Sun believed to be in violation of the agreement. Following a lawsuit filed against Microsoft by Sun, J++ development was halted. The last available version was discontinued in 2001. # Perl script to send an email message # from http://learn.perl.org/examples/email.html #!/usr/bin/perl use strict; use warnings; # first, create your message use Email::MIME;
my $message = Email::MIME->create( header_str => [ From => '[email protected]', To => '[email protected]', Subject => 'Happy birthday!', ], attributes => { encoding => 'quoted-printable', charset => 'ISO-8859-1', }, body_str => "Happy birthday to you!n", ); # send the message use Email::Sender::Simple qw(sendmail); sendmail($message); Figure 16 – Perl http://www.perl.org/ http://perl6.org/
JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 27 Microsoft subsequently released J#, which was also discontinued and does not work with any version of the.NET framework beyond .NET Studio 2005. The Sun-Microsoft lawsuit resulted in the release of internal Microsoft documents revealing what they referred to as an “embrace-extend- exterminate” corporate strategy. Microsoft planned to adopt industry standards, co-opt the standards by extending them to include Microsoft-only features linked to their operating systems, then attempt to drive their competitors from the market by not letting other companies use the new features7. C# was released by Microsoft during their legal battle with Sun. Despite its name, many people believe it is closer to Java than to C++, although over the years the two languages have developed in different directions. In the article “Why Microsoft’s C# Isn’t” in a January 2002 edition of CNET News, James Gosling was asked about his reaction to C#. He replied: "The trite answer is, 'Imitation is the sincerest form of flattery…But the other answer is, 'You guys
(at Microsoft) still don't get it,' because it's sort of Java with reliability, productivity and security deleted… They had this problem in their design rules that they had to support C and C++, which means you have to have a memory model where you can access everything at all times. It's the existence of those loopholes that is the source of security, reliability and productivity problems for developers.” 8 C# has replaced VB.NET as the most popular programming language for the.NET environment. Microsoft C# is a proprietary closed source language, meaning the source code is not available. The ISO released a C# standard in 2003, and a revision to the standard in 2006. To date, a few open source C# compilers exist, but none are full implementations of C#. Microsoft has extended its version of C# to include features not in the ISO standard. Objective C and Swift Objective C was originally developed by Brad Cox and Tom Love at Productivity Products International (later renamed StepStone) in the early 1980s – roughly the same time the C++ language was released.
Like C++, Objective C was intended to add Smalltalk-like objects to C programming. The language was not widely used until it was adopted by Apple as the language of choice for iPhone and iPad programming. The NeXT computer company (founded by Steve Jobs) acquired the rights to Objective C from StepStone in 1995. In 1996 Apple bought the Next company and Jobs returned to Apple. The Objective C language became available for the Mac OS X operating system and later became the preferred language for the iOS operating system used on iPhones and iPads. C is a subset of Objective C, just as it is with C++. The object- oriented nature of the language is actually closer to the original Smalltalk than to C++. Objective C syntax is different from the C++/Java syntax. 7 See the ZDNets Newsletter, Nov 9, 1998, available online at: http://www.zdnet.com/news/intel-exec-ms-wanted-to-extend- embrace-and-extinguish-competition/100925 8 available on the Web at: http://news.cnet.com/2100-1082- 817522.html http://news.cnet.com/2100-1082-817522.html
JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 28 For example, methods are not called from other methods in Objective C, they are invoked by message passing. There are many other differences between the two languages and how they are used, but they are best understood by experienced programmers. Basic logic and control – branching, looping, and so on – is similar to the Algol-derived syntax in C, C++, and Java. The primary difference between Objective C and Java is in their target systems: Java is a cross platform language for programming devices on large heterogeneous networks, while Objective C is used almost exclusively for programming OS X and iOS devices, especially iPhones and iPads. At Apple’s 2014 Word Wide Developer’s Conference, the company introduced a new language called Swift, and announced that Objective C would be replaced by Swift. Apple Vice President Craig Federighi referred to Swift as “Objective C without the C”.9 Python The Python programming language was developed by Guido van Rossum, a Dutch-born computer
scientist who now lives in the United States. He began developing Python as a scripting language to replace ABC, an earlier teaching and prototyping language he had helped develop. Van Rossum said that he choose the name Python because he is a big fan of Monty Python's Flying Circus and he was in an irreverent mood at the time. 9 See Venture Beat News, June 5, 2014. Online at: http://venturebeat.com/2014/06/02/apple-introduces-a-new- programming- language-swift-objective-c-without-the-c/ // part of a tic tac toe game written in Swift // from https://developer.apple.com/wwdc/resources/sample- code/ unc placedPiece(x : Int, y : Int) -> Bool { let piece = board.pieceAt(x, y: y) if piece.isOpen { if whoseTurnIsIt == 1 { piece?.playerOwner = player1 }
else { piece?.playerOwner = player2 } viewController.collectionView.reloadItemsAtIndexPaths([NSIn dexPath(forRow: x, inSection: y)]) nextTurn() return true } return false } Figure 17 – Swift JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 29 Van Rossum succinctly described Python in an article titled: “What is Python? Executive Summary” on the Web at https://www.python.org/doc/essays/blurb : “Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic
typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.” # mySQLconnectDemo.py # mySQL database remote connection and query example # last edited Dec 8, 2014 by C. Herbert import mysql.connector # connection information # host IP address: 68.178.216.151 # database: CWHDemo # username: student # password: Student%123 (Note capital "S" in password,
but not in username. # set up a configuration list as a python dictionary config = { 'user': 'student', 'password': 'Student%123', 'host': '68.178.216.151', 'database': 'CWHDemo', } # connect to the database and create a cursorf cnx = mysql.connector.connect(**config) cur = cnx.cursor() # execute a query to display all pets queryString = "SELECT * FROM pet ORDER BY name;"; print queryString, "n" cur.execute(queryString) rs = cur.fetchall()
print "%-12s%-12s%-12s " % ("Name", "Owner", "Species") print"************************************************ *************" for row in rs: print "%-12s%-12s%-12s " % (row[0], row[1], row[2]) print"************************************************ *************" cnx.close() Figure 18 – Python https://www.python.org/doc/essays/blurb JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 30 Van Rossum designed a language that was easy to read, east to write and easy to debug, with exception handling built into the Python interpreter. Exceptions are objects that are created detailing what happens when a computer program doesn’t run properly. Exception handling is a major topic in Java programming which you will learn more about later. Python programs are easy to create and run, but Python programs are slower than programs written in
major production languages like Java because they are interpreted. In a 1997 comparison of Java and Python, Van Rossum wrote that “Python programs are generally expected to run slower than Java programs, but they also take much less time to develop. Python programs are typically 3-5 times shorter than equivalent Java programs.” 10 Remember, interpreted programs must be translated line by line each time the program runs, making them slower than compiled programs whose translated version of a program is ready to run. Java adds the JVM step for portability, but it is still significantly faster than interpreted software. Van Rossum suggests that Java and Python complement each other well, with Python suited to prototyping software designs that can be more fully developed as components of large systems using Java. He also suggests that Python is well-suited for a scripting language used for quick, short applications in place of other scripting languages like JavaScript, and as a “glue language” to create short pieces of software that “tie together” components of large systems.
Python is free open source software. For more about Python see the Python Website at: Python.org . JavaScript JavaScript was developed by Netscape and announced by NetScape and Sun Microsystems in 1995: “JavaScript is an easy-to-use object scripting language designed for creating live online applications … JavaScript is designed for use by HTML page authors …it can be used by people with little or no programming experience to quickly construct applications.” 11 JavaScript is implemented as an interpreted language built into Web browsers. Short quick programs add interactivity and other feature to Web pages through HTML code that includes JavaScript. All version of Microsoft Internet Explorer since 1996 include support for JavaScript, as do the Chrome, Firefox, Safari, and Opera browsers. Bredan Eich, one of the cofounders of the Mozilla project, developed the original version of JavaScript for use in the Netscape Navigator Web browser – viewed by many as the “grandfather” of most modern Web browsers.
10 Comparing Python to Other Languages, a blog entry available on the Web at: https://www.python.org/doc/essays/comparisons 11 The original 1995 press release from NetScape and Sun is available on the Web at https://web.archive.org/web/20070916144913/http://wp.netscap e.com/newsref/pr/newsrelease67.html http://www.python.org/ https://www.python.org/doc/essays/comparisons https://web.archive.org/web/20070916144913/http:/wp.netscape. com/newsref/pr/newsrelease67.html JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 31 ECMA International (formerly the European Computer Manufacturers Association ) developed a standard for Web scripting languages based on JavaScript. Today JavaScript, JScript, ActionScript and several other Web and network scripting languages are all considered implementations of the ECMAScript Standard, which was adopt by the ISO in 1997 and updated in 1999, 2009 and 2011. JavaScript and other ECMAScript languages have a structured syntax similar to C (which is similar to Java and can be traced back to Algol) for branching, looping and
simple arithmetic. JavaScript can be called object-based, but it does not require or support true object- oriented programming like Java. In practice, JavaScript software is usually limited to simple programs that add features such as interactivity and the ability to perform calculations in HTML web pages. As its name indicates, it can be thought of as Java- light, although a number of its feature differ from those in Java. To learn more about JavaScript, see the W3 Schools Java Tutorial, on the Web at: http://www.w3schools.com/js (w3schools.com has introductory tutorials for many other scripting languages used for Web development.) The Website www.Javascriptsource.com has an extensive “cut and paste” repository of freely available JavaScript programs that can be used in Web page development. PHP PHP is a freely available server-side scripting language primarily used for applications involving HTML Web pages. The language was originally developed as Personal Home Page Tools (PHP Tools) and Personal Home Page Forms Interpreter (PHP FI) by Rasmus Lerdorf, a Canadian Computer Software
engineer from Greenland who had contributed to the development of the Apache server software. He has said he created the PHP interpreter for his own use to process HTML Web forms and communicate with databases. The source code for the language was freely released to the public in 199512. in 1997, two students from Tel Aviv University, Andi Gutmans and Zeev Suraski, began working with Lerdorf to turn PHP into a more useful programming language. PHP 3.0, the first version of PHP similar to the current language, was released in 1998 and gained some popularity as a scripting language for Web development as the Internet began to grow. PHP is now maintained by The PHP Group as a general-purpose scripting language that is still used primarily for Web development. According to the group, the name PHP now stands for “PHP Hypertext Preprocessor”. The most recent version of PHP is PHP 5. There are some issues that have prevented PHP from being more widely used as a general purpose scripting language. There is no ISO standard for PHP and the licensing agreement, though free and open- source, has some restrictions on the use of the name PHP or
names derived from PHP13. PHP does not fully support ISO’s Unicode standard for the encoding of character data, as most languages do. 12 See the history of PHP online at; http://php.net/manual/en/history.php.php 13 See: http://php.net/license http://www.w3schools.com/js http://www.javascriptsource.com/ http://php.net/manual/en/history.php.php http://php.net/license JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 32 In 2013 Google reported that its Safe Browsing Service had found malware in versions of the PHP source code being distributed to the public. The PHP group locked down its site, moved to new servers, and applied for a new security certificate. Despite these issues, several million Web developers continue to use PHP as a scripting language for Web development. Ruby Ruby was developed by Yukihiro Matsumoto in Japan as a true object-oriented scripting language with
functional programming capabilities. He said the name came from a colleague’s birthstone14. The first version of Ruby 1.0 was released to the public in 1996. It quickly became very popular for Web scripting in Japan, but was rarely used elsewhere before 2000, when the first English language Ruby documentation became available. The language declined a bit in popularity in 2003 when Ruby 1.8 was released. Ruby 1.8 was incompatible with older versions of the language, and a lot of Ruby applications had to be rewritten. Interest in Ruby began to increase significantly in 2005 when David Heinemeier Hansson, a Danish professional programmer and race car driver, used Ruby to develop the Rails framework for Web scripting that was especially well suited to mapping data from relational database tables to HTML Web pages. Apple included it with its OS X operating system in 2007. Since then, the language and the Ruby on Rails framework have steadily been increasing in popularity internationally. 14 An Interview with the Creator of Ruby, from the LInuxDevCenter Website, online at: http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.ht
ml <!—PHP/HTML page visit counter (using cookies) from: http://www.java2s.com/Code/Php/ <?php if (!isset($_COOKIE['visits'])) $_COOKIE['visits'] = 0; $visits = $_COOKIE['visits'] + 1; setcookie('visits',$visits,time()+3600*24*365); ?> <html> <head> <title> Title </title> </head> <body> <?php if ($visits > 1) { echo("This is visit number $visits."); } else { // First visit echo('Welcome to my Website! Click here for a tour!');
} ?> </body> </html> Figure 19 – PHP http://www.java2s.com/Code/Php/ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 33 The ISO issued a standard for the Ruby language in 2012. Ruby and Ruby on Rails are both freely available. The most recent version of Ruby, Ruby 2.1 was released by The Ruby Community late in 2013. There are several versions of Ruby in use today, such as JRuby which utilizes the Java Virtual Machine for cross-platform programming, MacRuby for Apple’s OS X operating system, IronRuby for the Microsoft .NET environment, and mruby – a light version of Ruby for Web applications. For more about Ruby see the official Ruby Website at: https://www.ruby-lang.org CheckPoint 1.3 1. What is the difference between machine code and assembly
language? 2. What is the difference between a compiler and an interpreter? 3. What is Java bytecode and how is it related to what IBM has called “the Java advantage”? 4. What is functional programming and what is most functional programming based on? 5. List and describe the importance of several historical programming languages and several programming languages currently in use. # mySQLconnectDemo.rb # Ruby mySQL connection and query example # last edited Dec 16, 2014 by C. Herbert require "mysql" begin con = Mysql.new '68.178.216.151', 'student', 'Student%123', 'CWHDemo' # execute a query to display all pets queryString = "SELECT * FROM pet ORDER BY name;"
puts queryString rs = con.query(queryString) n_rows = rs.num_rows puts "There are #{n_rows} rows in the result set." n_rows.times do puts rs.fetch_row.join("s") end rescue Mysql::Error => e puts e.errno puts e.error ensure con.close if con end Figure 20 – Ruby https://www.ruby-lang.org/
JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 34 Lesson 1.4 The Java Programming Language History and Development of the Java Language The Java programming language was developed by a team at Sun Microsystems led by chief developer James Gosling. (Sun was acquired by Oracle Corporation in 2010.) Sun started the development of Java in the early 1990s as a language for multimedia programming, but as the language developed, the internet blossomed – in particular the World Wide Web portion of the Internet. Quoting from Gosling’s early description of Java15: “The design requirements of the Java programming language are driven by the nature of the computing environments in which software must be deployed. …To live in the world of electronic commerce and distribution, Java technology must enable the development of secure, high performance, and highly robust applications on multiple platforms in heterogeneous, distributed networks.”
A heterogeneous network is a network that connects computers with different hardware and different operating systems. A distributed network is a network of computer equipment that connects many machines with CPU’s of their own, rather than connecting many devices to one CPU. The Internet is a heterogeneous, distributed network; in fact, it the most heterogeneous and most distributed network of all time. As the Internet grew, so did the use of Java, which was perfectly suited for Web-based programming. Sun was interested in developing a language in which applications could be created and distributed across many different computers, not just for one computer or one family of computers. Java’s built-in networking and security, distributed approach to computing, and multimedia capabilities fit in very well with the rise of the World Wide Web, and Java quickly became the language of choice for the development and delivery of software using the Internet. Today, more devices connected to the internet use Java than all other programming languages combined. There are more Java Runtime
Environments installed on computers, tablets and smartphones – and embedded in kitchen appliances, automobiles, industrial equipment and other systems – than all Android, Windows and iOS systems combined16. Sun Microsystems was acquired by Oracle Corporation in 2010. Oracle has continued to make Java freely available to the public. They have continued to update the language through the Java Community Process, a mechanism for proposing changes to Java. (see www.jcp.org.) Major changes in the language result in a new version of the language. Minor changes to the java compiler and related software result in a new release of the most current version of the language. The most recent version of Java is Java 8, released in 2014. As of January 2015, the most recent edition of Java is Java 8, release 25. 15 Design Goals of the Java TM Programming Language from The Java Language Environment by James Gosling and henry McGilton, May, 1996 Available online at: http://www.oracle.com/technetwork/Java/intro-141325.html 16 Learn About Java Technology, an oracle publication, online at http://www.Java.com/en/about http://www.jcp.org/
http://www.oracle.com/technetwork/Java/intro-141325.html http://www.java.com/en/about JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 35 The syntax of the Java language was based on C++, the most popular programming language at the time Java was introduced, so it would be familiar to programmers. Therefore, it can be traced back to Algol through C++ and C. Unlike C++, it requires all programs to be methods in objects, so it is a true object- oriented language. It has features limiting the use of low level system calls that can introduce security hazards in languages such as C and C++. We will learn more about the nature and history of Java while we learn to use Java as a tool for the development of software applications. A Look at Java Source Code Every Java program requires at least one class of objects to get things started. New programming projects in Java often have a class for the project itself, with the project’s startup code in a main method in the project’s class. This is what we will do in the first part of CSCI 111.
Here is an example of code from a Java programming project, showing the parts of the project: /* * CSCI 111 Spring 2015 * This application converts feet to yards and meter * and displays a table of the values for 1,000 to 10,000 yards */ package feetyardsmeters; public class FeetYardsMeters { // method prints a table from 1k to 10k yds. public static void main(String[] args) { double yards; // value in yards double feet; // value in feet double meters; // value in meters // print column headers -- t is the tab character System.out.println("yardstfeettmeters");
// loop to print the data in rows and columns for( yards = 1000; yards <= 10000; yards = yards + 1000) { feet = yards * 3; meters = yards * 0.9144; System.out.println(yards + "t" + feet + "t" + meters); } // end for } // end main } // end class FeetYardsMeters The code starts with a comment identifying the project and the programmer. Comments do not affect how the code runs. block comment package directive class declaration one line
comment method header one line comment body of the method comment variable declarations comment Figure 21 – Java sample JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 36 A package directive identifies a Netbeans (or Eclipse) programming package, then the class declaration marks the beginning of the class. The class name for the package’s class will be the same as the package name. In CSCI 111, Netbeans will set these up for you when you start a project. The code above has a header at the start of the main method: public static void main(String[] args)
The words public, static and void are modifiers that describe how the method will work. You will learn more about them as you learn Java. The name of the methods is main, followed by parameters for the method in parenthesis. The parameter (String[] args) is a default argument for a package’s main method. When you start a new project in NetBeans, you only need to specify the project’s name. The rest of the items in the method header will be generated by NetBeans for you. The actual code to make things work is inside the main method. Notice that braces { } mark the beginning and end of a block of code. In this case there are braces for the class, for the main method, and for the block of code in thefor loop inside the main method. As with everything else in this example, you will learn more about how to use braces as you learn Java. The actual code is rather short. First, three double precision floating point variables are named (yards, feet and meters), then the program prints a header for a table of values, followed by a loop to print the data in the table.
Why Java? Here is the same program as the Java project above, but written in the Python programming language: ''' CSCI 111 Spring 2015 (Python script) This application converts feet to yards and meter and displays a table of the values for 1,000 to 10,000 yards ''' # print the table’s heading print "yardstfeettmeterst" # print the table’s data for yards in range(1000,10000, 1000): print yards, "t", yards*3, "t", yards*0.9144 The python code looks so much easier! No package directives or class declarations, no braces, no method header, etc. are needed for this simple algorithm. If that’s the case, then why bother with all of the kerfuffle of Java? block comment
one line comment Figure 22 – Python sample JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 37 The answer lies in the purpose of CSCI 111. One of the main goals of CSCI 111, CSCI 112, and CSCI 211 is to help students prepare to become professional software developers. Java is a very sophisticated software development tool, which may seem like overkill for the introductory topics a new programmer needs to learn, but we chose Java because of its market dominance, its usefulness for large software development projects, and the fact that the language and techniques of object-oriented programming in Java are easily transferable to many other languages. Python allows you to quickly and easily create code for simple tasks. However, the resulting software runs inefficiently and is not secure enough for things like banking or medical systems. It is not as easily used across different platforms as Java is. For these reasons and a variety of other reasons, Python, and
several other scripting languages, are not well-suited for large scale software development. Python is very useful – indeed, just about anything that can be done in Java can be done in Python. It is great for writing short bits of code, such as a Cisco script to initialize a network router. It can be used to prototype or test the design of large software systems, and is often used as a glue language to quickly and easily tie together large software modules created in other languages. Yet most large scale professional software development is done with Java and a few similar languages. But what about Java compared to languages like C++, or C#? Do you remember the Java advantage discussed earlier in the chapter? A Java compiler first translates Java source code into Java bytecode, which can be stored and moved from one platform to another as Java .class files. To run Java, a machine only needs a Java Runtime Environment (JRE) with a JVM that translates and runs the Java bytecode as machine code for the host platform. The JVM’s rapid translation from bytecode to machine code provides high performance. The use of bytecode, combined with the widespread availability of JVMs for almost all
processors, makes Java software very portable. In fact, as of January, 2014 Oracle states that: “Java technology is already present in today’s embedded systems, in 5 billion SIMs and Smart Cards, 3 billion mobile handsets, 80 million TV devices, including every Blu-ray player shipped, and many other embedded solutions from printers and bank machines to e- book readers and cars.” 17 One reason for Java’s widespread use is the availability of many Java Application Programming Interfaces, the most common of which are included as part of the JRE. An Application Programming Interface (API) is a software library with classes and methods that extend a programming language for a specific purpose, such as for graphics, sound, database connectivity, or network security. Java has one of the most extensive set of APIs of any programming language. We will use some Java APIs in CSCI 111, but more extensive coverage of Java APIs is included in CSCI 112. For these reasons, and for others beyond the scope of this course, Java is the language of choice in Computer Science courses at Community College of Philadelphia.
17 See: http://www.oracle.com/technetwork/topics/newtojava/document ation/faqs-jsp-142592.html JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 38 Versions of Java A Java Development Kit (JDK) contains the tools needed to develop Java software, including a Java language compiler, a Java Runtime Environment with a JVM, and commonly used APIs. There are three main versions of Java Development Kits: 18 – Java SE lets its users develop and deploy Java applications on desktops and servers, as well as embedded environments. It is the core JDK. – Java EE is, according to Oracle, the industry standard for building large-scale web and enterprise applications. – Java ME is a development environment for building applications for mobile and embedded systems. Java ME is augmented by
other development packages for embedded processors, such as Java ME Embedded and the Java SE Embedded Suite. In addition, there are several specialized add-ons to these development kits, such as: – an advanced Java user interface (UI) platform for building multimedia enterprise business applications – Java Card technology enables development of applications that run on smart cards with very limited memory and processing capabilities. Multiple applications can be deployed on a single card, and new ones can be added even after the card has been issued. – Java TV enables development of applications that run on TV and set top box devices: such as Electronic Program Guides (EPG's), Video-on- Demand (VOD), games and educational applications. it can access bonus content on most Blu-ray Disc titles. – Java DB is Oracle's supported distribution of the Apache Derby open source database. It supports standard ISO standard SQL.
CheckPoint 1.4 1. Who developed the Java programing language, and for what purpose? 2. Who owns the Java language and how do they update it? 3. Where is the startup code for a new java programming project placed? 4. Why is Java used in CSCI 111 instead of a simpler and easier to learn language, such as Python, or instead of other production languages, such as C++ or C#? 5. How is Python used by Java software developers? 18 From the Get Started section of Oracle’s New to Java Website, at: http://www.oracle.com/technetwork/topics/newtojava http://www.oracle.com/technetwork/topics/newtojava JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 39 Lab 1 – Getting Started with NetBeans and Java In this step-by-step exercise we will learn to create a simple Java program using the NetBeans IDE. This lesson is similar to the NetBeans IDE Java QuickStart Tutorial which can be found online at:
https://NetBeans.org/kb/docs/Java/quickstart.html This exercise also includes information about: e source code in a new Java project, Computer Science 111. You should download and install Java and NetBeans before starting this exercise. Appendix A contains instructions for downloading and installing the software at home. This exercise uses the most recently available versions of the software as of January 2015: Java SE Development Kit 8 update 25 and NetBeans 8.0.2 Java SE Development Kit 8 update 11 with NetBeans 8.0, are installed in the labs and classrooms at Community College of Philadelphia. This exercise works with these versions of the software. It should also work with any newer releases of Jav 8 or NetBeans 8. Check with your instructor if you have any questions about which version of Java to use.
Hello World! We will create a simple program that displays the message “Hello World!” – traditionally the first program students learn to write in a new programming language. Hello World appeared in A Tutorial for the B Programming language written by Brian Kernighan at Bell labs in 1972. In 1978, his Hello World program became famous as the first program in the Kernighan and Ritchie book, The C Programming Language. It has since become a custom for programmers to try the Hello World program as the first program with a new compiler, or when learning a new programming language. The Hello World program is available in over 300 different programming languages online at several Websites, such as: http://www.mycplus.com/featured-articles/hello-world- programs-in-300-programming-languages Hello World is among the simplest of programs, but we will create it inside a NetBeans project. So, first we will open a new NetBeans project. The layout of the NetBeans IDE depends on the type of project. We will create a simple Java console application, which means our “Hello World!” message will be
displayed in a simple system console window within the IDE. The system console is a combination of the system’s standard input and output devices – usually the keyboard and display screen. https://netbeans.org/kb/docs/java/quickstart.html http://www.mycplus.com/featured-articles/hello-world- programs-in-300-programming-languages JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 40 Figure 22 shows the console output as it appears when we run the program in NetBeans. The output – in this case simply “Hello World” – appears between the run message and the Build Successful message. The steps below will show you how to create a Java Hello World program with console output using NetBeans. Our reference for Java-related terminology will be the Java Language Specification (JLS).19 Creating a New Java Project – Step-by-Step STEP 1.
Start your computer and run the NetBeans software by using the NetBeans desktop icon or finding NetBeans on your system. NetBeans will take a moment to start, then you should see either a blank Netbeans IDE or the IDE with the Learn & Discover startup screen, as shown below. If you wish, you can deselect the checkbox in the upper-right corner of the startup screen to stop showing the screen when the IDE starts. You can bring back the startup screen by choosing Reset Windows from the NetBeans Windows drop-down menu. 19 The Java Language Specification, (JLS) is online at: http://docs.oracle.com/Javase/specs Figure 23. Hello World! as NetBeans Console output. Figure 24 – NetBeans Startup Screen http://docs.oracle.com/javase/specs JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg.
41 STEP 2. Select New Project from the File menu. According to the NetBeans documentation, “A project is a group of source files and the settings with which you build, run, and debug those source files. In the IDE, all Java development has to take place within a project.” The NetBeans New Project wizard will open, as shown in Figure 26. The wizard’s Choose Project window has a Categories section on the left and a Projects section on the right. They are used to tell NetBeans the type of project for which it should configure the IDE. Figure 25 – Blank NetBeans IDE Figure 26 – Choose Project Type
JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 42 STEP 3. Select Java in the Categories section, then Java Application in the Projects section to configure the IDE for a standard Java application, then Click the [Next] button to continue. Almost all programming assignments in CSCI 111 will be standard Java applications. A New Java Application window will appear as shown in Figure 27. The window has text boxes to enter the project’s name and storage location. STEP 4. Type HelloWorld in the Project Name field. It should be in CamelCase, with no spaces. (See the box about CamelCase names on the next page.) Leave the project location and folder as the default. On a Windows system, this will create a new folder for the project in the Netbeans folder under Documents. The wizard also has options to use a dedicated folder for sharing Libraries and to create the application’s main class. We will not use a dedicated folder for libraries in this project. We also should leave the
main class as the default, which is based on the project name. Most Java applications require the project, project folder, and the project’s main class to have the same name. Click [Finish] to continue. NetBeans will take a moment to create and open a project configured for editing source code as a Java application. There are three windows open in the NetBeans interface, as shown in Figure 28: ❶the project window, ❷the navigator window, ❸the editor window. Figure 27 – Name and Location JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 43 HelloWorld will be a simple application with only a single source code class, and that class will have only one method. Next, we will look at a description of the source code the wizard generated, then return to our step-by-step exercise.
CamelCase Names in Java Java programmers customarily use the camelCase naming convention for the names of classes, objects, methods, and other items. CamelCase is the practice of writing compound names without using blank spaces, but capitalizing the first letter of each name that forms the compound name, as in “CamelCase.” If the first letter of the compound name is upper case, then we have upper CamelCase. If the first letter is lower case, then we have lower camelCase. Java class names are usually in upper CamelCase, while the names of instances of a class, properties, methods, and variables are usually in lower camelCase. This is not a requirement that will be enforced by a Java compiler, but is instead a programming convention. Programming conventions are rules that most programmers follow to make the work of one programmer compatible with the work of another, and to make code easier to understand. It is good practice to follow known programming conventions. Sometimes there is a slight variation in the naming convention to aid readability and make the meaning of a name easier to understand, such as a property named
studentID where the I and D are both capitalized. Oracle, Microsoft, Apple, and many other companies encourage the use of CamelCase names in software development. Quoting from Oracle’s Java Language Basics tutorial “If the [class] name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word.” (See Naming on Oracle’s Java Tutorials page, at: http://docs.oracle.com/Javase/tutorial/Java/nutsandbolts/variabl es.html ) Figure 28 – A new Java project JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 44 Description of the Source Code in a New Java Project The default source code for the new Java Project created by the Java Application Wizard in NetBeans is shown in Figure 29. Take a moment to look it over. Notice that each line in the Editor is conveniently numbered. This is a reference feature of the editor, not part of
the Java code. The code generated by the new project wizard includes: includes: headers and the Java Application Project Wizard Template. (Don’t even think about trying this until you are a more experienced NetBeans and user.) package directive telling the compiler which Java package will contain this software. Each CSCI 111 program will be in its own package. This name is generated by the Java Application Project Wizard Template. Later we will learn about establishing our own packages. the code. We will expand on this later in this exercise. HelloWorld class. The class is a public class, meaning that is can be accessed by software from outside the package. At least one class in each package must be a public class, so that the
software can be run from the operating system. Figure 29 – default source code JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 45 parameters for the method following on line 18. – the only method in our class. The name of the method is main, with a lowercase m. It is a Java naming convention to start method names with a lowercase letter. A parameter list, in parenthesis, follows the method name in the method header A Parameter is a value that is passed to a method when it runs. For example, if a method finds the sine of X degrees, where X could be any integer, then the value 45 might be passed to the method as a parameter to ask the method to find the sine of 45 degrees.
A method can have more than one parameter. Each parameters passed to a method is also called an argument of the method, and the list of parameters in the method header is also called the argument list. The comment on lines 15 through 17 is often used to describe the arguments in the argument list. It is also a good idea to add a comment before a method to describe what the method is intended to do. This method does not use any parameters, although a String array named args is allowed for by the presence of String[] args in the method header, and is referenced by the comment that precedes it. Every Java application project must have at least one class with a main method. This is the place where our application will start. When a Java application is executed, the main method is the first method that will run. In the case of our Hello World application, it is the only method that will run. This will be true for our first few programming exercises in CSCI 111. The keywords public, static and void in the method header are important. public means the method can be run from outside the class.
class itself, not with an instance of the class. Only static methods can be run without a reference to a specific instance of an object. We will learn more about this later in the semester. For now, our methods will be static methods. example, a square root method might. We will leave these keywords as is. Every Java application’s main method must be a public static void method. Notice that blocks of code in Java begin and end with braces { block of code }. (Braces are also often called brackets. The Java Language Specification uses the term braces.) This includes classes, methods, and other units of code. The NetBeans wizard places the beginning brace on the same line as the class or method header, then places the ending brace on a line by itself after the last line of the block. The blocks of code should be indented to make the blocks easier to identify. The NetBeans Source Code Editor will indent blocks of code automatically.
JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 46 Some of the items in the source code are comments. Comments are notes for programmers reading the source code, but they do not affect the way the program runs. In fact, comments are stripped out of the code as it is compiled. Comments are important. They appear as documentation, helping to make our source code easier to read and understand – for both ourselves and other programmers. Comments can be included in Java source code as in-line comments or block comments. An In-line comment begin with a double slash, like this: //This is an in-line comment. Everything after the double slash is a comment, ignored by the compiler, but everything before the double slash is part of the code, not part of the comment. All of Line 19 in the source code in Figure 29 is an in-line comment. The line below shows how an in-line a comment can be included after a Java instruction: double yards; //This is an in-line comment.
A block comment begins with a slash-star and end with a star- slash, like this: /* This is a block comment. It is three lines long. * In this comment, the star-slash is on the third line, * lined up with the beginning slash-star. */ Star refers to the asterisk, on the same key as the number 8 on a QWERTY keyboard. Everything typed between the slash-star marking the beginning of the comment and the star-slash marking the end of the comment – no matter how many lines – is part of the block comment and will be ignored by the compiler. Many programmers line up the stars in the slash-star at the beginning of a block comment and the star- slash at the end. They may also place a star on each line to make it clear that this is part of a comment. The NetBeans Source Code Editor will automatically add a star the beginning of each line in a block comment. Lines 1 through 5 in Figure 29 show this. There are three block comments and a single one line comment in the code that the Java Application
Project Wizard created to help get us started. It is really up to you how you format your block comments, as long as they are clear and easy to read. It is a good idea to ask your instructor in a class or check with your employer on the job to see what they would like you to do. Java code must run correctly and efficiently, but the readability of the source code is also very important. Comments and programming style should make the source code easier to read and understand. Sometimes a small touch can make a difference – in this example, line 18 is blank. The separation between the two lines with ending braces makes the code easier to read in a subtle way. Next we will finish our exercise by modifying the code created by the Java Application Wizard to create our Hello World program. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 47 Hello World! – Step-by-Step (continued) STEP 5.
Modify the comment above the package directive on lines 1-5 to include the following identifying information instead of the default message: – Hello World Application – created for CSCI 111. Your instructor may also want you to include the semester and section number. – last modified [date and approx. time]. - @author [your name]. @author is a JavaDoc tag, which we will learn about later in the semester. For now, be sure to include the tag in front of your name. STEP 6. Delete the comment on lines 9 through 12. It is no longer needed because of the information in the code’s opening comment. STEP 7.
Change the comment preceding the method header to briefly describe what the method does – main method prints a message on the screen. The comment already has a Javadoc parameter tag (@param) identifying the method’s parameters. We will not use these parameters, but they could be used by a more experienced Java user, so we will leave the @param as is. It is also always a good idea to include a brief comment at the beginning of a method to state what the method does (or at least what the programmer thinks it does.). That is what we are doing in this step, resulting in the code shown on the next page. The code in your project should now look something like that in Figure 31. Figure 30 – edited opening comment JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 48 STEP 8.
Replace the TO DO comment on line 16 with the instruction: System.out.println("Hello World!"); This is the actual Java code to be executed. The TODO comment is only a placeholder put there by the NetBeans wizard. Notice that the new line ends in a semicolon. This is necessary in Java. Each individual instruction in a block of code ends in a semicolon in Java. The System.out.println command tells Java to print the character string “Hello World!” on the standard system console output unit. system commands in its library. – to send something to the console output. print by itself, without the ln, would tell Java to print the message then wait on the line for whatever comes next. println tells Java to behave as if [Enter] is pressed after the message, whereas print is similar to typing something without pressing [Enter] at the end of the line. Here we use
println. s enclose the argument of the command – what is to be printed. – this means we are telling Java to literally print the exact string of characters between the opening and closing quotes – Hello World! Figure 31 – modified Java project Figure 32 – System.out.println JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 49 STEP 9. Add an in-line comment after the ending brace on line 17 – // end main(). This makes it clear that the brace is for the end of the main method. It doesn’t seem like a big deal for our short program, but in longer programs with many blocks of code it adds to readability and could save hours trying to debug code with a missing brace.
STEP 10. Add an in-line comment after the ending brace on line 19 – // end class HelloWorld. Make sure to leave a blank line between the end main brace and the end class brace. This it easier to see the structure of the code when reading the code. We are now finished editing the program and it is ready to run. It should resemble the code in Figure 31. NetBeans Notes – Copy and Paste Here’s a tip to improve your efficiency and cut down on typographical errors: use copy and paste to copy method or class header information to the comment marking the block’s ending brace. Generally, cut, copy and paste are a programmer’s friends. Public class HelloWorld { . . .
} // end class HelloWorld Figure 33 – completed Hello World! code JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 50 STEP 11. Run the application by selecting Run Project from the Run menu. The Run Project command is at the top of the menu. You could also use the F6 key to run a Java application in Netbeans. It will take a moment for Java to compile the source code before it runs the application. The image on the right shows us the console output as it appears when the program runs from inside NetBeans. The output from the program appears in a window below the Source Code Editor, with the actual output from the application between the run message and the
Build Successful message. Source code and other project elements are automatically saved when we run a project in NetBeans. We do not need to save before running, although it is a good idea to save any code that you have worked on for a while without either running or saving the project. Closing NetBeans Properly Projects remain open in NetBeans until they are purposely closed. If you exit NetBeans without closing a project, then normally the same project will be open when you restart NetBeans. You must specifically close a project when you are finished working on it. NetBeans Notes – Resizing IDE Windows The windows in the NetBeans interface can be re-sized by clicking and dragging the boundaries between the windows, either horizontally or vertically. Figure 35 – Hello World! console output in a
NetBeans Console Window. Figure 34 – the run menu JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 51 STEP 12. To close your project, select the HelloWorld project in the Project window, then select Close Project on the NetBeans File Menu, to close the project. After closing the project, the NetBeans interface should be blank. When you are ready to exit NetBeans, select Exit from the bottom of the File menu. When you re- open NetBeans, you can open your project by selecting Open Project form the NetBeans File Menu, or by selecting Open Recent Project. Copying and Submitting NetBeans Projects Each NetBeans project is stored in its own folder, within the NetBeansProjects folder on the host computer. If you installed NetBeans 8 on a Windows system as
directed in Appendix 1, then the NetBeansProjects folder will be in the Documents folder (My Documents on some systems) On other systems, or if you are not sure where the project folder is, then you can search for the NetBeansProjects folder and check its contents. To copy a NetBeansProject from one computer to another, copy the individual project folder from the NetBeansProjects folder on one system to the NetBeansProjects folder on another system. You could also zip/unzip the project folder to make moving it or storing a copy of it more convenient. Actually, a netbeans project folder will work from almost anywhere you put it on your computer, such as on the desktop. To submit a CSCI 111 programming assignment to your instructor: the NetBeans project folder. folder by using the upload link for the assignment in Canvas. You can also send it as an attachment to a Canvas message or as an
attachment to a regular email message. If you have a question about your code, it is often convenient to send your instructor a copy of the code attached to a message with the question. Figure 36 – closing a NetBeans project JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 52 Key Terms in Chapter 1 After completing this chapter, You should be able to define each of the following key terms: Algol, 16 algorithm, 9 argument list, 43 assembler, 11 assembly language, 11 BASIC, 19 block comment, 44 braces, 43
byte code, 13 C programming language, 21 C#, 24 C++, 23 class, 10 COBOL, 17 compiler, 12 computation, 4 computer engineering, 6 computer program, 9 computer science, 4 device drivers, 5 distributed network, 32 external storage, 3 FORTRAN, 14 heterogeneous network, 32 high-level languages, 12 human–computer interaction (HCI), 4
I/O, 4 in-line comment, 44 input units, 4 internal memory, 3 interpreter, 12 instance, 10 Java, 32 Java Runtime Environment, 13, 35 JavaScript, 28 JLS, 38 Lambda Calculus, 18 LISP, 18 machine code, 11 methods, 10 mnemonics, 11 object, 10 object code, 12 Objective C, 25
object-oriented programming, 10 operating system, 5 output units, 4 parameter, 43 Pascal, 20 peripherals, 4 Perl, 24 PHP, 29 property, 10 public, 43 Python, 26 random access memory (RAM), 3 read only memory (ROM), 3 Ruby, 30 scripting languages, 13 Simula, 22 Smalltalk, 22 source code, 12
static, 43 system console, 37 system utilities, 5 System.out.println, 46 Warning! – Flash ROM Failures USB flash ROM drives are convenient, but they can suddenly go bad without warning. They are good for moving data from one computer to another, but you should not rely on them as a backup copy of your data. Flash ROM technology is good for a limited number of write cycles -- usually about 10,000 cycles. Working directly from a flash ROM drive could result in hundreds of accesses per hour. Someone in the habit of working directly on the USB device could have the chip go bad in a few weeks of use. (More robust industrial grade flash ROM chips last for up to 1 million write operations, but are more expensive – $50 to $75 per gigabyte in 2013.) Instead of working directly on a flash ROM drive, you can copy your work to a computer’s hard drive, do
some work on your program, then copy your work back to the USB drive when you need to move it to another machine. If a file or folder is not too large, you can send it to yourself as an email attachment, then open the email message on another computer and save a copy of the attachment. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 53 Chapter 1 - Questions 1. What are the primary components of most computer systems? How are these components connected to one another? 2. What is inside a central processing unit and what is the function of each of these things? 3. How does internal memory differ from external storage? 4. For whom are algorithms named? Where and when did he do his most important work? What method for solving math problems did he present in his work? Why is his work important in the history of math and computer science? How is it related to computer
programming? 5. How are algorithms related to computer programs? 6. Why did computer scientists introduce object-oriented programming? What can be represented by an object in object-oriented programming? How are data and programs that manipulate data organized in object-oriented programming? 7. What is the difference between a computer engineer and a software engineer? How does their work relate to computer science and other fields? 8. What organization is responsible for accrediting computer science degree programs? What organizations sponsor the accrediting agency, and what do they do? How can it be beneficial for a computer professional to belong to one of these agencies? How can we find out more about their student memberships? 9. What are some of the more common specializations for computer scientists? 10. What is the difference between a high-level language and a low-level language? How does assembly language fit into all of this? How many different assembly languages are there?
11. What do compilers and interpreters do and how do they compare to one another? 12. What is the process for translating Java into machine code for specific systems? What design goals for the Java language led to the development of this method? How did several well-known major computer companies react to the way Java is implemented? What indications do we have of the success of Java’s method of implementation? 13. What early programming language that was not widely used commercially created a foundation for most modern programming languages? What are some of the more important features that first appeared in this language? 14. What programming language was based on Lambda Calculus, and what are some of its modern derivatives? What field of computer science has been most associated with this language? Why is lambda calculus important in computer science? 15. Why are Simula and Smalltalk important in the history of computer programming? Who developed these languages?
16. How is Java related to C and C++? JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 54 17. How did Guido van Rossum suggest Python and Java can be used together? 18. What is a JRE? What is included in a JRE? 19. Who owns the java programming language? How is the language updated? 20. What is a JDK? How do the three main versions of the JDK differ from one another? Chapter 1 - Exercises 1. Modify the HelloWorld project from the exercise is this chapter to print the message “Hello Dr. Kernighan!” on a line after it prints “Hello World!” Remember to update the comments in the code. 2. The bulleted list on page 46 tells us: “println tells Java to print the message then start a new line. print by itself, without the ln, would tell Java to print the message then wait on the line for whatever comes next. println tells Java to behave as if [Enter] is pressed after the message,
whereas print is similar to typing something without pressing [Enter] at the end of the line...” So the following two lines will print Hello. Goodbye. on the same line of console output: System.out.print("Hello. "); System.out.println("Goodbye."); Create a new Java project similar to the HelloWorld project that uses print and println to print the text from a business card for yourself. The output should look something like this: Chuck Herbert Computer Science major Community College of Philadelphia Philadelphia, PA 19130 [email protected] It should include the following items as String literals in the printing commands, not as variables: first name, last name, major, school, city, state, zip, and email address. No two items from this list above may be printed by the same command. For example, your first name should be printed using a print instruction, then your last name
printed using a println instruction. Blank spaces and the comma between city and state should be included. Don’t forget to include the proper comments in your code. 3. Create a diagram that shows the lineage of Java from the earliest programming languages. It should look like a family tree, showing which languages led to which other languages, that, in turn, eventually lead to Java. For example, our tree would show that both the C language and Simula influenced the development of C++. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 55 4. Which of the people mentioned in this chapter do you think is most important or most interesting? Research the person and write a short biography of the person, including what the person did in addition to what’s mentioned in the chapter. Cite your sources. You must use at least two sources of information other than Wikipedia. You can read the Wikipedia article, but should not cite it as source since its information is not fully verified as correct. Original
sources are the best. 5. Identify one of the programming languages in this chapter and look up the language on the site Webopedia.com. Webopedia is good source of information about technical terms related to computers and computer science. Starting with Webopedia and moving on to other sources, see what you can find out about the language write a short description, including what it primarily used for. List several sources of more information, such as language specifications, sources of compilers and interpreters (especially if they are free), and tutorials, and sample code. 6. There are a number of online forums and blogs discussing programming languages. Log into one of these and create or join a conversation addressing the question “What is best programming language is to learn and why?” Consider the difference between the easiest language to start with and the best language to know professionally. See if the comments posted by others seem well-founded or not. Do other people describe what their opinions are based on? Do there seem to be biases for or against certain languages, operating systems, or hardware? Which of the posts seem helpful or not helpful, and
why? Check the site every day for a week, and write a summary of what you observed and learned related to the items mentioned above. 7. A website that has “Hello world!” source code in different programming languages is cited on page 37. Find the code for “Hello world!” in three different languages – one that seems very easy, one that seems similar to Java, and one that seems complicated. Write a short report, which includes the code, telling what language each is in and something about the language, such as what the language is primarily used for. Look up the code for Java on the site and see if the Java code it shows is complete enough to run as a program by itself. If not, what missing? What does this tell you about the completeness of the code in other languages? 8. A list of some specializations in computer science can be found on page 6 along with a link to the ACM’s special interest group page - http://www.acm.org/sigs . Information about the ACM and the IEEE can be found on page 5, including references to their main websites. What specialization in computer science most interests you, even if you have a major other than
computing? What resources, including special interest groups, do the ACM or IEEE have related to your area of interest? What special interest groups might you be interested in joining? What courses other than computer courses might be useful for your area of interest? 9. The U.S. Department of Labor’s Bureau of Labor Statistics maintains the Occupational Outlook Handbook with career information for most job classifications in the U.S. It is online at http://www.bls.gov/ooh/ . (You can get there easily by typing OOH in Google or most other search engines.) They also publish a more current Occupational Outlook Quarterly. Find out what they have to say about careers in computer science and closely related fields. What do the jobs pay? What is the http://www.webopedia.com/ http://www.acm.org/sigs http://www.bls.gov/ooh/ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 56 work like? What education or background is needed? Are there many openings in that particular area?
Write a short report summarizing your findings for several areas related to computing. 10. In addition to NetBeans and Eclipse there are quite a few others IDEs that can be used for for Java software development, such as JCreator, BlueJ, JBuilder, IntelliJ, DrJava, Javelin, and Websphere. See what you can find out on the Web about some of them and write a short report describing your findings. —— 30 —— The Java Learning Kit: Chapter 2 – Reading, Writing, and Arithmetic Copyright 2015-2019 by C. Herbert, all rights reserved. Last edited October, 2019 by C. Herbert This document is a chapter from a draft of the Java Learning Kit, written by Charles Herbert, with editorial input from Craig Nelson, Christopher Quinones, Matthew Staley, and Daphne Herbert. It is available free of charge for students in Computer
Science courses at Community College of Philadelphia during the Spring 2019 semester. This material is protected by United States and international copyright law and may not be reproduced, distributed, transmitted, displayed, published or broadcast without the prior written permission of the copyright holder. You may not alter or remove any trademark, copyright or other notice from copies of the material. The Java Learning Kit: Chapter 2 Reading, Writing, and Arithmetic Lesson 2.1 – Data Types Lesson 2.2 – Variables and Constants Lesson 2.3 – Assignment Statements and Expressions Lesson 2.4 – Data Streams and System Console I/O Lesson 2.5 – Documentation First Programming Lab 2A – Console I/O: Age in Days Lesson 2.6 – JOptionPane Pop-Up Dialog Windows Lab 2B – Pop Up Windows Dialog: Age in Days JLK Chapter 2 – Introduction DRAFT October 2019 pg. 2
Contents Chapter 2 Learning Outcomes ........................................................................................... .... ....................... 4 Data Types ............................................................................................... .......................... 5 Common Data Types in Java ............................................................................................... .................. 5 Variables, Constants, and Literals ............................................................................................... .......... 6 Boolean Data ............................................................................................... .......................................... 6 Text Data ............................................................................................... ................................................ 7 Special Characters in Strings ............................................................................................... .................. 9 Integer Data ........................................................................................... .... ......................................... 10 Floating Point Data ...............................................................................................
............................... 10 IEEE Floating Point Numbers ............................................................................................... ................ 11 CheckPoint 2.1 ............................................................................................... ...................................... 12 Numbers from the Real (and Imaginary) World ................................................................................. 13 Variables and Constants ............................................................................................... ... 14 Local Variables ............................................................................................... ..................................... 14 Constant Declarations ...................................................................................... ......... .......................... 15 Hardcoding ............................................................................................... ........................................... 15 Variable and Constant Names – Java Identifiers ................................................................................ 15 CheckPoint 2.2 ............................................................................................... ...................................... 16
Assignment Statements and Expressions ....................................................................... 17 Polymorphism ............................................................................................... ...................................... 17 Arithmetic Operations ............................................................................................... ......................... 18 Quotients and Remainders ............................................................................................... .................. 19 Unary Operations ............................................................................................... ................................. 19 The Java Math Class ............................................................................................... ............................. 20 Order of Operations ............................................................................................... ............................. 22 Commutative and Associative Behavior ............................................................................................. 24 Type Casting ............................................................................................... ......................................... 25 Cast Operators
............................................................................................... ..................................... 26 CheckPoint 2.3 ............................................................................................... ..................................... 26 Data Streams and System Console I/O ........................................................................... 27 The Scanner Class ............................................................................. .................. ................................. 28 Checkpoint 2.4 ............................................................................................... ..................................... 29 Documentation First Programming ................................................................................ 30 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter%202%20- %20Reading%20Writing%20and%20Arithmetic/JLK%202%201 2%2031%208%20am.docx%23_Toc407776762 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter%202%20- %20Reading%20Writing%20and%20Arithmetic/JLK%202%201 2%2031%208%20am.docx%23_Toc407776765 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter%202%20- %20Reading%20Writing%20and%20Arithmetic/JLK%202%201 2%2031%208%20am.docx%23_Toc407776767 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 3
Lab 2A – Console I/O: Age in Days ............................................................................................... ........... 33 JOptionPane Pop-Up Dialog Windows ............................................................................ 38 Using the JOptionPane Message Dialog Window ............................................................................... 38 Using the JOptionPane Input Dialog Window ..................................................................................... 40 Parsing Numbers from Strings ............................................................................................... ............. 41 Exceptions When Parsing Numbers from Strings ............................................................................... 43 Lab 2B – Pop Up Windows Dialog: Age in Days ................................................................................ ...... 44 Key Terms in Chapter 2 ............................................................................................... ............................ 48 Chapter 2 - Questions ............................................................................................... .............................. 49 Chapter 2 – Exercises ............................................................................................... ............................... 50
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 4 The Java Learning Kit: Chapter 2 Reading, Writing, and Arithmetic This chapter introduces some of the basic elements needed to create Java programs. Lessons 1, 2 and 3 discuss data types and simple arithmetic in Java, including assignment statements and math expressions. Lesson 4 looks at console I/O, which is text input and output based on data streams. We won’t learn how to read and write data files in this chapter – that comes later – but the text data streams used for reading input from the keyboard and writing output to the screen are the basis for working with text data files in Chapter 6. Lesson 5 shows an alternative method of I/O – using pop-up dialog windows, which are more interesting and attractive than console I/O, and are fairly simple to use. Lesson 6 is about the importance of documentation and how to
use documentation as tool to help design and build software. The two labs in the chapter will provide you with some practice using most of the material covered in the chapter. The first lab is based on console I/O and the second lab uses pop-up dialog windows. Chapter 2 Learning Outcomes Upon completion of this chapter students should be able to: • describe the concept of a data type; list and describe the primitive data types in Java; • describe the difference between primitive data types and classes of objects, and how the String data type is unique in this regard; • describe the mathematical concepts of integers, rational numbers, and real numbers, and how they are implemented in Java; • describe the concepts of variables and constants, scope rules for variables, and Java naming conventions for variables; • declare and assign values to primitive and String variables in Java; • describe the benefits of frontloading declarations in Java methods;
• describe the concept of type casting and how type casting works in Java; • create Java expressions to perform integer and floating point addition, subtraction, multiplication and division, and the remainder operation for integers; • create Java code that uses methods from the java.lang.Math class; • describe the concept of a data stream and stream tokenization, and how console input and output data streams are handled in Java; • create Java code to allow applications to read data from a keyboard as console input; • describe what a pop-up dialog window is and how to create message and input dialogs windows in Java, including how to parse numbers from input Strings. • create Java code that implements a dialog with the user via JOptionPane pop-up dialog windows. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 5 Data Types A data type is a format used to store data, including instructions for operations that can be performed
on the data, along with an acceptable range of values for the data. Formats for data depend on what the data means and how the data will be used. Numbers, for example, are stored in formats that allow the computer to quickly perform arithmetic with the data. Using different data types allows computers to process data more efficiently – using less memory to store data and less time to process data. Generally, object-oriented programming languages have two main categories of data types – primitive data types and reference data types. A primitive data type is built into the programming language and may be used by a programmer without first defining the data type. A reference data type refers to an object, which needs to be defined by a programmer before it can be used. Reference data types are also called user-defined data types. Each class of object in Java is essentially its own user-defined data type. There is one exception – the String class in Java is a special class of objects, built into the language. We may use String as a primitive data type, even though it is actually a reference data type. The
primitive data types and the String class are together known as Java’s built-in data types. Common Data Types in Java Most programming languages have data types that each fall into one of four different categories of data: • Boolean data is used to keep track of true and false values. • text data is composed of characters – the symbols we use in human languages, such as the Latin alphabet used for the English language. • integer data is numeric data without fractions. • floating point data is numeric with fractions, most often as decimal numbers with a decimal point. Java has nine built-in data types that each fall into one of these categories, as shown Figure 1. Eight of built-in data types shown in the chart – boolean, char, byte, short, int, long, float, and double – are Java’s primitive data types, described in this chapter. The ninth built-in datatype is the String class of objects, which may be used as primitive data type. Notice that the names of most of the nine data types each start with a lowercase letter while the “S” in
String is capitalized. This is because the names of classes in Java are usually capitalized, while the names of primitive data types are not capitalized. We will use Strings starting in this chapter, then learn more about the String class in in subsequent chapters. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 6 Variables, Constants, and Literals Data may be represented in Java code as variables, constants or literals. A variable is a memory location holding a specific value, similar to a variable in algebra. A variable has a symbolic name in Java source code, which refers to the value stored in memory. The value, or the link between the variable name and the stored value, can be changed, hence the name variable. A constant refers to a value stored in memory which, once initialized, cannot be changed, hence the name constant. A literal is a source code representation of a specific value of a built-in data type. The phrase “Hello
World!” used in Lab 1 in Chapter 1 is an example of a String literal. Java’s built-in data types are described briefly in the following sections. For more detailed information about Java data types, see the data types section of the Java online tutorial at: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatyp es.html Boolean Data Java’s boolean data type is named “boolean” with a lowercase ‘b’ while the general term is Boolean, with an uppercase “B”, named after George Boole. A boolean variable may hold the values true or false used to keep track of whether something is true or false. It has the smallest range of any data type. The answer to any true or false question, or the equivalent, such as yes corresponding to true and no corresponding to false, can be stored as boolean data. A checkbox on a job application keeping track of whether or not the applicant has a driver’s license, for example, can be coded in Java as boolean data. Figure 1 – Java data types
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatyp es.html JLK Chapter 2 – Introduction DRAFT October 2019 pg. 7 Figure 2 shows two questions from the Pennsylvania Voter Registration Form that each are Boolean questions – they have yes or no answers that can correspond to the boolean values true or false. Boolean data can be represented by a single bit of storage space, but often computers use a byte to speed up software since most memory is byte addressable. Byte addressable means that each byte of memory has its own memory address, making it faster for the computer to address an entire byte than to address a bit within a byte. Each machine’s JVM handles Boolean data according to the rules of the host system. Some use only a single bit to store a boolean value, but most use an entire byte. There are only two literals for boolean data – true and false, lowercase with no quotes. Text Data Text data is made up of characters. A character is a single symbol from the alphabet of a language. In
English, the name “John”, for example, is made up of four characters – J, o, h, and n. Unicode and the older ASCII character set (American Standard Code for Information Interchange) are the most commonly used codes for storing text data. Java stores characters using UTF-16, a 16-bit version of Unicode. This means that each Java character is 16 bits (two bytes) long. See The Unicode Consortium Website at: http://www.unicode.org/ for more information. Java has two built-in data types for storing text data: • char – char is a primitive Java data type used to store a single UTF-16 character. The char data type has a length of 16 bits (two bytes). Char literals are enclosed in single quotes – ‘X’. • String – a Java String is a set of Unicode characters stored as an instance of the String class of objects. Special support is built into Java for String objects. 16 bits, (two bytes) are needed for each character in a Java String. Notice that the names of the primitive data types all start with a lowercase letter, while String starts with an uppercase ‘S’ because it is the name of a class of
objects and class names are capitalized. A String literal is a string of characters in quotes. It can be used anyplace a String value or variable can be used in Java, such as in output statements. “Hello World!” is an example. Strings literals are indicated by enclosing them in double quotes – “name”. Figure 2 – Boolean questions http://www.unicode.org/ JLK Chapter 2 – Introduction DRAFT October 2019 pg. 8 Any UTF-16 character can be used as a Java character or in a Java String. The term alphabetic character refers to upper and lowercase letters, usually in reference to the Latin alphabet used for English. The term numeric character refers to decimal numeric digits 0 through 9. The term alphanumeric character refers to the two together – alphabetic characters and numeric characters but it does not include special characters, such as $, !, ? or #. All characters that are not decimal numeric digits 0 through 9 are called non-numeric characters.
The String and char data types are used for information that is not normally used to perform arithmetic. Names, labels, and messages are most often stored using the String and char data types. This includes ID numbers used as labels identifying people or things, such as Social Security numbers, student numbers, and product serial numbers. Even though we call them numbers, they are really used as text data and often include non-numeric characters. We also don’t want them to be rounded off or truncated, as numbers sometimes are. X = √��� ���� + ������ �������� ������ � ? Representing ID Numbers ID numbers are numbers that identify a person, place or thing, such as social security number or zip code. They are not stored as numeric data because they will not normally be used for arithmetic. (When is the last time you needed average student number, or the square root of your
zip code?) They are really labels, and as such are Strings. In fact they should be Strings so they can include non-numeric characters, and so they aren’t rounded off, as some numeric occasionally is. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 9 Special Characters in Strings Θ α π ‫ب‬ ‫א‬ ☛ ☺ Escape sequences are codes for special characters. They are called escape sequences because they originally involved the use of the escape key on computer terminals. They were defined as part of the ASCII code and are now part of Unicode. They can be used as text data in Java and most other modern programming languages. Many are control codes, which do not print a character but control the way characters are printed. Each Unicode character has a code number, usually expressed as a hexadecimal number A character can be included in a Java String literal by typing the backslash followed by its escape
sequence character, or by typing a backslash followed by a u, followed by its Unicode hexadecimal code number. For example, this Java statement prints a String starting with a tab and ending with an alpha: System.out.println(“t This prints a Greek alpha u03b1.”); Here are examples of some Unicode control characters with escape sequences and Unicode non- Latin printable characters. All can be represented using their UTF-16 values. Control Codes (escape codes) name sequence Unicode (hexadecimal) Backspace b 0008 Tab t 0009 Linefeed (new line) n 000a Form feed (new page) f 000c Double quote ” 0022 Single quote ’ 0027 Backslash 005c Printable Characters (non-Latin)
name charcter Unicode (hexadecimal) Greek uppercase theta Θ 0398 Greek lowercase alpha α 03b1 Greek lowercase pi Π 03c0 Hebrew alef 05 ‫א‬d0 Arabic alef 0627 ‫ب‬ pointing hand ☛ 261b smiley face ☺ 263a There are Unicode UTF-16 characters from many alphabets (Arabic, Cyrillic, Greek, Hebrew, etc.) and for many special characters. The null value is Unicode 0000, which is distinguished from a blank space (0020), or a zero digit (0030). The non- printing control characters are used for special purposes, such as in data communications and to format output. For more information, see: The Unicode Consortium Website at: http://www.unicode.org and the interactive Unicode Character Code pages online at: http://www.unicode.org/charts http://www.unicode.org/ http://www.unicode.org/charts
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 10 Integer Data Java has four primitive integer data types: byte, short, int, and long: • A byte is an 8-bit value representing a signed integer with a minimum value of -128 and a maximum value of +127. It is the shortest of all integer data types, using only a single byte (8 bits) for each value. • A short integer has a minimum value of -32,768 and a maximum value of +32,767. It requires 16 bits of memory (two bytes) to store each value. • int data has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647, using 32-bits of memory (four bytes). It is the most commonly used integer data type. • A long integer has a minimum value of - 9,223,372,036,854,775,808 and a maximum value of longest primitive integer data type, using 64 bits of memory (eight bytes) for each value. Integers are entered in Java by typing the digits, with no commas for thousands, etc. A negative sign
should be used for negative numbers. All primitive integers in Java are stored using two’s complement arithmetic, studied in more detail in computer-related Math courses, such as Math 121 or Math 163 at Community College of Philadelphia. Java does not have primitive data types for unsigned integers, as some languages, such as C++, do. The only difference between any two Java integer data types is the length of the number, as determined by its storage space. The most commonly used integer data type is int. The short or byte data type can be used to save memory, such as in an embedded processor in a small chip with little memory. The long data type can be used when integers beyond the range of the int data type are needed. Floating Point Data Java’s floating point numbers are stored using a mantissa- exponent format similar to scientific notation with a mantissa, an exponent, and two signs, one for the mantissa and one for the exponent. For example, the value 437.65, which would be 4.3765 x 102 in base-ten scientific notation, would be stored as +4.3765E+02 as a Java floating point number. The value
before the E is the number’s mantissa and the value after the E is its exponent. It has become customary in Computer Science to refer to the mantissa as the significand in a floating point number to distinguish it from the mantissa in a logarithm. Floating point numbers are not stored in logarithmic formats, they are stored in a log-linear format, so what is called the mantissa in a floating point number is not the same thing as a mantissa in a number stored in a logarithmic format. Floating point number formats in Java are compliant with the IEEE’s Standard for Binary Floating-Point Arithmetic (IEEE 754-2008). JLK Chapter 2 – Introduction DRAFT October 2019 pg. 11 IEEE Floating Point Numbers The IEEE’s Standard for Floating-Point Arithmetic (IEEE 754) defines formats for floating point numbers and rules for operations on those numbers. Java uses two binary formats from the standard for binary floating point numbers: the 32-bit binary format for the float data type, and
the 64-bit binary format for the double data type. Values are stored in a binary format but displayed by default in a decimal format. Floating point numbers are similar to scientific notation: +4.3765E+02 is 4.3765 x 102, four point three seven six five times ten to the second power. An IEEE floating point number has: • a sign indicating if the value is positive or negative. • a significand containing the significant digits of the number. The significand is more formally known as the mantissa of a floating point number, but is often called a significand to distinguish it from the mantissa in a logarithm, Floating point numbers are in a log-linear format, not a logarithmic format. • an exponent. IEEE 754 uses an offset for the exponent which accounts for the sign, so the sign of the exponent is not stored separately. • The base, which is always 10, is not stored. 32-bit format used for float values Sign Exponent Significand
1 bit 8 bits 23 bits The 23-bit significand is always accurate to at least six decimal digits, sometimes seven, depending on the exact value. It is safe to rely on six digits of accuracy. The 8-bit exponent is in the binary range of -127 to +127, roughly equivalent to the decimal range 10- 64-bit format used for double values sign Exponent Significand 1 bit 11 bits 52 bits The 52-bit significand is always accurate to at least 15 decimal digits, sometimes 16, depending on the exact value. It is safe to rely on 15 digits. The 11-bit exponent is in the binary range of -1023 to +1023, roughly equivalent to the decimal range 10- Java floating point formats are based on the 1985 standards (IEEE754-1985). The standard was expanded in 2008 (IEEE754-2008) and adopted by the ISO. The old formats are a subset of the new definition, and floating point values in Java are compliant with the newer standard.
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 12 There are two primitive data types in Java for floating point numbers: • float – a single precision floating point value that is accurate to six decimal digits, with values ranging from roughly 10-38 to 10+38. A float requires 32-bits of storage space (four bytes). • double – a double precision floating point value that is accurate to fifteen decimal digits, with values ranging from roughly 10-308 to 10+308. A double requires 64-bits of storage space (eight bytes). The name double comes from the fact that it uses double the memory, not that the mantissa or exponent are double the accuracy. Floating point numbers may be typed in Java as decimal numbers, such as 1234.56, or in their significand-exponent format: +1.23456E+06. The significand is normalized, which means there is only one significant digit before the decimal point. 45.654E+02 would be normalized to 4.5654E+03.
Floating point numbers all have decimal points. 0.0 is a floating point value. 0 is an integer value. CheckPoint 2.1 1. What are Java’s nine built-in data types and how do they fit into four major categories? 2. Which Java built-in data type is not a primitive data type? 3. How do each of Java’s integer data types differ from one another? 4. What is a literal and how are literals represented for different built-in data types? 5. Describe the formats used to store floating point data in memory. Note: Be careful about answers that are correct, but incomplete. For example, float and double are the names of the formats used for floating point data, but questions 5 asks for more than just their names. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 13 Numbers from the Real (and Imaginary) World
We’ve looked at integer and floating point numbers in Java, but what about other kinds of numbers, such as whole numbers, real numbers, and so on? It turns that some are well-defined and some are subject to interpretation. An integer is numbers without a fraction {…, -3, -2, -1, 0, 1, 2, 3, …}. Any of Java’s integer datatypes can be used to represent integers, within the range of values for each type. The terms whole numbers, natural numbers and counting numbers are without universally agreed upon definitions. Some mathematicians say whole numbers and integer mean the same things, while others say whole numbers start at zero. Some say natural numbers start at zero and include only the positive integers. Others say natural numbers start at one. The same is true for counting numbers – some say they start at zero, some say at one. Mathematicians and computer scientists who wish to be precise use the terms positive integers and non-negative integers to define two subsets of integers: the positive integers start at one {1,2,3,…}, while the non-negative integers start at zero {0,1,2,…} The
non-negative are also called unsigned integers. Java does not have a special data type for unsigned integers as some languages do. A rational number is any number that can be represented by a ratio of integers; basically a fraction whose numerator (top) and denominator (bottom) are both integers. (The denominator cannot be zero.) Integers are a subset of the rational numbers. A real number is any number that can be represented on a number line. Basically, if we can draw a line of a certain length, even if the length cannot be expressed exactly as a rational number, it is a real number. The hypotenuse of a right triangle with two sides each 1 unit long is √2, which is a real number that does not exactly equal any rational number. Such numbers are known as irrational numbers. An irrational number is any real number that cannot be represented exactly by a ratio of integers, such as π or √2. We cannot represent all real numbers in Java, but we can represent a decimal approximation of real numbers using floating point numbers. For example, π is 3.14159265358979 as the 15 digit double
value +3.14159265358979E+00, which is accurate enough to calculate the radius of a sphere the size of the Earth within one-millionth of an inch. Numbers that involve negative square roots are imaginary numbers, since negative values have no square root. Complex numbers combine real and imaginary numbers. They are important in fields such as electronics. Basically, if you need to use them you know what they are, if not, then don’t worry about it for now. The Apache Commons website has a complex number API used by scientists and engineers. ( See: http://commons.apache.org/proper/commons- math/userguide/complex.html ) http://commons.apache.org/proper/commons- math/userguide/complex.html JLK Chapter 2 – Introduction DRAFT October 2019 pg. 14 Variables and Constants The variables and constants mentioned in the discussion of data types are an essential element of computer programming.
In addition to a data type, each variable and constant in Java has a scope of existence. The scope of existence, or simply the scope, of a variable or constant is that part of a program in which it exists and can be used. Variables may be local variables within a method or they may be used to refer to the properties of objects, such as the color of a car or the name of a person. In the rest of this section we will focus on local variables. The properties of objects are discussed in later chapters, but for now you should know that they also have a name and a data type, just as local variables do. Local Variables The variables in Java methods are called local variables. The scope of a local variable is determined by its lexical context, which means it depends on the variable’s place within specific language. A local variable can only be used within the block of code in which it is declared. The beginning and end of Java blocks of code are marked by braces { … } as we saw in Lab 1 chapter 1. A method is a block of code, since it begins and ends with braces. We may also have blocks within blocks, such as a block of code to
be repeated in a loop, or a block of code to be executed by an if command. A variable only exists and can only be used in the block of code in which it is declared. A variable declared inside one method does not exist in another method and cannot be used in another method. Another method could have a different variable with the same name, but they would be different variables, referring to different memory locations. To declare a variable means to state the name and data type of a variable, and possibly give it an initial value. Here are three examples: int sum; // the sum of the test scores double angle = 47.63; // angle of elevation String zipcode; // the customer’s zipcode In the first example, the variable named sum is declared to be an int variable. It has no initial value. A variable without a value is a null variable – it is not equal to zero, it has no value. There is a difference. In the second example, angle is declared to be a variable of type double, with an initial value of 47.63. All variables for primitive data types and Strings can be
initialized in this way when they are declared. The value should be a literal of the same data type as the variable, or an expression yielding a value of the correct data type. In the third example, the variable zipcode is declared as a String variable. Notice that the name zipcode is lowercase, as are almost all variable names. String with an uppercase ‘S’ is the name of a class; zipcode refers to an instance of the String class. In this example, zipcode in not initialized, so it will have a null value until it is used in the program. The inline comments in the variable declarations above make it easier for people reading the code to understand it – including the code’s author, reading the code months or years after it was written. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 15 Variable declarations may appear almost anywhere in a Java program, but it is a good programming practice to declare all variables for a method at the beginning of the method with a comment describing each variable. This practice, known as front loading declarations, does two things:
1. It creates a data dictionary at the beginning of a method, making it easier for people who read the code to find out what variables are used in the code and what they represent. 2. It makes it easier to read a program. Data declarations in the middle of code can sometimes make the code harder to follow, in a subtle way. Constant Declarations A constant in Java is declared and used just as a variable is, except that its value cannot be changed. We designate a constant by putting the keyword final in front of the type in its declaration, as in these examples: final double PI = 3.141592653589793; final String PAGENOTE = “© 2014 – All rights reserved”; final int CLASS_SIZE_LIMIT = 36; Notice that constant names are all uppercase, with an underscore character separating parts of a compound name. This a Java programming convention. Hardcoding Putting a data value directly into your code is known as
hardcoding data, and is generally frowned upon by good programmers (and instructors who will be grading your assignments). It is a bad habit to develop, because it can lead to errors and inefficiency. Imagine that you will use 365.25 as the number of days in a year many places in a program. Instead of typing 365.25 many times or copying and pasting it many times, you can declare a constant DAYS_PER_YEAR, and just use it each time. The same holds true for String values used repeatedly like “Northwest Philadelphia Regional Center” in CCP software, or “Aleksandr Isayevich Solzhenitsyn” in an application about Russian dissidents who won the Nobel Prize for literature in 1970. It is good programming practice to develop the habit of using constants instead of hardcoding values in software. Variable and Constant Names – Java Identifiers
A Java identifier is a string of Unicode characters that identifies something in Java code. Identifiers are used to name variables, methods, classes, and so on. The Java Language Specification (JLS)1 section 6.2 describes the acceptable syntax of a Java identifier and also suggests programmers follow common naming conventions. 1 Available online from Oracle at: http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls- 6.2 http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls- 6.2 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 16 According to the JLS, Java identifiers must start with a letter of the Latin alphabet (a-z), an underscore character (Unicode 005F), or a dollar sign (Unicode 0024). The use of the underscore and dollar sign are for historic reasons, and the JLS discourages their use as the first character in an identifier in modern code. The remaining characters in an identifier may also include decimal numeric digits (0-9), so they may be any the alphanumeric characters or the underscore or
dollar sign. There are two forms of names in Java, simple names and qualified names. A simple name is a single identifier. A qualified name is a sequence of two or more simple names separated by periods. Qualified names identify the context in which a simple name is used. For example, a property lastName for an instance of the Student class named student1 would have the qualified name student1.lastName. Simple names are used most of the time for local variables in Java code. Qualified names are used when the context needs to be specified, such as when code refers to properties or methods from a class. There are four primary naming conventions in Java: • names should be meaningful. Minimize the use of x, y, a, b, or things like num1 or num2. • class names are in Upper CamelCase, such as HelloWorldApp, Math, or Student. • variable and method names are in lower camelCase, such as sum, realRoot1, or hourlyRate • constants are named in all UPPERCASE, using an underscore to separate part of a compound name, such as PI, GROWTH_RATE, or MAX_WEIGHT. This clearly distinguishes constants.
Java Keywords are part of the language and are meaningful to the compiler. They may not be used as identifiers in Java. Some examples are int, class, double and if. Keywords are also called reserved words. Java has a relatively small set of 50 keywords: abstract continue for new switch assert default if package synchronized boolean do goto private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const float native super while By comparison, C++ has 86, C# has 79, Swift has 71, Python 2.0 had only 31 and COBOL has over 400. CheckPoint 2.2 1. What determines the scope of a local variable? 2. What is the difference between the way constants and variables are declared? 3. What is hardcoding and why is it better to use constants than to hardcode data? 4. What is a qualified name and why does it have more than one part?
5. What are the benefits of frontloading variable and constant declarations? JLK Chapter 2 – Introduction DRAFT October 2019 pg. 17 Assignment Statements and Expressions An assignment statement assigns a new value to an existing variable. It has two parts, separated by an equal sign: variable = expression; The only thing to the left of the equal sign is the name of the variable. An expression describing the value to be assigned is to the right of the equal sign. Here are three examples: angle = 45; // int assignment, hardcoded grossPay = hours * rate; // math expression city = “Philadelphia”; // String assignment Expressions tell a computer how to determine or calculate a value. Numeric expressions often look like expressions in elementary algebra and most of the rules are the same as in elementary algebra. The computer will attempt to resolve the expression to end up with a
single value of the required data type, then assign that value to the variable. An expression should yield a value of the same data type as the variable to which it is assigned. If not, type casting may occur. Type casting is discussed in more detail later in this section. Expressions have operands, which are the values used in an expression, and operators, which are symbols or functions indicating the operations to be performed in an expression. In the expression sum = a + b, the terms sum, a, and b are the operands, while the plus sign is the operator indicating the addition operation. Instructions included as part of a data type tell the computer how to perform basic operations on that type of data, such as addition, subtraction, multiplication, and division for integer data. The symbols used in assignments statements indicate these operations. Functions are methods that return a value, such as a math function to return the square root of a number or a String function to convert a String to all uppercase characters. The nature of an operation depends on the data types of the
operands being used with the operation. For example, The Math library’s round function can be used to round off a double or float to the nearest integer, but there is no need for such an operation for Strings: x = Math.round(17.6) results in x being set to 17. x = Math.round(“Hello world!”) doesn’t work, because “Hello world!” is a String, not a number, and the round operation is not defined for Strings. Polymorphism Sometimes a symbol for an operation or the name of a method in a method call can trigger one operation for one data type and another operation for a different data type. In computer programming, this is a form of polymorphism, which means the same name or symbol can stand for different operations on different data types. The meaning of the plus sign + depends on the data types of its operands. The plus sign is polymorphic because it performs different operations on different types of data: JLK Chapter 2 – Introduction DRAFT October 2019 pg. 18
• The Java instruction System.out.print(12 + 16) prints the number 28. The operands 12 and 16 are int values, so the computer will perform the operation associated with the plus sign for integers — simple integer addition. • The Java instruction System.out.print(“Joe” + “Smith”) prints the String “JoeSmith”. “Joe” and “Smith” are Strings, so the computer will perform the operation associated with String data — concatenation, sticking the two strings together to form a new longer string. The plus sign signifies addition for int values but concatenation for Strings. It has multiple meanings, with its meaning bound to the data types of its operands. This is an example of what is known as ad hoc polymorphism, in which the meaning of symbol or a method call depends on the data type of its operands. Ad hoc polymorphism is also called operator overloading and function overloading. Polymorphism is studied In more detail in CSCI 112 and 211, where students learn about parametric polymorphism, which means a generic method has been written to work with any data type. Ad hoc
polymorphism is limited to a few specific data types, while parametric polymorphism will work with any data type. For now, it is enough to have a general idea of what polymorphism is – the same method name or symbol can trigger different operations for different data types. Polymorphism is one of the key aspects of object-oriented programming. Arithmetic Operations Java has several built-in arithmetic operations that can be performed on integer and floating point data: • Addition + (the plus sign) • Subtraction - (the minus sign) • Multiplication * (the asterisk) • Division / (the slash) • The remainder operation % (the percent sign) • Unary negation - (the minus sign) • Unary increment (prefix and postfix) ++ (two plus signs with no space) • Unary decrement (prefix and postfix) -- (two minus with no space) Addition, subtraction, multiplication and division are similar to the same operations in elementary
algebra. Each of these operations takes two operands. sum = addend1 + addend2; difference = minuend – subtrahend; product = multiplier * multiplicand; quotient = dividend / divisor; Java does not understand implied multiplication, z = 3x + y must be written as: z = 3*x + y; JLK Chapter 2 – Introduction DRAFT October 2019 pg. 19 Quotients and Remainders A quotient from integer division will be an integer, the remainder is lost. For example, 20 divided by 3 is 6 remainder 2. The result will be the quotient, 6. The remainder of 2 is lost. The modulus operation, also called the remainder operation returns the remainder, not the quotient. The remainder is called
the modulo of a number (17 modulo 5 = 2). The operator is the percent sign instead of the slash: Remainder = dividend % divisor; This is read as “Remainder equals dividend modulo divisor.” Here is an example of how the modulus can be useful. Let’s assume that we have 20 feet and want to know how many yards there are in twenty feet and how many feet will be left over. There are three feet in a yard. 20 divided by 3 is 6, remainder 2. Division tells us how many whole yards, 6. Modulus tells us how many feet will be remaining, 2. In general, we could use two instructions in a method like the one below to capture quotient and remainder, assuming the operands are integers: public static void main( String[] args ) { int oldFeet; // the initial distance in feet; int yardsInOldFeet; // the yards in the distance int feetLeftOver; // the number of feet left over final int FEET_IN_YARD = 3; // constant 3 ft. = 1 yd. // insert some code here to get old feet from the user yardsInOldFeet = oldFeet / FEET_IN_YARD; // calculate yards
feetLeftOver = oldFeet % FEET_IN_YARD; // remaining feet // inset code here to beautifully display the results } // end main() The result of floating point division is a floating point value: 20 / 6 = 3.33333. The modulus operation may also be used to return the remainder from floating point data. 20.0 % 6.0 = 2.0. Unary Operations Several of the operations on integers are unary operations. A unary operation only has one operand. Negation, increment and decrement are unary operations. Negation means reversing the sign of a number; a positive value becomes negative and a negative value becomes positive. We do this by simply putting a minus sign immediately in front of an integer value. For clarity, the value might be placed in parentheses, like this: loss = -(gain); If gain is positive, loss will be negative. If gain is negative, loss will be positive. The Increment operation increases the value of an integer or floating point value by one. If count is ten,
then incrementing count makes it eleven. The increment operator is a double plus sign. Increment can be used alone as an instruction, as in this example: count++; // increment count (add 1 to count, equivalent to count = count+1) The new value of count will be the old value of count plus one more. Figure 3 calculating quotients and remainders JLK Chapter 2 – Introduction DRAFT October 2019 pg. 20 The increment operation can also be used in an expression, such as: total = count++; // total = count, then increment count If the operator is after the variable this is called a postfix increment. A Postfix Operation occurs after the variable is used. The value of count is assigned to total, then count is incremented. If the old value of count was 10, then after the instruction, total will equal 10, count will equal 11.
Increment can also be a prefix operation. A Prefix Operation occurs before the variable is used. Like this: total = ++count; // increment count, then assign the value to total In this case, count will be incremented first, then the value of count is assigned to total. If the old value of count was 10, then after the instruction, total and count will both equal 11. The decrement operation decreases the value of an integer or floating point by one. The decrement operator is a double minus sign. It is similar to the increment operation except it subtracts instead of adds, It can be used prefix or postfix, just as increment can be. Total = count--; // total = count, then decrement count Total = --count; // decrement count, then assign the value to total Java also has compound assignment operation. A compound assignment operation combines an arithmetic operation with an assignment statement to add, subtract, multiply, or divide a fixed value with the existing value of the variable, then assign the resulting value to the variable, such as: X += 5; // compound assignment, equivalent to x = x + 5;
How does this work? Consider the statement x = x + 1. In Java, the new value of x equals the old value of x plus one. The expression on the right side of the equals sign is evaluated, then the value is assigned to the variable on the left. This works even if the same variable is on both sides. We have just seen that an increment statement x++ can take the place of x = x + 1. In a similar manner, x = x + 5 can be replaced with X += 5. There are five compound assignment operators: addition assignment subtraction assignment multiplication assignment division assignment modulo assignment += -= *= /= %= Note that there are no spaces between the arithmetic operator and the equals sing in compound
assignment statements. The Java Math Class The Java programming language supports elementary arithmetic, but to do more advanced mathematical computation, such as working with exponents, logarithms, or trigonometry, Java provides a library of methods in the Math class, which is part of the java.lang package in the JDK. The java.lang package is a set of classes with features to support Java programming. It is unique because it is the only external package that does not require an import statement. We will learn more about import statements and using other packages later in this chapter. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 21 The Math class has a set of methods that perform math functions. The Math class methods are static methods, which means they are each invoked using the name of the class as part of their qualified name, not an instance of the class. Square root is an example of this. It has the simple name sqrt. Its
qualified name includes the class name: Math.sqrt. This table shows some methods available in the Math class in java.lang. The values in parentheses are the data types of a method’s parameters, the values after the method are the type the method returns. java.lang.Math abs(int x): int abs(long x): long abs(float x): float abs(double x): double the absolute value of x cos(double x): double the cosine of x radians exp(double x): double ex where e is 2.71828 hypot(double x, double y): double square root of ( x2 + y2) log(double x): double natural log of x log10(double x): double base 10 log of x max(int x, int y): int max(long x, long y): long max(float x, float y): float max(double x, double y): double the greater of the two arguments min(int x, int y): int
min(long x, long y): long min(float x, float y): float min(double x, double y): double the lesser of the two arguments pow(double x, double y): double xy x to the y power sin(double x): double the sine of x radians sqrt(double x): double the square root of x tan(double x): double the tangent of x radians todegrees(double x): double converts x degrees to radians toradians(double x): double converts x radians to degrees Notice that several of the functions in the Math class are polymorphic, which means they work with more than one data type. Polymorphic functions are actually different functions with the same name, but their parameters have different data types. If two functions have the same name, the compiler will decide which function to use based on the data types of their parameters. Two functions cannot have the same name and identical parameters. If the name is the same, the parameters must be different.
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 22 The Math class also has two defined double constants accurate to six decimal places: • Math.E = 2.718281828459045, the closest double value Euler’s number, the basis for natural logarithms • Math.PI = 3.141592653589793, the closest double value to π For a full description of the Math class, see the oracle Math class reference: http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html The Math class is also discussed in the Oracle Java tutorials, online at: http://docs.oracle.com/javase/tutorial/java/data/beyondmath.htm l Here is an example showing how to use the square root function from the Math class in a Java method: public static void main(String[] args) { double squareArea; // the area of a square double side; // the length of the side of the square squareArea = 100.0; // 100.0 is floating point
side = Math.sqrt(squareArea); // uses the square root function // output result – Strings and variables concatenated into one String System.out.println("The side of a square with area " + squareArea + " is " + side); } // end main() The output looks like this: The side of a square with area 100.0 is 10.0 The variables in this method are both double. To keep the example simple, squareArea is simply set to 100.0. (Normally this value would come from somewhere else, such as user input.) Notice that it is 100.0 instead of 100 to avoid type casting from an integer value to a floating point value. The method sqrt, which calculates a square root, is invoked from the Math library in the statement side = Math.sqrt(squareArea); Math is the name of the class, and sqrt is the name of the method. We use the qualified name Math.sqrt to access a method in another class. squareArea is an argument of the sqrt function, or in terms of Java,
a parameter that is passed to the method. The method will use the value of squareArea to calculate a square root and then return the value of the square root, which will be used in our expression. In this case, it is the only value in the expression, so side is set to the value returned by the sqrt() function. Order of Operations The order of operations in a programming language is affected by three things: • order of evaluation • operator precedence • grouping symbols 610 992 5620 Figure 4 using Java's Math class http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html http://docs.oracle.com/javase/tutorial/java/data/beyondmath.htm l JLK Chapter 2 – Introduction DRAFT October 2019 pg. 23 The order of evaluation for a language is basically the direction of the language – left to right for Java, just as it is for English. (Hebrew and Arabic are examples of
languages that are read from right to left, while some Asian languages are read from top to bottom.) Order of evaluation is superseded by operator precedence. Operator precedence is the precedence given to one operator over another by a compiler as it evaluates expressions. Here is part of the table of operator precedence from Oracle’s Java Documentation: Operator Precedence unary postfix expr++ expr-- unary prefix ++expr --expr -expr multiplicative * / % additive + - The table above shows us that for elementary math operations Java will evaluate multiplication and division before addition and subtraction, but that multiplication and division have the same precedence, and addition and subtraction have the same preference. Does MDAS sound familiar? It is the same order of operations for elementary math in elementary algebra. Here is an example:
x = 20 + 4 / 2; What does x equal? Normally we perform operations in order from left to right, but division has precedence over addition, so we should do the division first. The correct answer, in elementary algebra and in Java is x = 22, not x= 12. We can explicitly change the order of operations by using parentheses, as in this example: X = (20 + 4) / 2; In this case, X = 12, not 22. The parentheses tell the computer to evaluate the addition before the division. Parenthesis are a grouping symbol in math. We can always use parentheses to explicitly tell the computer to evaluate one operation before another. Parentheses are also very important when translating fractions into a programming language. In elementary algebra, the fraction bar is a grouping symbol just as parentheses are grouping symbols. Consider the following example: � = 3 + 9 3−1
What does x equal? 3 + 9 = 12, 3 - 1 = 2, and 12 2 is 6. The fraction bar tells us to evaluate the terms in the numerator and denominator before dividing. But what happens if we translate this into Java? Many people would simply enter: X = 3 + 9 / 3 – 1; JLK Chapter 2 – Introduction DRAFT October 2019 pg. 24 However this is not correct, because division has precedence over addition and subtraction, yielding: 3 + 9 3 - 1, which is 3 + 3 - 1, which is 5. The correct form of � = 3+9 3−1 translated into Java would be: x = (3 + 9) / (3 -1);
This example shows us that parentheses should be placed around the numerator and the denominators of fractions with operations in them when we are translating the fractions into expressions in Java. In general, if you are not sure what the computer will do first, you can tell the computer what you want it to do first by using parentheses. Note that functions with expressions in the argument of the function will resolve the argument to a single value before invoking the function. For example, in X = Math.sqrt(4 + 20); The computer will evaluate 4 + 20 to a single value before it uses the square root function. Commutative and Associative Behavior Most Java arithmetic operations are commutative and associative in the same manner as their counterparts in elementary algebra. Commutative means two operands can exchange positions and the result of the operation is the same; in other words, the order of the operands does not affect the result. (A+B = B+A) Addition and multiplication are commutative, subtraction and division are not. The order of the
operands in subtraction and division (including the modulus operation) affects the results. Even when the operation is commutative, computer programmers should still try to be consistent in the order in which they use operands. This is related to Crewton Ramone’s corpulent midget rule. 2 Carpenters always specify length, then width, then height when listing dimensions. Even though W x L is the same as L x W, if a carpenter gets the numbers in the wrong order on a job site, we could end up with a door for corpulent midgets ( 3 feet high and 7 feet wide instead of 7 feet high and 3 feet wide). The order of two values might make a difference in how a person interprets the data, even when it doesn’t make a difference in the result of a commutative operation. Associative means that if the same operation is used several times in a row, such as A+B+C, then it does not matter which operation is performed first: (A+B)+C = A+(B+C). Java is left associative, meaning that it will perform A+B then add the result to C, but if B+C were added to A, the result would be the same. Addition and multiplication are associative, but subtraction and division are not.
2 Crewton Ramone is a math educator in Hawaii. See Crewton Ramone’s House of Math, online at: http://www.crewtonramoneshouseofmath.com/ JLK Chapter 2 – Introduction DRAFT October 2019 pg. 25 Type Casting Type casting is the conversion of data from one type to another, according to rules embedded in the compiler. Unnecessary casting should be avoided, because it wastes time during the execution of a program, and could lead to errors. The following code shows examples of type casting: double base = 6.3; double bonus; int result; . . . bonus = 2 * base; // 2 is an int value – type casting will occur bonus = 2.0 * base; // 2.0 is a double value – no type casting occurs result = base; // result is int, base is double. the fractional part of base will be lost.
In the first two assignment statements, If 2 is used instead of 2.0, the expression casts the type from int to double since bonus and base are double and 2 is an int literal. It is better to use 2.0, a double literal. In the third assignment statement, a double value is being assigned to an int variable. In this case, result will equal 6, and a loss of accuracy occurs. If operands are of different data types, then the computer will attempt to resolve the expression using conversions by type casting. In general: • int values can be cast to double values with no loss of accuracy (only a loss of time). The int value 137 can become the float value 1.37E+02 (equal to 137.0) with no loss of information. • all floating point values cast to any integer type will be truncated, with a loss of information. The fractional portion after the decimal point in the regular (not scientific notation) equivalent of the value will be lost. The double value 4.13297E+03 ( = 4132.97) becomes the int value 4132. • both integers and floating point values can be cast as Strings, in which case they will become the String expression of the characters in the decimal value. 10.75,
becomes the String “10.75”. The String is the set of characters ‘1’, ‘0’, ‘.’, ‘7’, and ‘5’, not a numeric value. Often this happens in console or file output. Since I/O operations are slow in any case, casting in I/O operations is usually not a big concern in examining the efficiency of a program outputting data. Casting Strings to integers or floating point values can be tricky. There are special methods in the String library to parse numeric values from Strings, which we will study in another section. Converting a value from a data type of greater accuracy and range to a data type of lesser accuracy and range in known as a narrowing primitive conversion. The following are the narrowing primitive conversions in Java: • short to byte or char • char to byte or short • int to byte, short, or char • long to byte, short, char, or int • float to byte, short, char, int, or long • double to byte, short, char, int, long, or float
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 26 According to the JLS3, “A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.” Data errors caused by a loss of information from a type conversion, or by mixing up units (such as feet and meters), or by misplaced minus signs, could have serious consequences. Computers are used in important situations – medical systems, antilock braking systems in cars, passenger airplane controls, the military, and so on. We can help save time, save money, and even save lives by minimizing the chances for data errors in software we create. Cast Operators A programmer can force type casting by including a cast operator in an expression before a value to be cast. A cast operator is a data type in parentheses explicitly telling the computer to perform type casting, as in this example. int hours; // hours worked
double rate; // hourly pay rate double gross; // gross pay . . . // part of the code here is not shown gross = (double) hours * rate; In this case, hours is cast to a double value from and int value before the multiplication is performed because double is used as a cast operator. This prevents a loss of precision in the multiplication operation. CheckPoint 2.3 1. What is on each side of the equal sign in a Java assignment statement? 2. What does the term polymorphism mean in object oriented programming? 3. What does the % indicate in a math expression and what data types work with this operation? 4. What is the difference between the following two statements: a. y = x++; b. y = ++x; 5. convert each of the following to Java assignment statements: a. ��� = � �+� �
� � variables: double sum; int a, b, c, d b. � = √�2 + �2 variables: double a,b,c c. � = ��2 variables: double a, r; constant π d. � = �0 � ���(�ℎ���) − 1 2 g �2 variables double y, v0, t, theta; constant g= 9.8 e. ������ = ��������� (1 + ���� � ) � � variables: double principal, rate; int n, t 3 see section 5.1.3 of the JLS, online at: http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls- 5.1.3 http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls- 5.1.3 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 27 Data Streams and System Console I/O In chapter one, we used system console output to display a
message on a computer screen. Here we will briefly look at system console I/O in more detail. System I/O uses data streams, also called I/O streams. A data stream is just a sequence of data flowing from a sender to a receiver. Input data streams bring data in from external sources; output data streams send data out to external destinations. Java has a variety of packages supporting such I/O. A raw data stream contains unformatted binary data. A tokenized data stream contains tokens and delimiters. A token is a piece of data. A delimiter is a marker that separates one token from another in a data stream. In most modern computers, a delimiter is a Unicode character or a string of Unicode characters. When a person types a list, for example, commas often are used as delimiters. Java I/O data streams use whitespaces as delimiters. A whitespace is: • a blank space, such as you get by pressing the spacebar (Unicode 0008) • a set of consecutive blank spaces • a tab character (Unicode 0009)
• a newline (line feed) character (Unicode 000a) • a formfeed (page feed) character (Unicode 000c) • or any of several other technical characters related to file I/O, which we’ll see later. We have already seen the System.out.print and System.out.println statements for sending output to the system console, which is the system’s standard set of input and output devices: System.out.print(“The cursor is on this line after print. ”); System.out.println(“The cursor is on a new line after println.”); A system’s standard output device is usually a display screen. print and println when used with System.out usually send unformatted text data to a display screen. Input is a little tougher because the receiving device for an I/O data stream decides what to do with the data it receives. When we send data out to the console, the operating system decides what to do with the data, so system output is relatively simple, but when data comes into an application, the application needs to decide how to process the data. We need to tell our Java application how to handle the input data stream. There are many ways to do this; one of the simplest
is using the Scanner class. Figure 5 I/O data streams JLK Chapter 2 – Introduction DRAFT October 2019 pg. 28 The Scanner Class A Scanner class object processes an incoming data stream so that data can be put into variables. There are several input methods in the Scanner class that do this. The methods we will use read tokens of data into variables. The chart below describes some of these methods. java.util.Scanner next(): String reads the next token and returns it as a String value nextInt(): int reads the next token and returns it as a int value nextLong(): long reads the next token and returns it as a long value nextFloat(): float reads the next token and returns it as a float value nextDouble():
double reads the next token and returns it as a double value nextLine(): String reads an entire line and returns it as a String value (A line ends with a new line character.) close() closes the stream associated with the Scanner object The blank parentheses in the chart above indicate methods that do not need a parameter. Except for the close method, the methods are each functions that return a value, whose return type is indicated. To use the Scanner class methods, we must create an instance of the Scanner class by declaring a local variable to be of data type Scanner. The local variable represents the instance of the Scanner class in our method. We can then use the methods from the Scanner class in association with that variable. Scanner kb = new Scanner(System.in); When we use a method from the Scanner class, we use the qualified name of the method, which includes the name of the instance variable and the name of the method. // get the user’s name from the keyboard System.out.println("Please enter your name: ");
name = kb.nextLine(); The println command before the nextline command prompts the user to enter data. This creates a prompt and capture pair of instructions for user input. The nextline() method returns a String, so we assign the value it returns to a String variable. Most methods that capture data from a data stream work this way. We should also close the Input data stream for this instance when we are done with it. keyboard.close(); The following code demonstrates the use of the Scanner class to capture keyboard input. Note that this example uses the variable keyboard as the name of a Scanner class object associated with an input stream from the standard system input device (System.in). The name keyboard was chosen by the author of the code. It is a variable name that has no special meaning in Java. Many programmers use a simpler name for the same purpose, such as kb.
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 29 /* keyboardTest.java * java code for CSCI 111 with a simple keyboard input example. * last edited Dec 21, 2014 by C. Herbert */ package keyboardtest; // one of the following import statements is needed to use the Scanner class import java.util.*; import java.util.Scanner; public class KeyboardTest { public static void main(String[] args) { String name; // String to holds user’s name // create a new Scanner class object, associated with console input Scanner keyboard = new Scanner(System.in); // get the user’s name from the keyboard System.out.print("Please enter your name: " );
name = keyboard.nextLine(); // echo the name back to the screen System.out.println("Hello " + name); // close input stream keyboard.close(); } // end main() } // end class KeyboardTest Notice the import statements in the code above. An import statement tells a Java compiler to add bytecode from outside of the current source code to the bytecode for the software being compiled. This allows the use of external classes and methods in our Java code. We may import an entire package or import a single class from a package. In this case, we wish to use the Scanner class in the java.util utilities package. The first import statement – import java.util.*; – imports the entire package. The second import statement – import java.util.Scanner; – specifically imports just the Scanner class. Only one of the two is needed, both are included in this code for demonstration purposes. Theoretically, it is more efficient to
import only the specific classes that are used rather than importing an entire package. However, most Java compilers are optimizing compilers, which will import the minimum code needed. In this case, the resulting class file is 993 bytes long, with either import statement when compiling this software using IntelliJ Checkpoint 2.4 1. How is a tokenized data stream different from a raw data stream? 2. Describe how to open and close a data stream for console I/O. 3. Which functions from the Scanner class capture tokens into variables of the following types? a. String (single token) b. String (all tokens on one line as one variable) c. int d. double 4. Give an example of an import statement and describe what an import statement does. 5. Give an example of a “prompt and capture pair” of statements for console IO and how it works. Figure 6 console I/O code
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 30 Documentation First Programming An important aspect of engineering, including software engineering, is captured in the phrase: “Design it before you try to build it.” Documentation first programming is a simple design-first approach to software development in which we begin by writing comments to describe what the software should do, then create code to do what the comments say to do. We start documentation first programming by developing an outline of what the software should do from the specifications for the software, then we turn the outline into a set of comments. We then use those comments in a Java development project as the basis for the code needed to implement the software. If necessary, we refine the comments as we go along. This section contains a simple example of documentation first programming. In this example, we wish to create software for a simple road trip calculator that will tell us the average speed and gas mileage for
an automobile journey. The specifications call for a program to: 1. get the distance in miles, driving time in hours, and fuel used in gallons during a long car trip. The data will be input by the user. 2. calculate the average speed (miles per hour), and mileage (miles per gallon) for the trip. 3. display the distance, time, average speed, and mileage for the trip. This is an example of an I-P-O program – Input, Processing, Output – get some input, process the data, output the results. Many short programs fit the I-P-O pattern. It is a simple example of what’s known in software engineering as a design pattern. To create the road trip software using a documentation first approach, we start with an outline: 1. declare variables 2. set up program to read from keyboard 3. get user input a. distance in miles b. driving time in hours c. fuel used in gallons
4. calculate a. average speed (MPH) b. fuel mileage (MPG) 5. output results a. distance and time b. MPH c. MPG Next, we create a set of Java comments matching the outline, or copy and paste the outline into an IDE, refining it into comments as we go along. The result should look something like this: JLK Chapter 2 – Introduction DRAFT October 2019 pg. 31 // Road Trip Calculator // by C. Herbert for CSCI 111 // declare variables – all double // distance traveled in miles
// total driving time in hours // total fuel used in gallons // mileage - average miles per gallon MPG // average speed – miles per hour MPH // declare an instance of Scanner to read the data stream from the keyboard. // get distance in miles // get driving time in hours // get fuel used in gallons // calculate Fuel mileage (MPG) // calculate Average speed (MPH) // print results – distance and time, MPH and MPG // close the input Stream Our next step is to create code to do what each of the comments says to do. Our method might then look something like the code on the next page. An import statement and introductory comments that
were not included in the outline have been added to the code. This approach – starting with the documentation – saves work, makes programming easier to understand, and reduces errors. Comments first help us to design the program, then serve to document what we did after we are finished This approach separates the process of designing from building, and is a simple way to design something before you try to build it. It is much better than “cowboy coding”, in which we try to design the software as we code and then add comments later. Many new programming students are tempted to engage in cowboy coding because the first few programs they write are simple and the design is easy, but it is better to develop good programming habits from the beginning. Remember, we’re not here to learn how to write short simple programs, we’re here to learn habits that will serve us well in the long run. Documentation first programming is one step in that direction. Here is an example of the output from the RoadTrip program showing the dialog:
Figure 7 comments describing code Figure 8 console I/O output JLK Chapter 2 – Introduction DRAFT October 2019 pg. 32 /* RoadTrip.java * program to calculate average speed and mileage for a road trip * last edited Dec. 26, 2014 by C. Herbert for CSCI 111 * package roadtrip; import java.util.*; public class RoadTrip { public static void main(String[] args) { double distance; // Distance traveled in miles
double time; // Total driving time in double fuel; // total fuel used in gallons double mileage; // mileage - average miles per gallon MPG double speed; // average speed – miles per hour MPH // declare an instance of Scanner to read the data stream from the keyboard. Scanner keyboard = new Scanner(System.in); // get Distance in miles from the keyboard System.out.println("Please enter the distance (miles): "); distance = keyboard.nextDouble(); // get Driving time in hours System.out.println("Please enter the total driving time (hours): "); time = keyboard.nextDouble(); // get Fuel used in gallons System.out.println("Please enter the total fuel used (gallons): "); fuel = keyboard.nextDouble();
// Calculate Fuel mileage (MPG) mileage = distance / fuel; // calculate Average speed (MPH) speed = distance / time; // print results - distance and time, MPG and MPH System.out.println("You traveled " + distance + " miles in " + time + " hours."); System.out.println("Your average speed was " + speed + " MPH."); System.out.println("Your mileage was " + mileage + " MPG."); // close the input stream keyboard.close(); } // end main() } // end class
Figure 9 the road trip program chapter file: RoadTrip.zip JLK Chapter 2 – Introduction DRAFT October 2019 pg. 33 Lab 2A – Console I/O: Age in Days In this step-by-step programming exercise we will create a program with console I/O to ask for the user’s name and age in years, then return the user’s name and age in days. We will use 365.25 days per year as a constant value in the code. This exercise includes the use of String and numeric data types, variables and constants, simple arithmetic in assignment statements, and console I/0. The program should: • get the user’s name • say hello to the user by name and ask for the user’s age in years • calculate the user’s age in days • print the results – the user’s age in days.
STEP 1. Open IntelliJ and Start a new IntelliJ Java project named ageDays. If any other projects are open in IntelliJ, use the File menu to close them before continuing. The source code generated by NetBeans will be similar to the source code in Figure 10. Figure 10 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 34 STEP 2. Change the comments in the code as follows: • Remove the comment on lines 14-16 identifying method parameters • Remove the comment on lines 8-11 identifying the author • Change the introductory comment at the start of the source code to include identifying information – the name of the source code file, the nature and
purpose of the project, when it was last edited and by whom, as shown in Figure 11. • Add inline comments labeling the ending braces for the method and the class. Your code should now resemble that in Figure 11. STEP 3. Add the following comments to the main method in place of the TODO comment in the main method. // declare variables // user name // age (in years) // age (in days) // constant days per year // declare an instance of Scanner to read the data stream from the keyboard. // say hello to the user and ask for the user’s name // say hello to the user by name.
// ask for the user’s age in years // Calculate how many days are in the number of years entered Figure 11 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 35 // print results // close the input stream The code should now resemble that shown in Figure 12. You will need to use the tab key to indent comments properly. When the comments are in place, we can begin to create code to do what the comments say to do. STEP 4. Add declarations to the code as the comments indicate, and remove the declare variables comment: • a String called name for the user’s name,
• a double called years for the age in years, • a double called days for the age in days. • final double DAYS_PER_YEAR = 365.25; to establish the necessary constant. Figure 12 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 36 STEP 5. Declare an instance of the Scanner class below the appropriate comment: Scanner kb = new Scanner(System.in); Also, add an import statement right after the package directive near the beginning of the code to make this work: import java.util.*; STEP 6. Add code below the comment // say hello to the user and ask for the user’s name to do what the comment says:
System.out.println("Hello, please enter your name: " ); name = kb.nextLine(); (Can you figure out why we are using the nextLine() method instead of just next() ?) STEP 7. Add code below the comment // say hello to the user by name to do as the comment says. System.out.println("Hello, " + name); STEP 8. Add code below the next comment to ask for the user’s age in years. System.out.println("How many years old are you ?”); years = kb.nextDouble(); STEP 9. Add code in the appropriate location to calculate the user’s age in days. days = years * DAYS_PER_YEAR; STEP 10. Add code to print the result, in a format similar to this: Joe, you are 9865.75 days old.
System.out.println(name + “, you are” + days + “days old.”); STEP 11. Add code to close the input stream. kb.close(); STEP 12. Figure 13 on the next page shows the complete program. Build, run, and debug your code as necessary until it runs correctly. Testing reveals the out could look better. Modify the code by adding blank println() commands to separate the different parts of the output, so that it looks something like this: Hello, please enter your name: Joe Hello Joe, please enter your age in years: 27 Joe, you are 9865.75 days old. When your program runs correctly, you are finished with this exercise.
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 37 Figure 13 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 38 JOptionPane Pop-Up Dialog Windows The Swing API is one of several used for Graphical user Interface (GUI) programming. It includes the JOptionPane class, which provides a set of objects for complete pop-up dialog windows, such as the message dialog window and the input dialog window shown below: Each window has a title, an icon, a text message, and one or more buttons. A JOptionPane input window also contains a text entry box. The color and style of the pop-up windows depends on settings in each computer’s operating system. You will notice that not all of the windows in the examples in this section have the same look and feel.
There are four different types of JOptionPane pop-up dialog windows: • message dialog window – simply displays a text message • input dialog window – gets user input as String • confirm dialog window – asks a question with confirmation buttons, such as yes/no/cancel • option dialog window – a programmable dialog window that can be used for various purposes. In the remainder of this section we will focus on the message dialog window and the input dialog window for use with simple user I/O. More detailed information about JOptionPane pop-up dialog windows can be found on the JOptionPane Class documentation page online at: http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPa ne.html Using the JOptionPane Message Dialog Window JOptionPane has many methods that can be used to create dialog windows for various circumstances. We will use the showMessageDialog() method, which displays a pop-up message dialog window. The specifications for the code are shown by the method header
from the JOptionPane class: static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) The parameters for this method are: • parentComponent – leave this as null for a simple stand-alone pop-up window. The parent component of the window would be named in more complex GUI programming. • message – the message to be displayed in the window. It is most often simply a String message. • title – a String with the title to be displayed in the top of the window. The default is “Message”. http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPa ne.html JLK Chapter 2 – Introduction DRAFT October 2019 pg. 39 • messageType – affects the look of the Window, including which icon is displayed. The JOptionPane class has several messageType constants that can be used: messageType constant Java icon ERROR_MESSAGE
INFORMATION_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE PLAIN_MESSAGE no icon is shown The default messageType is INFORMATION_MESSAGE, The icon for an information message will be shown by default If you do not include a messageType constant in the parameters. Remember, Java is a multi-platform language; some operating systems will override the Java icons and use their own versions of each icon. • icon – This parameter allows a custom icon to be used. We will skip this for now. The showMessageDialog() method may be used as an instruction in a Java program to create a pop-up message window, since it is a void method that does not return a value. The following examples show
samples of Java code and the resulting dialog windows. JOptionPane Import Statement JOptionPane windows are part of Java’s Swing package, used for building graphical user interfaces (GUIs). Their use requires an import statement, such as the following: import javax.swing.*; JOptionPane Example 1 – Default Message Dialog Window In this example, the message is specified and the parameters that follow are not used. The default INFORMATION_MESSAGE icon and title will be shown. // message dialog window with default title and icon JOptionPane.showMessageDialog(null, "This is a message dialog window.nHello World!"); JLK Chapter 2 – Introduction DRAFT October 2019 pg. 40 JOptionPane Example 2 – Plain Message Dialog Window This example includes the PLAIN_MESSAGE parameter with a custom title. No icon will be shown.
// plain message dialog window with custom title; no icon is shown in a plain message JOptionPane.showMessageDialog(null, "This is a plain dialog window.", "custom title", JOptionPane.PLAIN_MESSAGE); The same code generated all three windows. the look and feel of each was set by the operating system. JOptionPane Example 3 – Warning Message Dialog Window This example shows a WARNING_MESSAGE with a custom title and warning icon. // warning message dialog window with custom title and the warning icon JOptionPane.showMessageDialog (null, “Warning, danger Will Robinson! Danger!", "Lost in Space Warning", JOptionPane.WARNING_MESSAGE); JOptionPane Example 4 – Error Message Dialog Window
This example shows an ERROR_MESSAGE with a custom title and error icon. // error message dialog window with custom title and the error icon JOptionPane.showMessageDialog(null,"We need a bigger boat.”, "Jaws Warning", JOptionPane.ERROR_MESSAGE); Using the JOptionPane Input Dialog Window The JOptionPane showInputDialog window will accept user input from the keyboard as a String. There are many variations of this method, but the most straightforward is a question-message dialog with one parameter – the question-message to be displayed in the window. Here is the method header: static String JOptionPane.showInputDialog(Object message); JLK Chapter 2 – Introduction DRAFT October 2019 pg. 41 The method returns a String equal to whatever the user enters in the text entry box in the window. The message parameter is a String, as is the value returned by the method. We use a String variable to
capture the input. JOptionPane Example 5 – Input Dialog Window (String input) // input dialog window getting the user's name. The variable must be a String // whatever the user enters will be captured as String. name = JOptionPane.showInputDialog("What is your name?"); This simple, easy to use method works well, but what if we want numeric input? The answer is to use a two-step process: 1. get the user input as a String. 2. convert the String into a numeric value using a parsing method. Parsing Numbers from Strings In linguistics, to parse a sentence means to break the sentence down into its component parts of speech. Compilers do something similar with statements in a programming language, by parsing a statement into its component parts. We can also parse Strings, which is what we will do here. To parse a String is to convert the information in a String, or part of a String, into a value of another data type.
Java has several Number classes corresponding to each of the primitive numeric data types. Each one provides a parsing method to parse a String into the corresponding numeric data type as follows: • static byte parseByte(String) is part of the Byte class • static short parseShort(String) is part of the Short class • static int parseInt(String) is part of the Int class • static long parseLong(String) is part of the Long class • static float parseFloat(String) is part of the Float class • static double parseDouble(String) is part of the Double class Since these parsing methods are each static, they are used with the name of the class, such as Int.parseInt() or Double.parseDouble(). By far, parseInt() and parseDouble() are the most commonly used parsing methods, as shown in the examples below. If a parsing method cannot find a valid numeric representation in the String, the parsing method will create a NumberFormatException, which we learn how to handle later this semester.
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 42 JOptionPane Example 6 – Input Dialog Window (double input) // input dialog window getting a double value // first, get a String ageString = JOptionPane.showInputDialog("How old are you?"); //next, parse a double value from the string age = Double.parseDouble(ageString); in Example 6, a JOptionPane input dialog window is used to get user input as a String, then a parsing function is used to parse the String into a double value. Example 7 is similar, except that the input String is parsed to an int value. JOptionPane Example 7 – Input Dialog Window (int input) // input dialog window getting an integer value (image shows user input) // first, get a String answer = JOptionPane.showInputDialog("What is the meaning of life,
the universe, and everything?"); //next, parse a double value from the string adamsNumber = Int.parseInt(answer); Input dialog windows are convenient, but they do not take the place of a more complete graphical user interface, which we will study later in a later chapter. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 43 Exceptions When Parsing Numbers from Strings What happens if we try to parse a number from a String that does not have a numeric value? In NetBeans, the exception that is created will cause the program to fail, and we will see an error: Exception in thread "main" java.lang.NumberFormatException: For input string: "nine hundred years old" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecim al.java:1241)
at java.lang.Double.parseDouble(Double.java:540) at joptionpanedemo.JOptionPaneDemo.main(JOptionPaneDemo.ja va:36) Java Result: 1 This message tells us a NumberFormatException was created by the input String "nine hundred years old" in the readJavaFormatString method, called by the parseDouble method, called by the main method in our JOptionPaneDemo program. The first line tells us the kind of exception created. The last line tells us the ultimate cause of the error – line 36 in the method JOptionPaneDemo.main. Line 36 is not wrong, but that is the line which was being executed when the error occurred. This is line 36: age = Double.parseDouble(inputString); The computer could not parse inputString “nine hundred years old”, because it has no numbers to parse. Exceptions are objects, so before learning to handle exceptions in java code, you need to learn more about objects. These topics will be covered later in this course and in Computer Science 112. CheckPoint 2.6
1. What does the JOptionPane class provide? 2. Describe the four different types of JOptionPane pop-up dialog windows. 3. What determines the look and feel of JOptionPane pop-up dialog windows? 4. What datatype does a JOptionPane input dialog window return? 5. Describe how to parse text from JOptionPane input dialog windows into numeric data types. Figure 14 Exception warning JLK Chapter 2 – Introduction DRAFT October 2019 pg. 44 Lab 2B – Pop Up Windows Dialog: Age in Days In this exercise we will modify the code from the ageDays program in Lab 2A to use JOptionPane windows for input and output in place of console I/O. Here is a sample of the I/O from the resulting program.
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 45 The new code will have four JOptionPane windows: two message windows, and two dialog windows. The code for the calculation will be in our program between the code segments for the last two windows. The windows shown above resulted from running the code on a Windows 8.1 system. The operating system set the look and feel of the JOptionPane windows. STEP 1. Download and unzip the ageDaysComplete NetBeans project included with the files for this chapter, then open the project in NetBeans. It contains the completed ageDays project from Lab 2A. You should unzip the project folder in a place that will be easy to access from within NetBeans, such as the desktop. The source code for the project is shown in figure xx on page 35. The comment at the top of the code refers to the original code. Change the comment as follows:
1. delete the word starting on line 3 2. update the date to the current date 3. update the most recent editor’s name to be your name The existing import statement on line 8 is needed for console I/O, but not for JOptionPane I/O. Instead we need an important statement that will enable the use of Swing objects. STEP 2. Replace the existing import statement – import java.util.*; – with an import statement to enable the use of Swing objects: import javax.swing.*; STEP 3. There is no need to declare a Scanner class object in this program. Delete the code in the main method that declares a Scanner class object and the comment above it: // declare an instance of Scanner to read the datastream from the keyboard. Scanner kb = new Scanner(System.in); You should also delete any extra blank lines so the code now looks something like this:
public static void main(String[] args) { String name; // user name double years; // age (in years) double days; // age (in days) final double DAYS_PER_YEAR = 365.25; // constant days per year // say hello to the user and ask for the user’s name System.out.print("Hello, please enter your name: "); name = kb.nextLine(); // say hello to the user by name. System.out.println("Hello, " + name); // ask for the user’s age in years System.out.println("How many years old are you ?"); years = kb.nextDouble(); Figure 15
JLK Chapter 2 – Introduction DRAFT October 2019 pg. 46 Several code segments in the method perform console I/O. Now we need to replace these with code to do the same things using JOptionPane input dialog windows. STEP 4. The first console I/O code segment to be replaced is just below the constant declaration where we find a comment and two lines forming a prompt and capture pair to ask for the user’s name. Replace the two statements for the first prompt and capture pair in the source code with a statement to do the same thing with a JOptionPane input dialog window: name = JOptionPane.showInputDialog("Hello. What is your name?"); This part of the code should now look like this: final double DAYS_PER_YEAR = 365.25; // constant days per year // say hello to the user and ask for the user’s name name = JOptionPane.showInputDialog("Hello. What is your
name?"); // say hello to the user by name. System.out.println("Hello, " + name); // ask for the user’s age in years System.out.println("How many years old are you ?"); years = kb.nextDouble(); STEP 5. Replace the println() statement that says hello to the user by name with code for a JOptionPane message dialog window to do the same: JOptionPane.showMessageDialog(null, "Hello, " + name + “.”); STEP 6. Replace the prompt and capture pair of statements with a statement to do the same thing using a JOptionPane input dialog window: ageString = JOptionPane.showInputDialog("How many years old are you ?”); Notice that the variable is named ageString. We have not yet declared this variable. The input from a
JOptionPane input dialog window is always a String. We need to declare this variable near the top of the method so that we can use it. We will also need to add code after the code for the JOptionPane input dialog window to parse the String value ageString to the double value years. Figure 16 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 47 STEP 7. Add a statement to the code near the top of the method to declare ageString as a String variable to be used in the method, so that the variable declarations near the beginning of the method look like this: public static void main(String[] args) { String name; // user name String ageString; // age as a String from user input double years; // age (in years)
double days; // age (in days) final double DAYS_PER_YEAR = 365.25; // constant days per year STEP 8. Add a statement after the code for the JOptionPane input dialog window to parse the String value ageString to the double value age. years = Double.parseDouble(ageString); The input and the calculate segments of the code should now look like this: // say hello to the user and ask for the user’s name name = JOptionPane.showInputDialog("Hello. What is your name?"); // say hello to the user by name. JOptionPane.showMessageDialog(null, "Hello, " + name +”.”); // ask for the user’s age in years ageString = JOptionPane.showInputDialog("How many years old are you ?");
years = Double.parseDouble(ageString); // Calculate how many days are in the number of years entered days = years * DAYS_PER_YEAR; Next, we need to convert the output from console I/O to JOptionPane I/O. We can also remove the close command leftover from the scanner class, since it is no longer needed. STEP 9. Replace the println() statement showing the result of the calculation with code for a JOptionPane message dialog window to do the same: JOptionPane.showMessageDialog(null, name + ", you are " + days + " days old."); STEP 10. Delete the close statement and the comment that precedes it. Adjust the line spacing as needed. // close the input stream kb.close(); STEP 11. Your program is now complete.
Test and debug the project as necessary before closing the project and exiting NetBeans. Figure 17 Figure 18 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 48 Key Terms in Chapter 2 After completing this chapter, You should be able to define each of the following key terms: ad hoc polymorphism, 18 alphanumeric character, 8 ASCII, 7 assignment statement, 17 associative, 24 boolean, 6 built-in data types, 5 byte (data type), 10
byte addressable, 7 cast operator, 26 char, 7 character, 7 commutative, 24 compound assignment, 20 concatenation, 18 confirm dialog window, 38 constant, 6 data type, 5 declare a variable, 14 decrement, 20 delimiter, 27 documentation first programming, 30 double (data type), 12 final, 15 float (data type), 12
front loading declarations, 15 function overloading, 18 functions, 17 hardcoding, 15 import statement, 29 increment, 19 Input data streams, 27 input dialog window, 38 int (data type), 10 Java identifier, 16 java.lang package, 20 JOptionPane, 38 Keywords, 16 literal, 6 local variables, 14 long (data type), 10 mantissa-exponent format, 10
Math class, 21 message dialog window, 38 modulus operation, 19 narrowing primitive conversion, 25 negation, 19 non-numeric characters, 8 null variable, 14 operands, 17 operator overloading, 18 operator precedence, 23 operators, 17 option dialog window, 38 order of evaluation, 23 output data streams, 27 parametric polymorphism, 18 parse, 41 polymorphism, 17
postfix operation, 20 prefix operation, 20 primitive data type, 5 prompt and capture, 28 qualified name, 16 raw data stream, 27 reference data type, 5 remainder operation, 19 Scanner class, 28 scope of a variable, 14 short (data type), 10 significand, 10 simple name, 16 String literal, 7 String, 7 token, 27 tokenized data stream, 27 type casting, 25
unary operation, 19 Unicode, 7 UTF-16, 7 variable, 6 whitespace, 27 IntelliJ Notes – Backing Up Project Files The project folder for each NetBeans project contains the files needed for the project. It a good idea from time to time to make a backup copy of the project folder – especially for any important projects and for any projects recently edited. Two copies of any important IntelliJ project should be stored in different locations on different devices to prevent a loss of the project in case of a systems failure. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 49 Chapter 2 - Questions
1. Why do we have different data types? How can a programmer determine which data type to use for a variable? What is the range of values for a data type related to? What is the difference between a primitive data type and a reference data type? 2. What data types are built into Java in each of the following categories: Boolean data, numeric data, and text data? 3. What is the minimum storage space needed for a boolean value? Why is a boolean variable in Java stored as a byte rather than a bit? 4. How are integers entered in Java? How are they stored? What special data type does Java have for unsigned integers? What is the only difference between any two of the four integer data types in Java? Which of the Java integer data types is used most often? 5. What formats does Java use to store floating point numbers? What is the accuracy and range of values for Java’s two floating point formats? Which of the two Java floating point data types is used most often? 6. Where can we find out more about data types in Java?
7. What character set is used for char and String data in Java? Where can String literals be used in Java? How do we indicate String literals in Java? 8. How is the scope of a local variable determined in Java? 9. How is a constant different from a variable in Java? How are constants declared in Java? When does Java replace constants in code with their values? Why is hardcoding rather than using constants a bad habit to develop? 10. What rules determine how Java identifiers are named? What is camel case? How should camel case be used in naming variables, methods and classes in Java? What is the difference between a simple name and a qualified name in Java? What characters may be used in the names of Java variables? 11. What do we find to the left of the equals sign in a Java assignment statement? What do we find on the right? What will happen if an expression yields a value that is not of the same data type as the variable to which it is being assigned? Why is this a bad idea? 12. What is the difference between an operator and an operand in an expression in Java? What actually
determines which operation will be performed in Java expressions? What is this a form of? What operation will be performed on String operands with the plus sign (+) as an operator? 13. What is a narrowing primitive conversion, and why is it such a problem in computer programming? 14. What are the eight arithmetic operations that may be performed on numeric data in Java? Which of these are unary operations, and what does that mean? 15. What is the difference between postfix and prefix increment operations? Illustrate your answer with examples that show the difference. 16. What are some of the methods in the java.lang.Math class, and how are they used in Java programs? How do some of these methods exhibit polymorphism? Where can we find out more about the Java Math class? JLK Chapter 2 – Introduction DRAFT October 2019 pg. 50 17. How is the order of operations determined in a programming language? What is the order of precedence for arithmetic operations in Java? How should fractions with operations in the numerator
and the denominator, such as � + 3 � − 3 , be entered in Java as numeric expressions to preserve the intended order of operations? 18. Which arithmetic operations in Java are commutative and associative? Which two-operand arithmetic operations are not commutative and associative? 19. How are Java I/O data streams usually organized? What do they use as delimiters? What are some of the Scanner class methods we can use to read data from an I/O stream? What must we do to use them in Java? 20. What is the difference between a message dialog window and an input dialog window? What are the five message type constants used for JOptionPane message dialog windows and what are the icons that go with each of them? Chapter 2 – Exercises 1. Identify appropriate data types for each of the following situations with a reason for your choice:
a. hours, rate, and gross pay in a payroll program. b. the number of people in each census district; the average number of people in each census district. c. the number of people on a 40-passenger SEPTA bus. The code will run on a small processor embedded in the bus’s electronic passenger counter. d. Serial numbers in a program to keep track of digital recordings. e. each of the following fields in a student data base program – first name, last name, student number, city, state, zip code, major, GPA, currently enrolled? 2. In the following list of variable names, describe which are invalid in Java and why, which are valid but violate programming conventions and why, and which are valid. x, sum, sum1, float, name$, name_42, native, joeSmith, 1root, BattingAverage, status?, GPA 3. Show the output for each of the following: a. [Note: all variables are double – the square root of 10 is 3.162278] num = 10.0;
square = num*num; sroot = Math.sqrt(num); System.out.println("numbertsquaretsquare root"); System.out.println(num + ”t” + square + ”t” + sroot); JLK Chapter 2 – Introduction DRAFT October 2019 pg. 51 b. System.out.print("This assignment "); System.out.print("is due on "); System.out.print(“September, ”); System.out.println(“8th.”); c. System.out.print("This assignment "); System.out.print("is due on"); System.out.println(“September, ”); System.out.println(“8th.”); d. System.out.print("This assignment "); System.out.print("is due onn"); System.out.print(“tSeptember, ”);
System.out.println(“8th.”); 4. Rewrite each of the following formulas as Java assignment statements: a. C = 5 9 (F - 32) Fahrenheit to Celsius conversion b. payment = �� 1−(1+�)−� loan payment (a = loan amount, r = rate, n = periods) c. root = −�±√�2−4�� 2� calculating two roots of a quadratic equation d. dist = √(�2 − �1)2 + (�2 − �1)2 distance from (x1,y1) to (x2, y2) e. haversine = 1−cos (�) 2 haversine function used in maritime navigation
5. The yards and feet conversion program in section 2.3 is incomplete. Finish the program and get it to run in NetBeans. Make sure it is properly documented. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 52 I-P-O software A common simple design pattern in programming is input- processing-output (I-P-O). In problems 6 through 10, create interactive I-P-O software that asks the user for some input, processes the data, then outputs the result. You should use variable names that are more meaningful than those in exercise 3, above, or in the formulas below. Use constants where appropriate. Make your output look attractive, useful to the user, and easy to understand. Keep your code readable, easy to understand, and well-organized. 6. World City Temperature Celsius to Fahrenheit Converter Input:
• ask for a city name • ask for the current temperature in the city temperature in degrees Celsius, using the name of the city Processing: • convert to degrees Fahrenheit using the formula: F = ( 9 5 C) + 32 Output: • a statement of the form: The current temperature in London is 20 ⁰C, which is 68 ⁰F [ Note: the degree symbol is Unicode u00b0 ] 7. Monthly Loan Payment Calculator Input: • the address of the property • the amount of the loan • annual interest rate, (Entered as a decimal. For example, 4.5% is .045)
• number of monthly payments Processing: • calculate the effective monthly interest rate by dividing the annual rate by 12.0 • calculate the monthly payment using the formula in exercise 4b, above Output: • the amount of the loan • the annual interest rate • the number of monthly payments • the amount of each monthly payment [Note: test data – $100,000 at 5% for 30 years is a payment of $536.82] JLK Chapter 2 – Introduction DRAFT October 2019 pg. 53 8. Change for a dollar. Input: • using short integers, ask the user for a number of cents less than 1 dollar
Processing: • calculate the number of quarters, dimes, nickels and pennies in the amount. We do this using the division and remainder operations. Think about how you would do it, then design a program to do the same. How many quarters? How much is left over? How many dimes in that amount, and so on? Output: • a neatly organized statement of the form: 87 cents is: 3 quarters 1 dime 0 nickels 2 pennies 9. Area, Volume, and Surface Area Input: • ask the user to input a distance in inches Processing: • calculate the area of:
o a circle with that radius area = πr2 o a square with that side area = s2 • calculate the volume of: o a sphere with that radius volume = 4 3 πr3 o a cube with that side volume = s3 • calculate the surface area of o a sphere with that radius surface area = 4 πr2 o a cube with that side surface area = 6 s2 Output: • an attractive and neatly organized display of the results. 10. Identify five errors in the code on the next page that will stop the program from compiling or running: JLK Chapter 2 – Introduction DRAFT October 2019 pg. 54
— End of Chapter 2 —

The Java Learning Kit Chapter 1 – Introduction Copyri.docx

  • 1.
    The Java LearningKit: Chapter 1 – Introduction Copyright 2015 by C. Herbert, all rights reserved. Last edited December, 2014 by C. Herbert This document is a chapter from a draft of the Java Learning Kit, written by Charles Herbert, with editorial input from Craig Nelson, Christopher Quinones, and Matthew Staley. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Spring 2015 semester. This material is protected by United States and international copyright law and may not be reproduced, distributed, transmitted, displayed, published or broadcast without the prior written permission of the copyright holder. You may not alter or remove any trademark, copyright or other notice from copies of the material. The Java Learning Kit: Chapter 1 – Introduction Lesson 1.1 – Computing and Computer Science
  • 2.
    Lesson 1.2 –Algorithms and Objects Lesson 1.3 – Programming Languages Lesson 1.4 – The Java Programming Language Lab 1 – Getting Started with NetBeans and Java JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 2 Contents Computing and Computer Science .................................................................................. 5 What is computer science? ............................................................................................... .................. 6 What do computer scientists and software engineers actually do? ................................................... 7 CheckPoint 1.1 ............................................................................................... ..................................... 8 Professional Organizations ............................................................................................... ................... 9 Computer Science Specializations ................................................................................ ............... ...... 10
  • 3.
    Algorithms and Objects ............................................................................................... ..11 CheckPoint 1.2 ....................................................................................... ........ ................................... 12 Programming Languages ............................................................................................... 13 Machine Code ............................................................................................... .................................... 13 Assembly Language ............................................................................................... ............................ 13 High Level Languages ............................................................................................... ......................... 14 Compilers and Interpreters ............................................................................................... ................ 14 The Java Advantage ............................................................................................... ........................... 15 FORTRAN ............................................................................................... ............................................ 16
  • 4.
    Who develops andregulates technology standards? ....................................................................... 17 Algol ....................................................................................... ........ ................................................... 18 COBOL ............................................................................................... ................................................ 19 Functional Programming: LISP and Lambda Calculus ........................................................................ 20 BASIC ............................................................................................... .................................................. 21 Pascal ............................................................................................... ................................................. 22 The C Programming Language ................................................................................ ............... ........... 23 Simula and Smalltalk ............................................................................................... .......................... 24 C++ ............................................................................................... ..................................................... 25 Perl ...............................................................................................
  • 5.
    ..................................................... 26 C# (C Sharp)..................................................................................... ..................................................26 Python ............................................................................................... ................................................ 28 JavaScript ............................................................................................... ........................................... 30 PHP ............................................................................................... .................................................... 31 Ruby ............................................................................................... ................................................... 32 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0891 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0892 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0902
  • 6.
    JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 3 CheckPoint 1.3 ............................................................................................... ................................... 33 Lesson 1.4 The Java Programming Language ........................................................................................ 34 History and Development of the Java Language ............................................................................... 34 A Look at Java Source Code ............................................................................................... ................ 35 Why Java? ............................................................................................... .......................................... 36 Versions of Java ............................................................................................... ................................. 38 CheckPoint 1.4 ............................................................................................... ................................... 38 Lab 1 – Getting Started with NetBeans and Java .................................................................................. 39 Hello World! ............................................................................................... ....................................... 39
  • 7.
    Creating a NewJava Project – Step-by-Step ..................................................................................... 40 CamelCase Names in Java ............................................................................................... .................. 43 Description of the Source Code in a New Java Project ...................................................................... 44 Hello World! – Step-by-Step (continued) ........................................................................................ 47 Closing NetBeans Properly ............................................................................................... ................. 50 Copying and Submitting NetBeans Projects .................................................................................. .... 51 Key Terms in Chapter 1 ............................................................................................... .......................... 52 Chapter 1 - Questions ............................................................................................... ............................ 53 Chapter 1 - Exercises ............................................................................................... .............................. 54
  • 8.
    file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter1%20- %20Introduction/JLK%201%20introduction.docx%23_Toc40769 0927 JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 4 Chapter 1 – Introduction This chapter is a brief introduction to computers, programming, and using Java to create software. Section 1 provides a brief background in computers and computer science, some of which may be familiar to you. It also has information from the ACM and IEEE about what computer scientists do and specializations in the field of computer science. Links in the section lead to more detailed information from experts in the field. A discussion of algorithms and objects in section 1.2 provides a short introduction to these two topics that lie at the heart of modern software development. Section 1.3 has an overview of computer programming languages. The last part of the chapter – sections 1.4 and Lab 1 – focus on Java. Section 1.4 introduces the
  • 9.
    Java language, whilethe lab will help you get started creating and editing Java software development projects using NetBeans, a widely used integrated development environments (IDE). The Lab introduces elements of Java projects, comments in Java source code, how to copy and move Java projects, and how to submit Java projects as homework assignments in Computer Science 111. Learning Outcomes Upon completion of this chapter students should be able to: electronic computer system; nce and common specializations within the field; in computer science; -oriented programming; ers do, and how they compare to one another; of each in the history of programming languages;
  • 10.
    role of Javabytecode, the Java Virtual Machine and the Java Runtime Environment in that process; , zip the project, and transmit the project as an email attachment, via social networking, or in a learning management system. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 5 Computing and Computer Science Generally speaking, a computer is any device that can store and process information. Most modern computers include a processing unit, often called a central processing unit or CPU; internal memory; input units; output units; and external storage devices, which could be considered a special category of input and output units. Figure 1-1 shows a block diagram of such a system. The various parts of the
  • 11.
    computer system areconnected by one or more communication channels. Each communication channel is a set of wires called a bus. Usually, three separate busses carry data, instructions, and control signals throughout the computer. A Central Processing Unit can be thought of as the heart or the brain of a computer system. It usually has one or more Arithmetic Logic Units (ALU) that process data by performing binary arithmetic, registers to hold data temporarily during processing, and a control unit to control the flow of information throughout the computer. The control unit orchestrates the timing and coordination of all of the computer system’s components, both within and outside of the CPU.
  • 12.
    Internal memory ina modern computer is chip-based electromagnetic memory, with no mechanical moving parts. It is usually much smaller and faster than external storage. The internal memory could be on the same chip as the CPU or in separate chips, depending on the sophistication and size of the system. There are generally two distinct types of internal memory – Random Access Memory (RAM) in which randomly selected memory cells can be written to, erased, and reused; and Read Only Memory (ROM) which has programs or data permanently burned into a chip that can read but not re-written. External storage includes larger and slower memory devices, such as hard disk drives. They are usually electromechanical, which means they have moving parts that slow things down, such as spinning disks. Some newer technologies used for external storage, such as Flash ROM, use no moving parts, but are still slower than internal memory because of the technology used and because of the distance to the CPU. Flash ROM is a slower, less expensive non-volatile electromagnetic version of RAM technology with
  • 13.
    a limited numberof access cycles. Commonly used USB flash ROM storage devices are convenient, but should not be relied upon for long-term storage of important data because the chips eventually wear out and because they could be damaged by environmental factors, such as magnetic fields or static electricity. Figure 1. A simple block diagram of the major components in a computer system. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 6 Input units bring data into the computer from the outside world. Output units send data from the computer to the outside world. Together, they are referred to by the term input/output, or I/O. Peripheral equipment, or just peripherals, are devices outside of the main part of the computer that communicate with the CPU through I/O controllers. Most people consider external storage devices to be included in the term peripherals, along with I/O and communication equipment, such as keyboards, screens, and network adapters. The field of human–computer
  • 14.
    interaction (HCI) addresseshow people interact with computers including hardware, software, and computing practices. HCI experts help design I/O devices that people will use to communicate with computer systems. Data — including both data to be processed and instruction sets (programs) for the CPU — are usually moved from slow external storage into fast internal memory when needed, then moved back again for long-term storage. There is a hierarchy of memory within a computer system, from smaller, faster (and more expensive) caches of memory located close to or within the CPU to larger, slower (and less expensive) memory located farther away from the CPU. The actual organization of a computer varies from system to system, but the simple diagram above still captures the essential organization of digital electronic computers. Today, the circuitry for a complete computer system can actually be placed on a single chip. The organization of computer systems and the transfer and control of data within a computer system are studied in greater detail in a Computer Organization and Architecture course – the equivalent of an
  • 15.
    anatomy and physiologycourse for computers. Such courses are often required in Computer Science, Computer Engineering, and related degree programs. What is computer science? Computer Science is the scientific study of computation, theoretically and in practice, as the basis for modern information systems. Computation includes numerical calculation and processes related to calculation. This may sound a bit boring, but remember, Information isn’t just numbers; it can also be text, graphics, sound, or video – anything that can have meaning to people. Modern computer systems manipulate, communicate, and store information in its many forms. Modern personal computer systems, tablets, and cell phones are the convergence of many devices dealing with information – typewriters, calculators, telephones, cameras, radios, televisions, sound and video recording equipment, and so on. Modern computer science is really a convergence of many fields of study dealing with information in its many forms. Yet at heart, computers are always about numerical processing, since, all information in its
  • 16.
    many forms isrepresented numerically inside a computer. It’s all done with numbers. Computer Science is the study of how it’s done. Computer scientists study the theoretical ideas underlying modern computer systems and the practical application of those ideas to make sure that computer systems do what they are supposed to do correctly and in an efficient manner. They also search for new and better ways to build and use computers. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 7 Programming is only important part of computer science. Today computer scientists who develop new software and maintain existing software are often known as software engineers, applying time-tested engineering concepts and practices to the modern discipline of computer programming. What do computer scientists and software engineers actually do? The layering of complex systems around simpler systems is one of the key aspects of computer science and modern computer systems. Some computer scientists and software engineers work directly with
  • 17.
    algorithms for thefundamental processes found in the innermost layers of all computer systems, but most work with the outer layers, the application software that people see when they use computers. Let’s look at an example of this layering, and then see how it relates to what computer scientists and software engineers actually do, followed by a look at specializations in computer science. A typical task, or application, for which we would use a computer system is word processing – creating, editing and printing documents using a computer system, most often using a keyboard and screen. A word processing program manages all of this so that you don’t need to worry about how it’s actually done. This is an example of application software, which is software people use to complete a task in the world outside of the computer system, as opposed to system software used to manage the computer. The word processing program asks the operating system to tell it what keys the user is pressing, and translates this into instructions telling the operating system what to store in memory, what to display on the screen, and so on. An operating system is like a master program always running on a computer and
  • 18.
    coordinating what thecomputer does. It also provides the interface between a user and the system. The operating system works with short specialized programs called system utilities to complete specific tasks. Device drivers are a type of utility software that allows an operating system to communicate with the circuitry controlling specific hardware– such as a video control unit, a memory management unit or a disk controller. Together, the application software, the operating system, and the device drivers carry Figure 2. A computer system is composed of layers of specialized software. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 8 out binary digital arithmetic manipulating billions of bits of data each second to complete all of the tasks that are part of word processing. Hardware engineers design the hardware, systems programmers develop the operating system and utility software, and applications programmers design the software that most people see and use
  • 19.
    directly. All contributeto the development of systems for tasks such as word processing. Those who start out studying computer science may end up as pure computer scientists expanding the theoretical foundations of computing, but most will specialize in other areas, particularly software development, and the majority of software developers are application developers. Most application developers specialize in areas that overlap with other disciplines. Business programmers, for example, usually need to know something about business, most often accounting, or they need to work with specialists who have such knowledge. Game programmers often work with graphic artists and audio engineers. They sometimes work with physics programmers or use a physics engine written by physics programmers to create realistic movement and interactions between physical objects in games that mimic the real world. The expertise needed to design and create software is as varied as the software itself. The term computer engineering is related to computer science. Computer engineering usually refers to
  • 20.
    the study anddevelopment of computer hardware and involves the study of physics, computer science, and engineering, especially electrical engineering. Hardware engineering and software engineering are distinct fields, but there is a great deal of overlap between the two, so the term computer engineering often includes both. Theoretical computer science provides a foundation for both hardware and software engineering, but is most closely linked to software engineering, especially focusing on the development of efficient algorithms and data structures for information processing. The study of advanced mathematics is important in both software engineering and hardware engineering. In summary, some computer scientists are theoretical computer scientists – the philosophers of the computer world. Others focus on low-level systems engineering and programming, but most are application developers working on the outer layers of software that carry out common processes in our everyday world – video games, word processing programs, business software, and so on. They often have additional knowledge in other fields or work with people who have such knowledge.
  • 21.
    CheckPoint 1.1 1. Whatis a computer? 2. What is inside a CPU? 3. What field in computing addresses how people use I/O devices? 4. What is Computer Science? 5. How are the terms software engineering and computer engineering related to one another? JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 9 Professional Organizations The Computer Science Accreditation Board (CSAB) is the primary agency for accrediting Computer Science degree programs in the United States. They recognize several areas of specialization in computer science education, listed on the following page. (See their website at http://www.csab.org)
  • 22.
    The CSAB issponsored by two major computer science professional organizations – the Association for Computing Machinery (ACM) and the Institute of Electrical and Electronic Engineers (IEEE). Professional organizations are made up of members with qualifications in a specific area – usually a college degree in the field or professional licensing, such as the American Bar Association for lawyers and the American Medical Association for physicians. According to the ACM website: The ACM, the world’s largest educational and scientific computing society, delivers resources that advance computing as a science and a profession. ACM provides the computing field's premier Digital Library and serves its members and the computing profession with leading-edge publications, conferences, and career resources. Their website has listings for professional jobs in computer science and education. They have a large repository of professional literature about research and development in the field of computing.
  • 23.
    The IEEE Websitesays: The IEEE is the world's largest professional association dedicated to advancing technological innovation and excellence for the benefit of humanity. IEEE and its members inspire a global community through IEEE's highly cited publications, conferences, technology standards, and professional and educational activities. The IEEE focuses on Electrical Engineering and related fields, including data communications and computing. They publish standards for these areas that are often the basis for ISO standards. Their website features job listing for professional engineers. See http://www.acm.org/ for more information about the ACM and http://www.ieee.org for more information about the IEEE. Both the ACM and the IEEE have student memberships. ACM student membership page: http://www.acm.org/membership/student IEEE student membership page: www.ieee.org/students
  • 24.
    http://www.csab.org/ http://www.acm.org/ http://www.ieee.org/ http://www.acm.org/membership/student file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/ww w.ieee.org/students http://www.acm.org/ http://www.ieee.org/ JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 10 Computer Science Specializations specializing in the spatial and temporal efficiency of software and the relationship between data formats and processing to manipulate data developing machines with intelligence, including decision making, perception, planning, and machine learning similar to human mental abilities the logical design and organization of computers and their components graphics creating and improving computer based imaging methods and technology improving the efficient transport and security of data between
  • 25.
    systems mathematically-based efforts toimprove the way people and enterprises store and access data computing across multiple platforms -computer interaction (HCI) how people use computer and how computers communicate with people e and security keeping data safe from harm and from loss or change due to technical factors the applied mathematics end of computing focus on software to coordinate and control computer systems, and to provide a bridge between the hardware and the user the execution of algorithms using multiple coordinated processors research into better ways to develop software an engineering approach to designing and building software
  • 26.
    theoretical study ofthe limits and nature of computing The CSAB recognizes each of the above areas as sub-fields within computer science. For career information see: http://www.csab.org/career.html. ACM special interest groups (SIG) bring together computer scientists in these and other specializations, such as bioinformatics, computers and society, or embedded systems. See: http://www.acm.org/sigs http://www.csab.org/career.html http://www.acm.org/sigs JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 11 Algorithms and Objects At the heart of everything computer scientists study, at the core of computing, we find the concept of the algorithm. Simply put, an algorithm is a step-by-step process. Early in the ninth century of the Christian Era, a scholar named Muhammad ibn Musa al-
  • 27.
    Khwarizmi (Arabic: ‫دمحم‬‫نب‬ ‫ىسوم‬ ‫)يمزراوخلا‬ came to live and work in the City of Baghdad. Al-Khwarizmi1 means from Khwarezm (Arabic: ‫مزراوخ‬, Russian: Хорезм, Uzbek: Xorazm), in what is now Uzbekistan, which was his ancestral homeland. He was one of many scholars brought to Baghdad by the Caliph to form one of the world’s first modern universities. Al-Khwarizmi wrote several important books on mathematics, geography, and astronomy, but perhaps his most important work was his second book, al-Kitab al-mukhtasar fi hisab al- jabr wa'l-muqabala (‫بات‬ ‫ك‬ ‫رص‬ ‫لا‬ ‫ت‬ ‫خم‬ ‫ي‬ ‫لا‬ ‫باس‬ ‫ف‬ ‫رب‬ ‫ح‬ ‫ج‬ ‫ةل‬ ‫لا‬ ‫ل‬ ‫)وا‬ (A ‫م‬ ‫اب‬ ‫ق‬ Compendium on Calculation by Completion and Balancing), in which he presented a method for solving math problems by balancing equations. His method came to be known as algebra. (Al-jabr = algebra.) This was only one part of his systematic approach to solving math and science problems, known in various
  • 28.
    languages as themethod of al-Khwarizmi, and from which we get the Latinized term algorithm2. According to the French writer and historian Andre Allard3, almost all Western ideas about mathematics, and hence much of modern science, technology, and engineering, were derived in part from seven critical texts written during the twelfth century and widely circulated through Europe in the centuries that followed. All seven of those books quote extensively from translations of al-Khwarizmi’s work. He stands with Euclid and a few others as one of the ancient founders of modern Science, Technology, Engineering and Mathematics – the STEM disciplines. A computer program is a step-by-step set of instructions telling a computer how to perform a specific task. As such, every computer program is an algorithm. Students in a good computer programming course are consciously learning about the logical structure of algorithms and techniques for organizing algorithms which have their roots in the work of al-Khwarizmi more than a thousand years ago. 1 For more about Al-Khwārizmī and his work see: http://www-groups.dcs.st-
  • 29.
    andrews.ac.uk/history/Mathematicians/Al-Khwarizmi.html 2 From DonaldKnuth’s Website at Stanford University: http://www-cs-faculty.stanford.edu/~uno/graphics.html 3 Allard, Andre (1992) Le calcul indien (Algorismus) / Muhammad ibn Musa al-Khwarizmi ; histoire des textes, Paris: Libraire scientifique et technique Albert Blanchard. Figure 3. A Soviet stamp from the 1980s marking al- Khwarizmi’s 1200th birthday. http://www-groups.dcs.st- andrews.ac.uk/history/Mathematicians/Al-Khwarizmi.html http://www-cs-faculty.stanford.edu/~uno/graphics.html JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 12 Of course, data and algorithms have evolved since the days of al-Khwarizmi, especially since the advent of computers in the twentieth century. Computer scientists developed the notion of objects and object- oriented programming to help manage the growing complexity of data and algorithms. Anything that can be represented by data in the computer’s memory and
  • 30.
    manipulated by algorithmsimplemented as computer programs can be organized as an object. Objects can be things in the physical world or even just abstract ideas. An airplane, for example, is a physical object that can be manipulated by a computer. A student’s grade point average is an example of an object that is not a physical object. The data that represent an object are organized into a set of properties. Each property is a unit of data that describes the object in some way. The programs that manipulate the properties of an object are known as the object’s methods. In a modern computer system, an object is a collection of properties and the methods that are used to manipulate those properties. This modern approach to computer programming is known as object-oriented programming, or OOP for short. Objects with the same methods and properties
  • 31.
    are instances ofthe same class of objects. A class definition is a like blueprint for new instances of the object. Figure 3 shows a Universal Modeling Language (UML) diagram for a BankAccount class of objects. Each instance of the object will have the same properties, but have its own values in those properties. Java is an object-oriented programming language. You will learn much more about objects and object- oriented programming as you study Java. CheckPoint 1.2 1. What is an algorithm and why are algorithms important in computer programming? 2. What is an object? 3. What is the difference between a class of objects and an instance of an object? 4. What is a property in object-oriented programming? 5. What is a method in object-oriented programming?
  • 32.
    Figure 4. AUML diagram for a BankAccount class of objects. Each individual account is an instance of the class. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 13 Programming Languages All of a computer system’s data and instructions are processed in a CPU’s arithmetic logic units that perform binary arithmetic. Usually, the data and instructions come into a processor in separate streams – a data stream and an instruction stream. Some of the instructions in the instruction stream tell the processor which math operations to perform, while others direct the movement of data. Still others control the logic of programming – the branching and looping present in algorithms. At the level of the CPU, a computer’s instructions are in the form of binary numbers, just like the data itself. Programs written in languages like Java must somehow be converted into these ones and zeroes. Machine Code The set of binary numbers that the CPU understands as its instruction set is called the computer’s
  • 33.
    machine code. EachCPU, or each family of CPUs, such as the Intel x86 family, has its own machine code. So, there are just as many different machine codes as there are families of processing units. Eventually, everything that a computer does must be translated into its machine code. Assembly Language When a new processor is first developed, it can only be programmed in machine code. Systems programmers use machine code to build an assembler, which is a program that translates assembly language into machine code. An assembly language is made up of very primitive instructions, just like machine code, but they can be written using numbers in bases other than base two and mnemonics, which are short words that sound like what they represent and are easy to remember, such as ADD for addition or SUB for subtraction. They can also use symbolic names instead of numbers to refer to memory locations. Assembly Language Machine Code Hexadecimal Equivalent mov ebx,mval
  • 34.
    mov ecx,arraySize mov edi,arrayPtr L1:mov eax,ebx imul eax, DWORD PTR[edi] mov DWORD PTR[edi],eax add edi,TYPE DWORD loop L1 10001011 01011101 00001000 10001011 01001101 00010000 10001011 01111101 00001100 10001011 11000011 00001111 10101111 00000111 10001001 00001100 10000011 11000111 00000100 11100010 11110100 8B 5D 08
  • 35.
    8B 4D 10 8B7D 0C 8B C3 0F AF 07 89 07 83 C7 04 E2 F4 Figure 5. Part of an Intel x86 family assembly language program. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 14 Figure 5 shows the main body of a program written in x86 assembly language, the language for the Intel family of processors used in most personal computers, along with the code’s translation into binary x86 machine code and its hexadecimal (base 16) equivalent. This code multiplies each value in an array in memory by a scalar value. Hexadecimal numbers are often used in printouts of machine
  • 36.
    code to makethe code easier read. The translation from binary to hexadecimal is simple, because 16 = 24. Each hexadecimal digit represents four binary digits, as shown in the chart below. Hexadecimal and binary numbering are often covered in courses in Computer Math and Logic or Discrete Mathematics. Binary Equivalents of Hexadecimal Digits 1111 = F 1011 = B 0111 = 7 0011 = 3 1110 = E 1010 = A 0110 = 6 0010 = 2 1101 = D 1001 = 9 0101 = 5 0001 = 1 1100 = C 1000 = 8 0100 = 4 0000 = 0 High Level Languages Creating software can still be difficult and time consuming in assembly language. Eventually, computer scientists and software engineers build translators that can handle high-level languages, which are programming languages that are closer to human languages and easier for people to understand. Java, JavaScript, Visual BASIC, C++, and Python are all examples of modern high-level computer programming
  • 37.
    languages. In contrast,machine code and assembly language are called low-level languages. Compilers and Interpreters There are two types of translators that convert high-level languages into machine code: compilers and interpreters. A compiler translates an entire program into machine code and stores the result. The programmer ends up with two stored copies of the program. The first, in the original high-level programming language, is called the source code. The second stored copy of the program, which is the same program after translation into a particular machine code, is called the object code. Even after translation into machine code, a program may still need to be linked with subroutines from the operating system so that it will run on a particular platform. This step is sometimes called linking and loading or making an executable program. Sometimes linking and loading happens when we try to run object code, and sometimes the compiler makes and stores an executable program as another step in the process of compiling. In either case, with a compiler, there are at least two stored copies of the program, the original source code along with the already-
  • 38.
    translated the objectcode, and often a third copy called an executable program. An interpreter is much simpler than a compiler. An interpreter translates a program one instruction at a time as the program runs. It feeds each translated instruction to the CPU to be executed before translating the next instruction. The only stored copy of the program is the original source code. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 15 Often scripting languages, such as JavaScript or Visual BASIC for Applications (VBA), are interpreted. Scripting languages are simplified high-level languages that allow someone to program in a particular environment. JavaScript can be added to the HTML codes for Web pages to provide them with some primitive data processing capability. VBA allows someone to program features in Microsoft Office products, such as Word or Excel. Interpreters have also been used for teaching languages. Serious computer programming languages
  • 39.
    such as Javaand C# that are used by professional software developers are sometimes referred to as production languages. Teaching languages are languages that are not generally used in production environments, but are instead used to teach someone the logic of computer programming or the processes used in creating computer software before attempting to teach them to use production languages. The Pascal programming language was an example of a teaching language. The Java Advantage What about Java? Java is both compiled and interpreted. Portability and high performance were both design goals for the Java language. These goals are sometimes in conflict because of the differences from one platform to another. Java’s developers introduced the Java Virtual Machine to address this issue. The Java Virtual Machine (JVM) is basically an interpreter that can handle a simplified intermediate language called Java bytecode. Java bytecode is a set of one and two-byte codes representing an intermediate step between Java source code and a computer’s machine code. It is very similar to a generic machine code, which can be translated into
  • 40.
    a specific machinecode more quickly and easily than a high-level language. A Java compiler first translates Java source code into Java bytecode. This can be stored and moved from one platform to another. Java .class files are bytecode files. Each machine that needs to run Java is equipped with a Java Runtime Environment (JRE) that has everything needed to run Java software on Figure 6. All programs must be translated into machine code. Compilers, interpreters and assemblers perform this translation. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 16 that machine, including a JVM that translates and runs the Java bytecode as machine code for the host platform. The JVM’s rapid translation from bytecode to machine code provides high performance. The use of bytecode, combined with the widespread availability of JVMs for almost all processors, makes Java software very portable. Both Apple and Microsoft were highly critical of this approach,
  • 41.
    but it provedsuccessful, largely due to the Internet. Today, almost all Web browsers are Java-enabled – meaning that they can run Java bytecode – and most personal computers, tablets and smart phones are enabled with a Java Runtime Environment or its equivalent, which is free for all systems4. According to Oracle, there were over 1.1 billion PCs and over 3 billion smartphones running Java at the end of 20135. There are now more Java- enabled devices in the world than there are people. This portability for a powerful object-oriented language is what IBM calls “The Java advantage”. Let’s take a look at several other important and popular high- level languages that were developed over the years. FORTRAN FORTRAN, one of the first high level programming languages, was released in 1957 by IBM for use on their popular 701
  • 42.
    computer. It was proposedby John Backus, a mathematician who specialized in writing programs to perform complex calculations. The name FORTRAN comes from the two words “formula translator”, and as the name implies, it was designed for use by scientists and engineers, with special instructions for math functions. 4 The JRE download page is online at: http://www.oracle.com/technetwork/Java/Javase/downloads/Java -se-jre-7-download-432155.html 5 See Oracle’s Lean About Java Technology page online at: http://www.Java.com/en/about/ According to the site, “31 times
  • 43.
    more Java phonesship every year than Apple and Android combined.” ! FORTRAN 77 by C. Herbert ! code to find the roots of a quadratic equation PROGRAM ROOTS READ A,B,C D = B**2 - 4*A*C IF (D.GT.0.0) THEN D = S**0.5 X1 = (-B+D)/(2*A) X2 = (-B-D)/(2*A) PRINT *, 'TWO REAL ROOTS:' X1 'AND' X2 ELSE IF (D.GT.0.0) THEN X = -B/(2*A) PRINT 'ONE REAL ROOT:',X ELSE PRINT 'NO REAL ROOTS' END IF
  • 44.
    END IF END Figure 7– FORTRAN 77 http://www.oracle.com/technetwork/java/javase/downloads/java -se-jre-7-download-432155.html http://www.java.com/en/about/ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 17 Who develops and regulates technology standards? Technology standards are important in the modern world so that things like computers (or telephones, or even plumbing systems) are compatible with one another. They are also important to maintain public health and safety. Various governmental and private agencies are responsible for technology standards. es are part of the government or are backed by the government and have the force of law behind them. Their standards are often called regulations rather than standards. Sometimes they adopt standards from other agencies and give them the force of law. For example, The Federal Communications Commission (FCC) is a federal government agency in the U.S. responsible for regulating electronic communications. They can regulate the nature and amount of electromagnetic interference a computer generates, so that it
  • 45.
    won’t interfere withcell phones. The Occupational Health and Safety Administration (OSHA) can regulate how computers and related equipment affect workers in business and industry. There are many such agencies. pendent organizations, but are sometimes supported by the government or are part of the government, depending on the country. The International Organization for Standardization, also named ISO, is an umbrella group responsible for international standards in a wide variety of areas. (The name ISO comes from the Greek for equal, and is not an acronym.) It is composed of national standards agencies from more than 160 countries around the world. The American National Standards Institute (ANSI) is the national standards agency in the United States. It is a private, non-profit voluntary organization composed of committees of experts in different fields. Some national standards agencies are government agencies, such as the Standardization Administration of the People's Republic of China (SAC), the Chinese equivalent of ANSI. The ISO has released standards for many programming languages. For more information on ISO and its members, see: http://www.iso.org/iso/home/about/iso_members.htm societies, such as the ACM and the IEEE mentioned earlier in this chapter, often release standards and guidelines. The IEEE has played an important role in developing standards for electronics and computing, such as the IEEE standards for
  • 46.
    floating point numbers. commoninterest. The Electronics Industries Alliance (EIA), formerly known as the Electronics Industries Association, is an organization of computer and electronic equipment manufacturers. They often adopt standards so that equipment from different manufacturers is compatible. The Computer Technology Industry Association (CompTIA) publishes standards for certifying computer professionals, especially in networking and security. Sometimes a group of industry experts from industry, academia, and the government get together to address areas of common interest. This happened in Philadelphia in 1960 when CODASYL, the Conference on Data Systems Languages, was formed to discuss “the feasibility of establishing a common language for programming of computers in business data processing applications.” * Their work gave rise to the COBOL language. control their own standards. Technically, Java belonged to Sun Microsystems, but was designated as Free Open Source Software, and the current mechanism for proposing changes to the java standard is the Java Community Process (see http://www.jcp.org ). The .NET languages – (C#.NET, VB.NET, etc.) are owned by Microsoft. * from The History of Cobol, edited by William M. Klein, available online at:
  • 47.
    http://home.comcast.net/~wmklein/DOX/History.pdf http://www.iso.org/iso/home/about/iso_members.htm http://www.jcp.org/ http://home.comcast.net/~wmklein/DOX/History.pdf JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 18 Versions of FORTRAN were soon created for IBM’s other computers, including the 1400 series, and then for most of the more popular computers from other vendors. This made FORTRAN the first portable programming language – one that is widely used across different computing platforms. The FORTRAN code had to be compiled for each specific platform, but the source code could be used on any computer with a FORTRAN compiler. IBM developed several versions, culminating in FORTRAN IV in 1962. The American National Standards Institute (ANSI) issued a definition for a standard FORTRAN language, called ANSI FORTRAN 66, in 1966 followed by ANSI FORTRAN 77 in 1977. In 1991, the ISO released an international standard for Fortran, with a parallel ANSI standard, which broadened the language and changed the name from all caps to simply Fortran. That version
  • 48.
    is often calledFortran 90. Before FORTRAN almost all software was created using assembly language and machine code. Once FORTRAN appeared, people began to use it for much more than science and engineering. The increasing use of FORTRAN to process commercial business data led to problems for financial accountants and auditors. A bank auditor, for example, needs to be able to “follow the money” from one account to another. This was nearly impossible with FORTRAN, unless the auditor was also a trained computer programmer. In addition, even though FORTRAN contained functions for mathematics, it was not well suited for programming business and financial transactions. Other languages were needed. A list of free FORTRAN tutorials is available online at: http://www.fortran.com/fortran/market.html . This webpage is maintained by the Fortran Company, which provides Fortran products and professional consulting. Today Fortran is a rarely used programming language, but some applications based on old legacy code still use it. Algol
  • 49.
    Soon after thedevelopment of FORTRAN, John Backus was also instrumental in the development of Algol, which was a language designed by an international group of mathematicians and programmers for use in describing and discussing algorithms. Some of the more important features of modern programming languages that first appeared in Algol include: -end pairs to mark blocks of code and limit the scope of variables rameters to implement their own data types. Algol was never commercially successful as a production language, nor was it intended to be. Burroughs was the only large computer company that provided an Algol compiler, and many of its features were additions to the Algol standard. Algol did not have the built-in specific tools for scientific or business programming like FORTRAN or COBOL, and it lacked a standard definition of input and output routines
  • 50.
    for file handling,screen displays, and printing. Instead, it was the language used internationally by research computer scientists to publish algorithms, and created a foundation for more advanced programming languages, including most modern programming languages. C, C++, Java, Python and most http://www.fortran.com/fortran/market.html JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 19 other languages used widely today can trace their origins back to ideas implemented in Algol. In fact, even early languages, such as COBOL and BASIC, adopted features from Algol. Several early versions of Algol were defined, including Algol 58 (1958), Algol 60 (1960). COBOL The solution to the problem of using FORTRAN in the business world was solved with the introduction of the COBOL language in 1960. Like the name FORTRAN, COBOL is an acronym that comes from the words COmmon Business-Oriented Language. COBOL was developed by a team of people working for
  • 51.
    the United StatesNavy under the direction of Grace Hopper, who went on to become an admiral (O-7) before she retired after a 40-year naval career. In April of 1959, The Conference on Data Systems Languages (CODASYL) held their first meeting at the University of Pennsylvania in Philadelphia. The conference, made up of representatives of major computer companies and several government agencies, was formed by the Defense Department to develop a standardized business programming language that could be used across all computing platforms. The first COBOL compilers were released in 1960. The first ANSI version of COBOL was COBOL 68, followed by COBOL 74 and COBOL 85, which was adopted as an ISO standard. procedure Findmax(a) Size:(n) Result:(b) Subscript:(k); value n, b,k; array a; integer n, b, k; comment Find the maximum value in an array of n integers, b is the minimum value, k is its index -- Algol 60 code by C. Herbert; begin integer i;
  • 52.
    b := a[1];k := 1; for i := 2 step 1 until n do if a[i] > b then begin b := a[i]; k := I; end end Findmax Figure 8 – Algol 60 JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 20 COBOL has functions and instructions that are more suited to commercial data processing than FORTRAN, and is a wordier language, which makes it easier for financial auditors to understand without extensive training. It was better suited for business recordkeeping and accounting than FORTRAN or almost any other language, which is what the language was designed to do. It was estimated that by the year 2000 there were more lines of
  • 53.
    code written inCOBOL than in any other computer programming language, and that more than 80 percent of the world’s business software was written in COBOL. The use of COBOL declined at the end of the twentieth century, coinciding with the rise of electronic spreadsheets, specialized accounting software, and relational database management systems. In 1990, the US Department of Labor estimated there were 500,000 professional COBOL programmers in the US. By 2010, that number had dropped to less than 75,000. Today, only a small percentage of new programmers are learning COBOL. Functional Programming: LISP and Lambda Calculus Another programming language that appeared around 1960 was LISP, developed at MIT by John McCarthy with some help from Marvin Minsky. The name LISP comes from “List Processing”. LISP is a functional language based on Lambda Calculus. As the name implies, the processing of lists, especially linked lists, is an important feature of the language. Princeton mathematician Alonzo Church developed Lambda Calculus in the 1930s as a formal system of logic for discussing mathematical functions. It is important in
  • 54.
    computer science, especiallyas the basis for functional programming languages. Lambda Calculus is all about substituting one equivalent item for another. In standard algebra, for example, if we discover that Y = X+3, then we could substitute X+3 in place of Y to help solve for X in 2X+Y=12. It becomes 2X+(X+3) = 12 which reduces to 3X+3=12, then 3X=9, then X=3. Earlier in this chapter we discussed the ninth century work of al-Khwarizmi, from whom algorithms derive their name. He was one of the first to formalize a language for this kind of IDENTIFICATION DIVISION. PROGRAM-ID. Multiplier. AUTHOR. Michael Coughlan. * COBOL 68 sample program from The University of Limerick, Ireland * Example program using ACCEPT, DISPLAY and MULTIPLY to * get two single digit numbers from the user and multiply them together DATA DIVISION.
  • 55.
    WORKING-STORAGE SECTION. 01 Num1PIC 9 VALUE ZEROS. 01 Num2 PIC 9 VALUE ZEROS. 01 Result PIC 99 VALUE ZEROS. PROCEDURE DIVISION. DISPLAY "Enter first number (1 digit) : " WITH NO ADVANCING. ACCEPT Num1. DISPLAY "Enter second number (1 digit) : " WITH NO ADVANCING. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", Result. STOP RUN. Figure 9 – COBOL 68 JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 21 substitution to solve calculation problems. Professor Church developed lambda calculus as a theoretical model for computation, originally used to explore which
  • 56.
    functions can andcannot be computed using algebra or any other system of calculation. It has become a cornerstone of theoretical computer science. LISP has been an important language, associated with research into artificial intelligence and functional programming, but otherwise rarely used as a production language for business, scientific, or systems programming. Today the two most common versions of LISP are Scheme and Common LISP. Scheme has been used in introductory computer science courses, but its use has declined in recent years. Haskell, ML, and CAML are other functional programming languages sometimes used in upper- level computer science courses and computer science research.
  • 57.
    BASIC COBOL, like FORTRAN,takes a while to master. For College students, this often meant that a semester or more had to be spent learning programming before anything useful could be done with a computer. At the same time, computers were becoming smaller, less- expensive, and more accessible to the public. Personal computers were still some years away, but by the mid-1960s many colleges and universities had computers that students could use on campus. In 1965, in order to make programming accessible to students on the new “mini-computers” that had begun to appear, two professors at Dartmouth College in Hanover, New Hampshire, John Kemeny and Thomas Kurtz, invented the BASIC programming language. BASIC (Beginner’s All-Purpose Symbolic Instruction Code) was an interpreter-based language rather than a
  • 58.
    compiled language likeFORTRAN or COBOL. It was designed to be easy to learn and easy to use. ;;; sample Lisp function ;;; from The University of Michigan Language Guide ;;; This function, given a specific degree in Farhrenheit, ;;; presents the user with equivalent Celsius degree. (defun convert () (format t "Enter Fahrenheit ") (LET (fahr) (SETQ fahr (read fahr)) (APPEND '(celsisus is) (*(- fahr 32)(/ 5 9)) ) ) ) 10 REM BASIC SAMPLE CODE BY C. HERBERT 20 REM 1 TO 100 GUESSING GAME 30 LET X = INT(RND * 99 + 1)
  • 59.
    30 PRINT “IAM THINKING OF A NUMBER FROM 1 TO 100.” 40 PRINT “TRY TO GUESS WHAT IT IS.’ 50 PRINT “YOUR GUESS” 60 INPUT G 70 IF G = X THEN GOTO 200 100 IF G < X THEN PRINT “LOWER” 110 ELSE PRINT “HIGHER” 120 PRINT “TRY AGAIN” 130 PRINT 140 GOTO 50 200 PRINT “CORRECT” Figure 10 – Lisp Figure 11 – BASIC JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 22 BASIC caught on quickly. When personal computers began to appear in the late 1970s almost every
  • 60.
    machine was equippedwith a BASIC interpreter, so, at the time, more people learned BASIC than any other language. Over the years there have been many versions of BASIC, including GW-BASIC, Quick BASIC, True BASIC, and Visual Basic, just to name a few. Today the most common version of Basic is Microsoft’s Visual Basic.NET (VB.NET), which appears to be declining in popularity and professional use. The newest version of Visual Basic is part of Microsoft’s Visual Studio 2013. Pascal BASIC and FORTRAN both had a GOTO command, which is sometimes referred to as an unconditional branching command. Each line in a BASIC or FORTRAN program was numbered, and at any point in the program the GOTO instruction could suddenly re-direct the flow of control to a line number in another part of the program. The command was intended to let users set up
  • 61.
    branching and looping,but it was so flexible to use that programmers often ended up with poorly designed logic that jumped repeatedly back and forth throughout the code, leading to what was referred to as spaghetti code. People other than the original programmer often had to spend hours trying to figure out how such a program worked. In response to this problem, Swiss computer scientist Niklaus Wirth released the Pascal programming language in 1970. He named the language after the seventeenth century French Mathematician and Philosopher, Blaise Pascal, one of the first people to ever build a working mechanical calculator. Wirth’s Pascal was widely used as a teaching language and for prototyping - designing algorithms in one language for implementation
  • 62.
    in another. in thelate 1970s and 1980s. It was based on concepts from Algol, but had built-in commands for looping and branching that forced the user to write programs according to good principles of structured logical design. In Pascal, it became natural for programmers to code with a logical flow of instructions and (* Pascal sample code by C. Herbert *) (* 1 to 100 guessing game *) program Guess; begin var pick: integer = random(100); guess: integer; writeln('I am thinking of a number from 1 to 100.’); writeln('Try to guess what it is.’); repeat writeln();
  • 63.
    writeln(‘Your guess?); readln(guess); if guess> pick begin writeln(‘Lower.’); writeln(‘Try again.’); end else begin writeln(‘Higher.’); writeln(‘Try again.’); end until pick = guess; writeln(‘correct’) end. Figure 12 – Pascal JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg.
  • 64.
    23 almost impossible forthem to end up with spaghetti code as they did in BASIC. Pascal was a simple interpreter-based language that was easy to learn and use. Pascal code could also be compiled for production of commercial software. It did see some professional use, particularly by Apple from 1978 into the mid1980s, but was never on a par with FORTRAN, COBOL, or newly emerging object-oriented languages. Niklaus Wirth went on to develop Modula and Modula 2, languages designed around the concept of modular programming, and Oberon, a true object-oriented language. The C Programming Language The C programming language was developed at Bell Labs by Dennis Ritchie for use as a systems programming language. C is a simple high-level language that incorporates many of the Algol features, but it has a fairly simple compiler, and uses a small amount of memory compared to more complex languages. This provides C with two advantages: first, it is relatively easy for a
  • 65.
    team of goodassembly language programmers to build a C compiler quickly, and second, the language can run in a small amount of memory, such as on small embedded processors. C is often the first language high-level language developed for a new processor, and is often used for developing system software, such as parts of operating systems, device drivers, and compilers and interpreters for other languages. It was used to write the original Unix operating system, and has been closely linked with Unix and Linux systems. C is also an important language on which many more advanced languages are based, such as C++, Java, and Python. There is a direct connection from Algol through C to many modern languages. In 1978, The C Programming Language, a book by Brian Kernighan and Dennis Ritchie, appeared on the market. 6 It was the definitive book on C programming with a very simple straightforward style teaching experienced programmers how to use the language. It became one of the most widely read and
  • 66.
    influential programming booksof all time. Many C compilers were written using specifications based on K&R, as the book is called. In 1989 ANSI adopted a standard for the C programming language, which became the ISO standard the following year. ANSI C, ISO C, C 89 and C 90 are all fundamentally the same language. ISO revisions of the C standard appeared in 1994, 1999 and 2011. Today many people write C code using a C++ compiler, as C is a subset of the newer, object-oriented C++. 6 Kernighan, Brian W.; Ritchie, Dennis M. (February 1978). The C Programming Language (1st edition.). Englewood Cliffs, NJ: Prentice Hall. ISBN 0-13-110163-3. Figure 13. The C Programming Language by Kernighan and Ritchie. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 24 Simula and Smalltalk
  • 67.
    In the 1960stwo Norwegian computer scientists, Kristen Nygaard and Ole-Johan Dahl, developed a language for programming discrete event simulations, which they called Simula. A discrete event simulation simulates a system in which distinct events change the state of a system. It differs from a continuous real-time simulation in which variables are constantly changing. For example, a game of American football could be viewed as a discrete event simulation if we only see the results of each play and not the plays themselves. The state of the system could include which team has the ball, on what yard line, what down it is, how far to go for a first down, and the score. Each play could be considered a discrete event that changes the state of the system. The defense picks a formation, the offense picks a play, and the simulation shows the result. Many games and real world processes can be viewed in this way. Most discrete event simulations in business and industry are much more complicated, such as modeling a manufacturing process or a transportation system. Nygaard and Dahl needed a programming language to simulate discrete systems and interactions between multiple systems. They came up with an Algol-based
  • 68.
    language that hadobjects with properties, along with distinct methods to manipulate those properties – the basis for modern object oriented programming. Objects communicated with each other by passing messages back and forth to each other. The language was defined by the International Federation for Information Processing in 1967 as Simula 67. Simula was a language for a very specific purpose, but the ideas in Simula inspired others. At the Xerox Palo Alto Research Center in California, computer scientists led by Alan Kay developed the Smalltalk programming language, which was highly influenced by the innovations in Simula. Smalltalk, released in 1980,
  • 69.
    is a trueobject-oriented programming language in which every bit of data and every method must be part of an object. Objects communicate with each other only through message passing between objects. The properties of each object are fully encapsulated, meaning that no object can see the properties of another object except through messages from that object. “Smalltalk example from Clemson University” “Prof. Joe Turner, 1998” ApplicationModel subclass: #TalkInterface instanceVariableNames: 'talk message ' classVariableNames: '' poolDictionaries: '' category: 'UIApplications-New'! !TalkInterface methodsFor: 'initialization'!
  • 70.
    initialize "Initialize an interfaceinstance." talk := TalkBox new! ! !TalkInterface methodsFor: 'actions'! goodbye "Action when the Goodbye button is selected." message value: talk goodbye! hello "Action when the Hello button is selected." message value: talk hello! ! Figure 14 – Smalltalk JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 25 After several years of research, Smalltalk-80 was released in 1980. ANSI Smalltalk (1998), Apple Smalltalk, Squeak, and VisualWorks are just a few of the many versions of Smalltalk. Smalltalk is rarely
  • 71.
    used for modernproduction programming compared to languages like Java, and C++. C++ The C++ programming language is a revision of C influenced by Simula and Smalltalk. (The name C++, comes from the fact that the ++ operator indicates iteration in the C language.) C++ is an object- oriented language in the sense that it can be used to implement objects and message passing, but it does not require that programmers use objects and message passing. In fact, the C language is a subset of C++ and many C programs will work with a C++ compiler with little or no change.
  • 72.
    C++ was developedat Bell labs by Dr. Bjarne Stroustrup, a Danish- born computer scientist with a PhD. in Computer Science from Cambridge University. He merged the object features from Smalltalk into the C programming language to create a language that was practical and versatile like C, but that could support object- oriented development. Dr. Stroustrup viewed C++ as a good tool for developing large software systems. C++ was released in 1983. ISO standards for C++ were released in 1998 and revised in 2003, 2007 and 2011. Today C++ is among the most widely used programming languages, and has spawned several spinoffs,such as C#, and Objective C. Many game development systems use a programming language
  • 73.
    based on C++.Java syntax was based on on C++. // C++ program to display a pattern of stars on the screen // CIS 106 - Spring 2012 #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int size = 3; int row; int column; int space = size*2; for(row = 1 ; row <= size ; row++) { for(column = 1 ; column < space ; column++) { printf(" "); } for(column = 1 ; column <= 2 * row - 1 ; column++) { printf("*"); } space--; printf("n"); } system("PAUSE"); return EXIT_SUCCESS;
  • 74.
    } Figure 15 –C / C++ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 26 Perl Perl was developed by Larry Wall in 1987 as a language for extracting data and creating reports on Unix computers. The language was well suited to preforming similar tasks for Web and Network programming and increased in popularity with the rise of the Internet. Perl is also well-suited for tying together applications and for writing very short (often online) scripts for Unix and Linux systems administrators. Perl scripts are sometimes used by systems administrators when installing software. Wall originally named the language Pearl after
  • 75.
    “the pearl ofgreat price”, mentioned in the Bible’s book of Matthew. He changed it to Perl when he found that an older obscure language named Pearl existed. Today some people say the Perl stands for Program Extraction and Reporting Language. Perl 5 has been around since 1994. The most recent version, released in May 2014, is Perl 5.20. Perl 6 has been developed as a different language related to Perl 5. Both are freely available software. For more about Perl 5, see: http://www.perl.org For more about Perl 6, see: http://perl6.org C# (C Sharp) C# was developed as a proprietary part of Microsoft’s .NET Framework. Anders Hejlsberg was the lead developer. The C# programming language was released by Microsoft following their failed attempt to implement the J++ language, a version of the Java programming language.
  • 76.
    From its inception,Java was intended to be a freely available language for use on any computer system. Sun Microsystems (and later Oracle) allowed others companies to develop their own Java compilers and software development systems, provided they agreed to make their versions of Java conform to Sun’s standards for Java compatibility. Microsoft developed a version of Java under such a license, but began to add proprietary features to their “J++” language, which Sun believed to be in violation of the agreement. Following a lawsuit filed against Microsoft by Sun, J++ development was halted. The last available version was discontinued in 2001. # Perl script to send an email message # from http://learn.perl.org/examples/email.html #!/usr/bin/perl use strict; use warnings; # first, create your message use Email::MIME;
  • 77.
    my $message =Email::MIME->create( header_str => [ From => '[email protected]', To => '[email protected]', Subject => 'Happy birthday!', ], attributes => { encoding => 'quoted-printable', charset => 'ISO-8859-1', }, body_str => "Happy birthday to you!n", ); # send the message use Email::Sender::Simple qw(sendmail); sendmail($message); Figure 16 – Perl http://www.perl.org/ http://perl6.org/
  • 78.
    JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 27 Microsoft subsequently released J#, which was also discontinued and does not work with any version of the.NET framework beyond .NET Studio 2005. The Sun-Microsoft lawsuit resulted in the release of internal Microsoft documents revealing what they referred to as an “embrace-extend- exterminate” corporate strategy. Microsoft planned to adopt industry standards, co-opt the standards by extending them to include Microsoft-only features linked to their operating systems, then attempt to drive their competitors from the market by not letting other companies use the new features7. C# was released by Microsoft during their legal battle with Sun. Despite its name, many people believe it is closer to Java than to C++, although over the years the two languages have developed in different directions. In the article “Why Microsoft’s C# Isn’t” in a January 2002 edition of CNET News, James Gosling was asked about his reaction to C#. He replied: "The trite answer is, 'Imitation is the sincerest form of flattery…But the other answer is, 'You guys
  • 79.
    (at Microsoft) stilldon't get it,' because it's sort of Java with reliability, productivity and security deleted… They had this problem in their design rules that they had to support C and C++, which means you have to have a memory model where you can access everything at all times. It's the existence of those loopholes that is the source of security, reliability and productivity problems for developers.” 8 C# has replaced VB.NET as the most popular programming language for the.NET environment. Microsoft C# is a proprietary closed source language, meaning the source code is not available. The ISO released a C# standard in 2003, and a revision to the standard in 2006. To date, a few open source C# compilers exist, but none are full implementations of C#. Microsoft has extended its version of C# to include features not in the ISO standard. Objective C and Swift Objective C was originally developed by Brad Cox and Tom Love at Productivity Products International (later renamed StepStone) in the early 1980s – roughly the same time the C++ language was released.
  • 80.
    Like C++, ObjectiveC was intended to add Smalltalk-like objects to C programming. The language was not widely used until it was adopted by Apple as the language of choice for iPhone and iPad programming. The NeXT computer company (founded by Steve Jobs) acquired the rights to Objective C from StepStone in 1995. In 1996 Apple bought the Next company and Jobs returned to Apple. The Objective C language became available for the Mac OS X operating system and later became the preferred language for the iOS operating system used on iPhones and iPads. C is a subset of Objective C, just as it is with C++. The object- oriented nature of the language is actually closer to the original Smalltalk than to C++. Objective C syntax is different from the C++/Java syntax. 7 See the ZDNets Newsletter, Nov 9, 1998, available online at: http://www.zdnet.com/news/intel-exec-ms-wanted-to-extend- embrace-and-extinguish-competition/100925 8 available on the Web at: http://news.cnet.com/2100-1082- 817522.html http://news.cnet.com/2100-1082-817522.html
  • 81.
    JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 28 For example, methods are not called from other methods in Objective C, they are invoked by message passing. There are many other differences between the two languages and how they are used, but they are best understood by experienced programmers. Basic logic and control – branching, looping, and so on – is similar to the Algol-derived syntax in C, C++, and Java. The primary difference between Objective C and Java is in their target systems: Java is a cross platform language for programming devices on large heterogeneous networks, while Objective C is used almost exclusively for programming OS X and iOS devices, especially iPhones and iPads. At Apple’s 2014 Word Wide Developer’s Conference, the company introduced a new language called Swift, and announced that Objective C would be replaced by Swift. Apple Vice President Craig Federighi referred to Swift as “Objective C without the C”.9 Python The Python programming language was developed by Guido van Rossum, a Dutch-born computer
  • 82.
    scientist who nowlives in the United States. He began developing Python as a scripting language to replace ABC, an earlier teaching and prototyping language he had helped develop. Van Rossum said that he choose the name Python because he is a big fan of Monty Python's Flying Circus and he was in an irreverent mood at the time. 9 See Venture Beat News, June 5, 2014. Online at: http://venturebeat.com/2014/06/02/apple-introduces-a-new- programming- language-swift-objective-c-without-the-c/ // part of a tic tac toe game written in Swift // from https://developer.apple.com/wwdc/resources/sample- code/ unc placedPiece(x : Int, y : Int) -> Bool { let piece = board.pieceAt(x, y: y) if piece.isOpen { if whoseTurnIsIt == 1 { piece?.playerOwner = player1 }
  • 83.
    else { piece?.playerOwner =player2 } viewController.collectionView.reloadItemsAtIndexPaths([NSIn dexPath(forRow: x, inSection: y)]) nextTurn() return true } return false } Figure 17 – Swift JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 29 Van Rossum succinctly described Python in an article titled: “What is Python? Executive Summary” on the Web at https://www.python.org/doc/essays/blurb : “Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic
  • 84.
    typing and dynamicbinding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.” # mySQLconnectDemo.py # mySQL database remote connection and query example # last edited Dec 8, 2014 by C. Herbert import mysql.connector # connection information # host IP address: 68.178.216.151 # database: CWHDemo # username: student # password: Student%123 (Note capital "S" in password,
  • 85.
    but not inusername. # set up a configuration list as a python dictionary config = { 'user': 'student', 'password': 'Student%123', 'host': '68.178.216.151', 'database': 'CWHDemo', } # connect to the database and create a cursorf cnx = mysql.connector.connect(**config) cur = cnx.cursor() # execute a query to display all pets queryString = "SELECT * FROM pet ORDER BY name;"; print queryString, "n" cur.execute(queryString) rs = cur.fetchall()
  • 86.
    print "%-12s%-12s%-12s "% ("Name", "Owner", "Species") print"************************************************ *************" for row in rs: print "%-12s%-12s%-12s " % (row[0], row[1], row[2]) print"************************************************ *************" cnx.close() Figure 18 – Python https://www.python.org/doc/essays/blurb JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 30 Van Rossum designed a language that was easy to read, east to write and easy to debug, with exception handling built into the Python interpreter. Exceptions are objects that are created detailing what happens when a computer program doesn’t run properly. Exception handling is a major topic in Java programming which you will learn more about later. Python programs are easy to create and run, but Python programs are slower than programs written in
  • 87.
    major production languageslike Java because they are interpreted. In a 1997 comparison of Java and Python, Van Rossum wrote that “Python programs are generally expected to run slower than Java programs, but they also take much less time to develop. Python programs are typically 3-5 times shorter than equivalent Java programs.” 10 Remember, interpreted programs must be translated line by line each time the program runs, making them slower than compiled programs whose translated version of a program is ready to run. Java adds the JVM step for portability, but it is still significantly faster than interpreted software. Van Rossum suggests that Java and Python complement each other well, with Python suited to prototyping software designs that can be more fully developed as components of large systems using Java. He also suggests that Python is well-suited for a scripting language used for quick, short applications in place of other scripting languages like JavaScript, and as a “glue language” to create short pieces of software that “tie together” components of large systems.
  • 88.
    Python is freeopen source software. For more about Python see the Python Website at: Python.org . JavaScript JavaScript was developed by Netscape and announced by NetScape and Sun Microsystems in 1995: “JavaScript is an easy-to-use object scripting language designed for creating live online applications … JavaScript is designed for use by HTML page authors …it can be used by people with little or no programming experience to quickly construct applications.” 11 JavaScript is implemented as an interpreted language built into Web browsers. Short quick programs add interactivity and other feature to Web pages through HTML code that includes JavaScript. All version of Microsoft Internet Explorer since 1996 include support for JavaScript, as do the Chrome, Firefox, Safari, and Opera browsers. Bredan Eich, one of the cofounders of the Mozilla project, developed the original version of JavaScript for use in the Netscape Navigator Web browser – viewed by many as the “grandfather” of most modern Web browsers.
  • 89.
    10 Comparing Pythonto Other Languages, a blog entry available on the Web at: https://www.python.org/doc/essays/comparisons 11 The original 1995 press release from NetScape and Sun is available on the Web at https://web.archive.org/web/20070916144913/http://wp.netscap e.com/newsref/pr/newsrelease67.html http://www.python.org/ https://www.python.org/doc/essays/comparisons https://web.archive.org/web/20070916144913/http:/wp.netscape. com/newsref/pr/newsrelease67.html JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 31 ECMA International (formerly the European Computer Manufacturers Association ) developed a standard for Web scripting languages based on JavaScript. Today JavaScript, JScript, ActionScript and several other Web and network scripting languages are all considered implementations of the ECMAScript Standard, which was adopt by the ISO in 1997 and updated in 1999, 2009 and 2011. JavaScript and other ECMAScript languages have a structured syntax similar to C (which is similar to Java and can be traced back to Algol) for branching, looping and
  • 90.
    simple arithmetic. JavaScriptcan be called object-based, but it does not require or support true object- oriented programming like Java. In practice, JavaScript software is usually limited to simple programs that add features such as interactivity and the ability to perform calculations in HTML web pages. As its name indicates, it can be thought of as Java- light, although a number of its feature differ from those in Java. To learn more about JavaScript, see the W3 Schools Java Tutorial, on the Web at: http://www.w3schools.com/js (w3schools.com has introductory tutorials for many other scripting languages used for Web development.) The Website www.Javascriptsource.com has an extensive “cut and paste” repository of freely available JavaScript programs that can be used in Web page development. PHP PHP is a freely available server-side scripting language primarily used for applications involving HTML Web pages. The language was originally developed as Personal Home Page Tools (PHP Tools) and Personal Home Page Forms Interpreter (PHP FI) by Rasmus Lerdorf, a Canadian Computer Software
  • 91.
    engineer from Greenlandwho had contributed to the development of the Apache server software. He has said he created the PHP interpreter for his own use to process HTML Web forms and communicate with databases. The source code for the language was freely released to the public in 199512. in 1997, two students from Tel Aviv University, Andi Gutmans and Zeev Suraski, began working with Lerdorf to turn PHP into a more useful programming language. PHP 3.0, the first version of PHP similar to the current language, was released in 1998 and gained some popularity as a scripting language for Web development as the Internet began to grow. PHP is now maintained by The PHP Group as a general-purpose scripting language that is still used primarily for Web development. According to the group, the name PHP now stands for “PHP Hypertext Preprocessor”. The most recent version of PHP is PHP 5. There are some issues that have prevented PHP from being more widely used as a general purpose scripting language. There is no ISO standard for PHP and the licensing agreement, though free and open- source, has some restrictions on the use of the name PHP or
  • 92.
    names derived fromPHP13. PHP does not fully support ISO’s Unicode standard for the encoding of character data, as most languages do. 12 See the history of PHP online at; http://php.net/manual/en/history.php.php 13 See: http://php.net/license http://www.w3schools.com/js http://www.javascriptsource.com/ http://php.net/manual/en/history.php.php http://php.net/license JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 32 In 2013 Google reported that its Safe Browsing Service had found malware in versions of the PHP source code being distributed to the public. The PHP group locked down its site, moved to new servers, and applied for a new security certificate. Despite these issues, several million Web developers continue to use PHP as a scripting language for Web development. Ruby Ruby was developed by Yukihiro Matsumoto in Japan as a true object-oriented scripting language with
  • 93.
    functional programming capabilities.He said the name came from a colleague’s birthstone14. The first version of Ruby 1.0 was released to the public in 1996. It quickly became very popular for Web scripting in Japan, but was rarely used elsewhere before 2000, when the first English language Ruby documentation became available. The language declined a bit in popularity in 2003 when Ruby 1.8 was released. Ruby 1.8 was incompatible with older versions of the language, and a lot of Ruby applications had to be rewritten. Interest in Ruby began to increase significantly in 2005 when David Heinemeier Hansson, a Danish professional programmer and race car driver, used Ruby to develop the Rails framework for Web scripting that was especially well suited to mapping data from relational database tables to HTML Web pages. Apple included it with its OS X operating system in 2007. Since then, the language and the Ruby on Rails framework have steadily been increasing in popularity internationally. 14 An Interview with the Creator of Ruby, from the LInuxDevCenter Website, online at: http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.ht
  • 94.
    ml <!—PHP/HTML page visitcounter (using cookies) from: http://www.java2s.com/Code/Php/ <?php if (!isset($_COOKIE['visits'])) $_COOKIE['visits'] = 0; $visits = $_COOKIE['visits'] + 1; setcookie('visits',$visits,time()+3600*24*365); ?> <html> <head> <title> Title </title> </head> <body> <?php if ($visits > 1) { echo("This is visit number $visits."); } else { // First visit echo('Welcome to my Website! Click here for a tour!');
  • 95.
    } ?> </body> </html> Figure 19 –PHP http://www.java2s.com/Code/Php/ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 33 The ISO issued a standard for the Ruby language in 2012. Ruby and Ruby on Rails are both freely available. The most recent version of Ruby, Ruby 2.1 was released by The Ruby Community late in 2013. There are several versions of Ruby in use today, such as JRuby which utilizes the Java Virtual Machine for cross-platform programming, MacRuby for Apple’s OS X operating system, IronRuby for the Microsoft .NET environment, and mruby – a light version of Ruby for Web applications. For more about Ruby see the official Ruby Website at: https://www.ruby-lang.org CheckPoint 1.3 1. What is the difference between machine code and assembly
  • 96.
    language? 2. What isthe difference between a compiler and an interpreter? 3. What is Java bytecode and how is it related to what IBM has called “the Java advantage”? 4. What is functional programming and what is most functional programming based on? 5. List and describe the importance of several historical programming languages and several programming languages currently in use. # mySQLconnectDemo.rb # Ruby mySQL connection and query example # last edited Dec 16, 2014 by C. Herbert require "mysql" begin con = Mysql.new '68.178.216.151', 'student', 'Student%123', 'CWHDemo' # execute a query to display all pets queryString = "SELECT * FROM pet ORDER BY name;"
  • 97.
    puts queryString rs =con.query(queryString) n_rows = rs.num_rows puts "There are #{n_rows} rows in the result set." n_rows.times do puts rs.fetch_row.join("s") end rescue Mysql::Error => e puts e.errno puts e.error ensure con.close if con end Figure 20 – Ruby https://www.ruby-lang.org/
  • 98.
    JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 34 Lesson 1.4 The Java Programming Language History and Development of the Java Language The Java programming language was developed by a team at Sun Microsystems led by chief developer James Gosling. (Sun was acquired by Oracle Corporation in 2010.) Sun started the development of Java in the early 1990s as a language for multimedia programming, but as the language developed, the internet blossomed – in particular the World Wide Web portion of the Internet. Quoting from Gosling’s early description of Java15: “The design requirements of the Java programming language are driven by the nature of the computing environments in which software must be deployed. …To live in the world of electronic commerce and distribution, Java technology must enable the development of secure, high performance, and highly robust applications on multiple platforms in heterogeneous, distributed networks.”
  • 99.
    A heterogeneous networkis a network that connects computers with different hardware and different operating systems. A distributed network is a network of computer equipment that connects many machines with CPU’s of their own, rather than connecting many devices to one CPU. The Internet is a heterogeneous, distributed network; in fact, it the most heterogeneous and most distributed network of all time. As the Internet grew, so did the use of Java, which was perfectly suited for Web-based programming. Sun was interested in developing a language in which applications could be created and distributed across many different computers, not just for one computer or one family of computers. Java’s built-in networking and security, distributed approach to computing, and multimedia capabilities fit in very well with the rise of the World Wide Web, and Java quickly became the language of choice for the development and delivery of software using the Internet. Today, more devices connected to the internet use Java than all other programming languages combined. There are more Java Runtime
  • 100.
    Environments installed oncomputers, tablets and smartphones – and embedded in kitchen appliances, automobiles, industrial equipment and other systems – than all Android, Windows and iOS systems combined16. Sun Microsystems was acquired by Oracle Corporation in 2010. Oracle has continued to make Java freely available to the public. They have continued to update the language through the Java Community Process, a mechanism for proposing changes to Java. (see www.jcp.org.) Major changes in the language result in a new version of the language. Minor changes to the java compiler and related software result in a new release of the most current version of the language. The most recent version of Java is Java 8, released in 2014. As of January 2015, the most recent edition of Java is Java 8, release 25. 15 Design Goals of the Java TM Programming Language from The Java Language Environment by James Gosling and henry McGilton, May, 1996 Available online at: http://www.oracle.com/technetwork/Java/intro-141325.html 16 Learn About Java Technology, an oracle publication, online at http://www.Java.com/en/about http://www.jcp.org/
  • 101.
    http://www.oracle.com/technetwork/Java/intro-141325.html http://www.java.com/en/about JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 35 The syntax of the Java language was based on C++, the most popular programming language at the time Java was introduced, so it would be familiar to programmers. Therefore, it can be traced back to Algol through C++ and C. Unlike C++, it requires all programs to be methods in objects, so it is a true object- oriented language. It has features limiting the use of low level system calls that can introduce security hazards in languages such as C and C++. We will learn more about the nature and history of Java while we learn to use Java as a tool for the development of software applications. A Look at Java Source Code Every Java program requires at least one class of objects to get things started. New programming projects in Java often have a class for the project itself, with the project’s startup code in a main method in the project’s class. This is what we will do in the first part of CSCI 111.
  • 102.
    Here is anexample of code from a Java programming project, showing the parts of the project: /* * CSCI 111 Spring 2015 * This application converts feet to yards and meter * and displays a table of the values for 1,000 to 10,000 yards */ package feetyardsmeters; public class FeetYardsMeters { // method prints a table from 1k to 10k yds. public static void main(String[] args) { double yards; // value in yards double feet; // value in feet double meters; // value in meters // print column headers -- t is the tab character System.out.println("yardstfeettmeters");
  • 103.
    // loop toprint the data in rows and columns for( yards = 1000; yards <= 10000; yards = yards + 1000) { feet = yards * 3; meters = yards * 0.9144; System.out.println(yards + "t" + feet + "t" + meters); } // end for } // end main } // end class FeetYardsMeters The code starts with a comment identifying the project and the programmer. Comments do not affect how the code runs. block comment package directive class declaration one line
  • 104.
    comment method header one linecomment body of the method comment variable declarations comment Figure 21 – Java sample JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 36 A package directive identifies a Netbeans (or Eclipse) programming package, then the class declaration marks the beginning of the class. The class name for the package’s class will be the same as the package name. In CSCI 111, Netbeans will set these up for you when you start a project. The code above has a header at the start of the main method: public static void main(String[] args)
  • 105.
    The words public,static and void are modifiers that describe how the method will work. You will learn more about them as you learn Java. The name of the methods is main, followed by parameters for the method in parenthesis. The parameter (String[] args) is a default argument for a package’s main method. When you start a new project in NetBeans, you only need to specify the project’s name. The rest of the items in the method header will be generated by NetBeans for you. The actual code to make things work is inside the main method. Notice that braces { } mark the beginning and end of a block of code. In this case there are braces for the class, for the main method, and for the block of code in thefor loop inside the main method. As with everything else in this example, you will learn more about how to use braces as you learn Java. The actual code is rather short. First, three double precision floating point variables are named (yards, feet and meters), then the program prints a header for a table of values, followed by a loop to print the data in the table.
  • 106.
    Why Java? Here isthe same program as the Java project above, but written in the Python programming language: ''' CSCI 111 Spring 2015 (Python script) This application converts feet to yards and meter and displays a table of the values for 1,000 to 10,000 yards ''' # print the table’s heading print "yardstfeettmeterst" # print the table’s data for yards in range(1000,10000, 1000): print yards, "t", yards*3, "t", yards*0.9144 The python code looks so much easier! No package directives or class declarations, no braces, no method header, etc. are needed for this simple algorithm. If that’s the case, then why bother with all of the kerfuffle of Java? block comment
  • 107.
    one line comment Figure22 – Python sample JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 37 The answer lies in the purpose of CSCI 111. One of the main goals of CSCI 111, CSCI 112, and CSCI 211 is to help students prepare to become professional software developers. Java is a very sophisticated software development tool, which may seem like overkill for the introductory topics a new programmer needs to learn, but we chose Java because of its market dominance, its usefulness for large software development projects, and the fact that the language and techniques of object-oriented programming in Java are easily transferable to many other languages. Python allows you to quickly and easily create code for simple tasks. However, the resulting software runs inefficiently and is not secure enough for things like banking or medical systems. It is not as easily used across different platforms as Java is. For these reasons and a variety of other reasons, Python, and
  • 108.
    several other scriptinglanguages, are not well-suited for large scale software development. Python is very useful – indeed, just about anything that can be done in Java can be done in Python. It is great for writing short bits of code, such as a Cisco script to initialize a network router. It can be used to prototype or test the design of large software systems, and is often used as a glue language to quickly and easily tie together large software modules created in other languages. Yet most large scale professional software development is done with Java and a few similar languages. But what about Java compared to languages like C++, or C#? Do you remember the Java advantage discussed earlier in the chapter? A Java compiler first translates Java source code into Java bytecode, which can be stored and moved from one platform to another as Java .class files. To run Java, a machine only needs a Java Runtime Environment (JRE) with a JVM that translates and runs the Java bytecode as machine code for the host platform. The JVM’s rapid translation from bytecode to machine code provides high performance. The use of bytecode, combined with the widespread availability of JVMs for almost all
  • 109.
    processors, makes Javasoftware very portable. In fact, as of January, 2014 Oracle states that: “Java technology is already present in today’s embedded systems, in 5 billion SIMs and Smart Cards, 3 billion mobile handsets, 80 million TV devices, including every Blu-ray player shipped, and many other embedded solutions from printers and bank machines to e- book readers and cars.” 17 One reason for Java’s widespread use is the availability of many Java Application Programming Interfaces, the most common of which are included as part of the JRE. An Application Programming Interface (API) is a software library with classes and methods that extend a programming language for a specific purpose, such as for graphics, sound, database connectivity, or network security. Java has one of the most extensive set of APIs of any programming language. We will use some Java APIs in CSCI 111, but more extensive coverage of Java APIs is included in CSCI 112. For these reasons, and for others beyond the scope of this course, Java is the language of choice in Computer Science courses at Community College of Philadelphia.
  • 110.
    17 See: http://www.oracle.com/technetwork/topics/newtojava/document ation/faqs-jsp-142592.html JLK Chapter1 – Introduction DRAFT January 2015 Edition pg. 38 Versions of Java A Java Development Kit (JDK) contains the tools needed to develop Java software, including a Java language compiler, a Java Runtime Environment with a JVM, and commonly used APIs. There are three main versions of Java Development Kits: 18 – Java SE lets its users develop and deploy Java applications on desktops and servers, as well as embedded environments. It is the core JDK. – Java EE is, according to Oracle, the industry standard for building large-scale web and enterprise applications. – Java ME is a development environment for building applications for mobile and embedded systems. Java ME is augmented by
  • 111.
    other development packagesfor embedded processors, such as Java ME Embedded and the Java SE Embedded Suite. In addition, there are several specialized add-ons to these development kits, such as: – an advanced Java user interface (UI) platform for building multimedia enterprise business applications – Java Card technology enables development of applications that run on smart cards with very limited memory and processing capabilities. Multiple applications can be deployed on a single card, and new ones can be added even after the card has been issued. – Java TV enables development of applications that run on TV and set top box devices: such as Electronic Program Guides (EPG's), Video-on- Demand (VOD), games and educational applications. it can access bonus content on most Blu-ray Disc titles. – Java DB is Oracle's supported distribution of the Apache Derby open source database. It supports standard ISO standard SQL.
  • 112.
    CheckPoint 1.4 1. Whodeveloped the Java programing language, and for what purpose? 2. Who owns the Java language and how do they update it? 3. Where is the startup code for a new java programming project placed? 4. Why is Java used in CSCI 111 instead of a simpler and easier to learn language, such as Python, or instead of other production languages, such as C++ or C#? 5. How is Python used by Java software developers? 18 From the Get Started section of Oracle’s New to Java Website, at: http://www.oracle.com/technetwork/topics/newtojava http://www.oracle.com/technetwork/topics/newtojava JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 39 Lab 1 – Getting Started with NetBeans and Java In this step-by-step exercise we will learn to create a simple Java program using the NetBeans IDE. This lesson is similar to the NetBeans IDE Java QuickStart Tutorial which can be found online at:
  • 113.
    https://NetBeans.org/kb/docs/Java/quickstart.html This exercise alsoincludes information about: e source code in a new Java project, Computer Science 111. You should download and install Java and NetBeans before starting this exercise. Appendix A contains instructions for downloading and installing the software at home. This exercise uses the most recently available versions of the software as of January 2015: Java SE Development Kit 8 update 25 and NetBeans 8.0.2 Java SE Development Kit 8 update 11 with NetBeans 8.0, are installed in the labs and classrooms at Community College of Philadelphia. This exercise works with these versions of the software. It should also work with any newer releases of Jav 8 or NetBeans 8. Check with your instructor if you have any questions about which version of Java to use.
  • 114.
    Hello World! We willcreate a simple program that displays the message “Hello World!” – traditionally the first program students learn to write in a new programming language. Hello World appeared in A Tutorial for the B Programming language written by Brian Kernighan at Bell labs in 1972. In 1978, his Hello World program became famous as the first program in the Kernighan and Ritchie book, The C Programming Language. It has since become a custom for programmers to try the Hello World program as the first program with a new compiler, or when learning a new programming language. The Hello World program is available in over 300 different programming languages online at several Websites, such as: http://www.mycplus.com/featured-articles/hello-world- programs-in-300-programming-languages Hello World is among the simplest of programs, but we will create it inside a NetBeans project. So, first we will open a new NetBeans project. The layout of the NetBeans IDE depends on the type of project. We will create a simple Java console application, which means our “Hello World!” message will be
  • 115.
    displayed in asimple system console window within the IDE. The system console is a combination of the system’s standard input and output devices – usually the keyboard and display screen. https://netbeans.org/kb/docs/java/quickstart.html http://www.mycplus.com/featured-articles/hello-world- programs-in-300-programming-languages JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 40 Figure 22 shows the console output as it appears when we run the program in NetBeans. The output – in this case simply “Hello World” – appears between the run message and the Build Successful message. The steps below will show you how to create a Java Hello World program with console output using NetBeans. Our reference for Java-related terminology will be the Java Language Specification (JLS).19 Creating a New Java Project – Step-by-Step STEP 1.
  • 116.
    Start your computerand run the NetBeans software by using the NetBeans desktop icon or finding NetBeans on your system. NetBeans will take a moment to start, then you should see either a blank Netbeans IDE or the IDE with the Learn & Discover startup screen, as shown below. If you wish, you can deselect the checkbox in the upper-right corner of the startup screen to stop showing the screen when the IDE starts. You can bring back the startup screen by choosing Reset Windows from the NetBeans Windows drop-down menu. 19 The Java Language Specification, (JLS) is online at: http://docs.oracle.com/Javase/specs Figure 23. Hello World! as NetBeans Console output. Figure 24 – NetBeans Startup Screen http://docs.oracle.com/javase/specs JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg.
  • 117.
    41 STEP 2. Select NewProject from the File menu. According to the NetBeans documentation, “A project is a group of source files and the settings with which you build, run, and debug those source files. In the IDE, all Java development has to take place within a project.” The NetBeans New Project wizard will open, as shown in Figure 26. The wizard’s Choose Project window has a Categories section on the left and a Projects section on the right. They are used to tell NetBeans the type of project for which it should configure the IDE. Figure 25 – Blank NetBeans IDE Figure 26 – Choose Project Type
  • 118.
    JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 42 STEP 3. Select Java in the Categories section, then Java Application in the Projects section to configure the IDE for a standard Java application, then Click the [Next] button to continue. Almost all programming assignments in CSCI 111 will be standard Java applications. A New Java Application window will appear as shown in Figure 27. The window has text boxes to enter the project’s name and storage location. STEP 4. Type HelloWorld in the Project Name field. It should be in CamelCase, with no spaces. (See the box about CamelCase names on the next page.) Leave the project location and folder as the default. On a Windows system, this will create a new folder for the project in the Netbeans folder under Documents. The wizard also has options to use a dedicated folder for sharing Libraries and to create the application’s main class. We will not use a dedicated folder for libraries in this project. We also should leave the
  • 119.
    main class asthe default, which is based on the project name. Most Java applications require the project, project folder, and the project’s main class to have the same name. Click [Finish] to continue. NetBeans will take a moment to create and open a project configured for editing source code as a Java application. There are three windows open in the NetBeans interface, as shown in Figure 28: ❶the project window, ❷the navigator window, ❸the editor window. Figure 27 – Name and Location JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 43 HelloWorld will be a simple application with only a single source code class, and that class will have only one method. Next, we will look at a description of the source code the wizard generated, then return to our step-by-step exercise.
  • 120.
    CamelCase Names inJava Java programmers customarily use the camelCase naming convention for the names of classes, objects, methods, and other items. CamelCase is the practice of writing compound names without using blank spaces, but capitalizing the first letter of each name that forms the compound name, as in “CamelCase.” If the first letter of the compound name is upper case, then we have upper CamelCase. If the first letter is lower case, then we have lower camelCase. Java class names are usually in upper CamelCase, while the names of instances of a class, properties, methods, and variables are usually in lower camelCase. This is not a requirement that will be enforced by a Java compiler, but is instead a programming convention. Programming conventions are rules that most programmers follow to make the work of one programmer compatible with the work of another, and to make code easier to understand. It is good practice to follow known programming conventions. Sometimes there is a slight variation in the naming convention to aid readability and make the meaning of a name easier to understand, such as a property named
  • 121.
    studentID where theI and D are both capitalized. Oracle, Microsoft, Apple, and many other companies encourage the use of CamelCase names in software development. Quoting from Oracle’s Java Language Basics tutorial “If the [class] name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word.” (See Naming on Oracle’s Java Tutorials page, at: http://docs.oracle.com/Javase/tutorial/Java/nutsandbolts/variabl es.html ) Figure 28 – A new Java project JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 44 Description of the Source Code in a New Java Project The default source code for the new Java Project created by the Java Application Wizard in NetBeans is shown in Figure 29. Take a moment to look it over. Notice that each line in the Editor is conveniently numbered. This is a reference feature of the editor, not part of
  • 122.
    the Java code. Thecode generated by the new project wizard includes: includes: headers and the Java Application Project Wizard Template. (Don’t even think about trying this until you are a more experienced NetBeans and user.) package directive telling the compiler which Java package will contain this software. Each CSCI 111 program will be in its own package. This name is generated by the Java Application Project Wizard Template. Later we will learn about establishing our own packages. the code. We will expand on this later in this exercise. HelloWorld class. The class is a public class, meaning that is can be accessed by software from outside the package. At least one class in each package must be a public class, so that the
  • 123.
    software can berun from the operating system. Figure 29 – default source code JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 45 parameters for the method following on line 18. – the only method in our class. The name of the method is main, with a lowercase m. It is a Java naming convention to start method names with a lowercase letter. A parameter list, in parenthesis, follows the method name in the method header A Parameter is a value that is passed to a method when it runs. For example, if a method finds the sine of X degrees, where X could be any integer, then the value 45 might be passed to the method as a parameter to ask the method to find the sine of 45 degrees.
  • 124.
    A method canhave more than one parameter. Each parameters passed to a method is also called an argument of the method, and the list of parameters in the method header is also called the argument list. The comment on lines 15 through 17 is often used to describe the arguments in the argument list. It is also a good idea to add a comment before a method to describe what the method is intended to do. This method does not use any parameters, although a String array named args is allowed for by the presence of String[] args in the method header, and is referenced by the comment that precedes it. Every Java application project must have at least one class with a main method. This is the place where our application will start. When a Java application is executed, the main method is the first method that will run. In the case of our Hello World application, it is the only method that will run. This will be true for our first few programming exercises in CSCI 111. The keywords public, static and void in the method header are important. public means the method can be run from outside the class.
  • 125.
    class itself, notwith an instance of the class. Only static methods can be run without a reference to a specific instance of an object. We will learn more about this later in the semester. For now, our methods will be static methods. example, a square root method might. We will leave these keywords as is. Every Java application’s main method must be a public static void method. Notice that blocks of code in Java begin and end with braces { block of code }. (Braces are also often called brackets. The Java Language Specification uses the term braces.) This includes classes, methods, and other units of code. The NetBeans wizard places the beginning brace on the same line as the class or method header, then places the ending brace on a line by itself after the last line of the block. The blocks of code should be indented to make the blocks easier to identify. The NetBeans Source Code Editor will indent blocks of code automatically.
  • 126.
    JLK Chapter 1– Introduction DRAFT January 2015 Edition pg. 46 Some of the items in the source code are comments. Comments are notes for programmers reading the source code, but they do not affect the way the program runs. In fact, comments are stripped out of the code as it is compiled. Comments are important. They appear as documentation, helping to make our source code easier to read and understand – for both ourselves and other programmers. Comments can be included in Java source code as in-line comments or block comments. An In-line comment begin with a double slash, like this: //This is an in-line comment. Everything after the double slash is a comment, ignored by the compiler, but everything before the double slash is part of the code, not part of the comment. All of Line 19 in the source code in Figure 29 is an in-line comment. The line below shows how an in-line a comment can be included after a Java instruction: double yards; //This is an in-line comment.
  • 127.
    A block commentbegins with a slash-star and end with a star- slash, like this: /* This is a block comment. It is three lines long. * In this comment, the star-slash is on the third line, * lined up with the beginning slash-star. */ Star refers to the asterisk, on the same key as the number 8 on a QWERTY keyboard. Everything typed between the slash-star marking the beginning of the comment and the star-slash marking the end of the comment – no matter how many lines – is part of the block comment and will be ignored by the compiler. Many programmers line up the stars in the slash-star at the beginning of a block comment and the star- slash at the end. They may also place a star on each line to make it clear that this is part of a comment. The NetBeans Source Code Editor will automatically add a star the beginning of each line in a block comment. Lines 1 through 5 in Figure 29 show this. There are three block comments and a single one line comment in the code that the Java Application
  • 128.
    Project Wizard createdto help get us started. It is really up to you how you format your block comments, as long as they are clear and easy to read. It is a good idea to ask your instructor in a class or check with your employer on the job to see what they would like you to do. Java code must run correctly and efficiently, but the readability of the source code is also very important. Comments and programming style should make the source code easier to read and understand. Sometimes a small touch can make a difference – in this example, line 18 is blank. The separation between the two lines with ending braces makes the code easier to read in a subtle way. Next we will finish our exercise by modifying the code created by the Java Application Wizard to create our Hello World program. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 47 Hello World! – Step-by-Step (continued) STEP 5.
  • 129.
    Modify the commentabove the package directive on lines 1-5 to include the following identifying information instead of the default message: – Hello World Application – created for CSCI 111. Your instructor may also want you to include the semester and section number. – last modified [date and approx. time]. - @author [your name]. @author is a JavaDoc tag, which we will learn about later in the semester. For now, be sure to include the tag in front of your name. STEP 6. Delete the comment on lines 9 through 12. It is no longer needed because of the information in the code’s opening comment. STEP 7.
  • 130.
    Change the commentpreceding the method header to briefly describe what the method does – main method prints a message on the screen. The comment already has a Javadoc parameter tag (@param) identifying the method’s parameters. We will not use these parameters, but they could be used by a more experienced Java user, so we will leave the @param as is. It is also always a good idea to include a brief comment at the beginning of a method to state what the method does (or at least what the programmer thinks it does.). That is what we are doing in this step, resulting in the code shown on the next page. The code in your project should now look something like that in Figure 31. Figure 30 – edited opening comment JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 48 STEP 8.
  • 131.
    Replace the TODO comment on line 16 with the instruction: System.out.println("Hello World!"); This is the actual Java code to be executed. The TODO comment is only a placeholder put there by the NetBeans wizard. Notice that the new line ends in a semicolon. This is necessary in Java. Each individual instruction in a block of code ends in a semicolon in Java. The System.out.println command tells Java to print the character string “Hello World!” on the standard system console output unit. system commands in its library. – to send something to the console output. print by itself, without the ln, would tell Java to print the message then wait on the line for whatever comes next. println tells Java to behave as if [Enter] is pressed after the message, whereas print is similar to typing something without pressing [Enter] at the end of the line. Here we use
  • 132.
    println. s enclose theargument of the command – what is to be printed. – this means we are telling Java to literally print the exact string of characters between the opening and closing quotes – Hello World! Figure 31 – modified Java project Figure 32 – System.out.println JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 49 STEP 9. Add an in-line comment after the ending brace on line 17 – // end main(). This makes it clear that the brace is for the end of the main method. It doesn’t seem like a big deal for our short program, but in longer programs with many blocks of code it adds to readability and could save hours trying to debug code with a missing brace.
  • 133.
    STEP 10. Add anin-line comment after the ending brace on line 19 – // end class HelloWorld. Make sure to leave a blank line between the end main brace and the end class brace. This it easier to see the structure of the code when reading the code. We are now finished editing the program and it is ready to run. It should resemble the code in Figure 31. NetBeans Notes – Copy and Paste Here’s a tip to improve your efficiency and cut down on typographical errors: use copy and paste to copy method or class header information to the comment marking the block’s ending brace. Generally, cut, copy and paste are a programmer’s friends. Public class HelloWorld { . . .
  • 134.
    } // endclass HelloWorld Figure 33 – completed Hello World! code JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 50 STEP 11. Run the application by selecting Run Project from the Run menu. The Run Project command is at the top of the menu. You could also use the F6 key to run a Java application in Netbeans. It will take a moment for Java to compile the source code before it runs the application. The image on the right shows us the console output as it appears when the program runs from inside NetBeans. The output from the program appears in a window below the Source Code Editor, with the actual output from the application between the run message and the
  • 135.
    Build Successful message. Sourcecode and other project elements are automatically saved when we run a project in NetBeans. We do not need to save before running, although it is a good idea to save any code that you have worked on for a while without either running or saving the project. Closing NetBeans Properly Projects remain open in NetBeans until they are purposely closed. If you exit NetBeans without closing a project, then normally the same project will be open when you restart NetBeans. You must specifically close a project when you are finished working on it. NetBeans Notes – Resizing IDE Windows The windows in the NetBeans interface can be re-sized by clicking and dragging the boundaries between the windows, either horizontally or vertically. Figure 35 – Hello World! console output in a
  • 136.
    NetBeans Console Window. Figure34 – the run menu JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 51 STEP 12. To close your project, select the HelloWorld project in the Project window, then select Close Project on the NetBeans File Menu, to close the project. After closing the project, the NetBeans interface should be blank. When you are ready to exit NetBeans, select Exit from the bottom of the File menu. When you re- open NetBeans, you can open your project by selecting Open Project form the NetBeans File Menu, or by selecting Open Recent Project. Copying and Submitting NetBeans Projects Each NetBeans project is stored in its own folder, within the NetBeansProjects folder on the host computer. If you installed NetBeans 8 on a Windows system as
  • 137.
    directed in Appendix1, then the NetBeansProjects folder will be in the Documents folder (My Documents on some systems) On other systems, or if you are not sure where the project folder is, then you can search for the NetBeansProjects folder and check its contents. To copy a NetBeansProject from one computer to another, copy the individual project folder from the NetBeansProjects folder on one system to the NetBeansProjects folder on another system. You could also zip/unzip the project folder to make moving it or storing a copy of it more convenient. Actually, a netbeans project folder will work from almost anywhere you put it on your computer, such as on the desktop. To submit a CSCI 111 programming assignment to your instructor: the NetBeans project folder. folder by using the upload link for the assignment in Canvas. You can also send it as an attachment to a Canvas message or as an
  • 138.
    attachment to aregular email message. If you have a question about your code, it is often convenient to send your instructor a copy of the code attached to a message with the question. Figure 36 – closing a NetBeans project JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 52 Key Terms in Chapter 1 After completing this chapter, You should be able to define each of the following key terms: Algol, 16 algorithm, 9 argument list, 43 assembler, 11 assembly language, 11 BASIC, 19 block comment, 44 braces, 43
  • 139.
    byte code, 13 Cprogramming language, 21 C#, 24 C++, 23 class, 10 COBOL, 17 compiler, 12 computation, 4 computer engineering, 6 computer program, 9 computer science, 4 device drivers, 5 distributed network, 32 external storage, 3 FORTRAN, 14 heterogeneous network, 32 high-level languages, 12 human–computer interaction (HCI), 4
  • 140.
    I/O, 4 in-line comment,44 input units, 4 internal memory, 3 interpreter, 12 instance, 10 Java, 32 Java Runtime Environment, 13, 35 JavaScript, 28 JLS, 38 Lambda Calculus, 18 LISP, 18 machine code, 11 methods, 10 mnemonics, 11 object, 10 object code, 12 Objective C, 25
  • 141.
    object-oriented programming, 10 operatingsystem, 5 output units, 4 parameter, 43 Pascal, 20 peripherals, 4 Perl, 24 PHP, 29 property, 10 public, 43 Python, 26 random access memory (RAM), 3 read only memory (ROM), 3 Ruby, 30 scripting languages, 13 Simula, 22 Smalltalk, 22 source code, 12
  • 142.
    static, 43 system console,37 system utilities, 5 System.out.println, 46 Warning! – Flash ROM Failures USB flash ROM drives are convenient, but they can suddenly go bad without warning. They are good for moving data from one computer to another, but you should not rely on them as a backup copy of your data. Flash ROM technology is good for a limited number of write cycles -- usually about 10,000 cycles. Working directly from a flash ROM drive could result in hundreds of accesses per hour. Someone in the habit of working directly on the USB device could have the chip go bad in a few weeks of use. (More robust industrial grade flash ROM chips last for up to 1 million write operations, but are more expensive – $50 to $75 per gigabyte in 2013.) Instead of working directly on a flash ROM drive, you can copy your work to a computer’s hard drive, do
  • 143.
    some work onyour program, then copy your work back to the USB drive when you need to move it to another machine. If a file or folder is not too large, you can send it to yourself as an email attachment, then open the email message on another computer and save a copy of the attachment. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 53 Chapter 1 - Questions 1. What are the primary components of most computer systems? How are these components connected to one another? 2. What is inside a central processing unit and what is the function of each of these things? 3. How does internal memory differ from external storage? 4. For whom are algorithms named? Where and when did he do his most important work? What method for solving math problems did he present in his work? Why is his work important in the history of math and computer science? How is it related to computer
  • 144.
    programming? 5. How arealgorithms related to computer programs? 6. Why did computer scientists introduce object-oriented programming? What can be represented by an object in object-oriented programming? How are data and programs that manipulate data organized in object-oriented programming? 7. What is the difference between a computer engineer and a software engineer? How does their work relate to computer science and other fields? 8. What organization is responsible for accrediting computer science degree programs? What organizations sponsor the accrediting agency, and what do they do? How can it be beneficial for a computer professional to belong to one of these agencies? How can we find out more about their student memberships? 9. What are some of the more common specializations for computer scientists? 10. What is the difference between a high-level language and a low-level language? How does assembly language fit into all of this? How many different assembly languages are there?
  • 145.
    11. What docompilers and interpreters do and how do they compare to one another? 12. What is the process for translating Java into machine code for specific systems? What design goals for the Java language led to the development of this method? How did several well-known major computer companies react to the way Java is implemented? What indications do we have of the success of Java’s method of implementation? 13. What early programming language that was not widely used commercially created a foundation for most modern programming languages? What are some of the more important features that first appeared in this language? 14. What programming language was based on Lambda Calculus, and what are some of its modern derivatives? What field of computer science has been most associated with this language? Why is lambda calculus important in computer science? 15. Why are Simula and Smalltalk important in the history of computer programming? Who developed these languages?
  • 146.
    16. How isJava related to C and C++? JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 54 17. How did Guido van Rossum suggest Python and Java can be used together? 18. What is a JRE? What is included in a JRE? 19. Who owns the java programming language? How is the language updated? 20. What is a JDK? How do the three main versions of the JDK differ from one another? Chapter 1 - Exercises 1. Modify the HelloWorld project from the exercise is this chapter to print the message “Hello Dr. Kernighan!” on a line after it prints “Hello World!” Remember to update the comments in the code. 2. The bulleted list on page 46 tells us: “println tells Java to print the message then start a new line. print by itself, without the ln, would tell Java to print the message then wait on the line for whatever comes next. println tells Java to behave as if [Enter] is pressed after the message,
  • 147.
    whereas print issimilar to typing something without pressing [Enter] at the end of the line...” So the following two lines will print Hello. Goodbye. on the same line of console output: System.out.print("Hello. "); System.out.println("Goodbye."); Create a new Java project similar to the HelloWorld project that uses print and println to print the text from a business card for yourself. The output should look something like this: Chuck Herbert Computer Science major Community College of Philadelphia Philadelphia, PA 19130 [email protected] It should include the following items as String literals in the printing commands, not as variables: first name, last name, major, school, city, state, zip, and email address. No two items from this list above may be printed by the same command. For example, your first name should be printed using a print instruction, then your last name
  • 148.
    printed using aprintln instruction. Blank spaces and the comma between city and state should be included. Don’t forget to include the proper comments in your code. 3. Create a diagram that shows the lineage of Java from the earliest programming languages. It should look like a family tree, showing which languages led to which other languages, that, in turn, eventually lead to Java. For example, our tree would show that both the C language and Simula influenced the development of C++. JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 55 4. Which of the people mentioned in this chapter do you think is most important or most interesting? Research the person and write a short biography of the person, including what the person did in addition to what’s mentioned in the chapter. Cite your sources. You must use at least two sources of information other than Wikipedia. You can read the Wikipedia article, but should not cite it as source since its information is not fully verified as correct. Original
  • 149.
    sources are thebest. 5. Identify one of the programming languages in this chapter and look up the language on the site Webopedia.com. Webopedia is good source of information about technical terms related to computers and computer science. Starting with Webopedia and moving on to other sources, see what you can find out about the language write a short description, including what it primarily used for. List several sources of more information, such as language specifications, sources of compilers and interpreters (especially if they are free), and tutorials, and sample code. 6. There are a number of online forums and blogs discussing programming languages. Log into one of these and create or join a conversation addressing the question “What is best programming language is to learn and why?” Consider the difference between the easiest language to start with and the best language to know professionally. See if the comments posted by others seem well-founded or not. Do other people describe what their opinions are based on? Do there seem to be biases for or against certain languages, operating systems, or hardware? Which of the posts seem helpful or not helpful, and
  • 150.
    why? Check thesite every day for a week, and write a summary of what you observed and learned related to the items mentioned above. 7. A website that has “Hello world!” source code in different programming languages is cited on page 37. Find the code for “Hello world!” in three different languages – one that seems very easy, one that seems similar to Java, and one that seems complicated. Write a short report, which includes the code, telling what language each is in and something about the language, such as what the language is primarily used for. Look up the code for Java on the site and see if the Java code it shows is complete enough to run as a program by itself. If not, what missing? What does this tell you about the completeness of the code in other languages? 8. A list of some specializations in computer science can be found on page 6 along with a link to the ACM’s special interest group page - http://www.acm.org/sigs . Information about the ACM and the IEEE can be found on page 5, including references to their main websites. What specialization in computer science most interests you, even if you have a major other than
  • 151.
    computing? What resources,including special interest groups, do the ACM or IEEE have related to your area of interest? What special interest groups might you be interested in joining? What courses other than computer courses might be useful for your area of interest? 9. The U.S. Department of Labor’s Bureau of Labor Statistics maintains the Occupational Outlook Handbook with career information for most job classifications in the U.S. It is online at http://www.bls.gov/ooh/ . (You can get there easily by typing OOH in Google or most other search engines.) They also publish a more current Occupational Outlook Quarterly. Find out what they have to say about careers in computer science and closely related fields. What do the jobs pay? What is the http://www.webopedia.com/ http://www.acm.org/sigs http://www.bls.gov/ooh/ JLK Chapter 1 – Introduction DRAFT January 2015 Edition pg. 56 work like? What education or background is needed? Are there many openings in that particular area?
  • 152.
    Write a shortreport summarizing your findings for several areas related to computing. 10. In addition to NetBeans and Eclipse there are quite a few others IDEs that can be used for for Java software development, such as JCreator, BlueJ, JBuilder, IntelliJ, DrJava, Javelin, and Websphere. See what you can find out on the Web about some of them and write a short report describing your findings. —— 30 —— The Java Learning Kit: Chapter 2 – Reading, Writing, and Arithmetic Copyright 2015-2019 by C. Herbert, all rights reserved. Last edited October, 2019 by C. Herbert This document is a chapter from a draft of the Java Learning Kit, written by Charles Herbert, with editorial input from Craig Nelson, Christopher Quinones, Matthew Staley, and Daphne Herbert. It is available free of charge for students in Computer
  • 153.
    Science courses atCommunity College of Philadelphia during the Spring 2019 semester. This material is protected by United States and international copyright law and may not be reproduced, distributed, transmitted, displayed, published or broadcast without the prior written permission of the copyright holder. You may not alter or remove any trademark, copyright or other notice from copies of the material. The Java Learning Kit: Chapter 2 Reading, Writing, and Arithmetic Lesson 2.1 – Data Types Lesson 2.2 – Variables and Constants Lesson 2.3 – Assignment Statements and Expressions Lesson 2.4 – Data Streams and System Console I/O Lesson 2.5 – Documentation First Programming Lab 2A – Console I/O: Age in Days Lesson 2.6 – JOptionPane Pop-Up Dialog Windows Lab 2B – Pop Up Windows Dialog: Age in Days JLK Chapter 2 – Introduction DRAFT October 2019 pg. 2
  • 154.
    Contents Chapter 2 LearningOutcomes ........................................................................................... .... ....................... 4 Data Types ............................................................................................... .......................... 5 Common Data Types in Java ............................................................................................... .................. 5 Variables, Constants, and Literals ............................................................................................... .......... 6 Boolean Data ............................................................................................... .......................................... 6 Text Data ............................................................................................... ................................................ 7 Special Characters in Strings ............................................................................................... .................. 9 Integer Data ........................................................................................... .... ......................................... 10 Floating Point Data ...............................................................................................
  • 155.
    ............................... 10 IEEE FloatingPoint Numbers ............................................................................................... ................ 11 CheckPoint 2.1 ............................................................................................... ...................................... 12 Numbers from the Real (and Imaginary) World ................................................................................. 13 Variables and Constants ............................................................................................... ... 14 Local Variables ............................................................................................... ..................................... 14 Constant Declarations ...................................................................................... ......... .......................... 15 Hardcoding ............................................................................................... ........................................... 15 Variable and Constant Names – Java Identifiers ................................................................................ 15 CheckPoint 2.2 ............................................................................................... ...................................... 16
  • 156.
    Assignment Statements andExpressions ....................................................................... 17 Polymorphism ............................................................................................... ...................................... 17 Arithmetic Operations ............................................................................................... ......................... 18 Quotients and Remainders ............................................................................................... .................. 19 Unary Operations ............................................................................................... ................................. 19 The Java Math Class ............................................................................................... ............................. 20 Order of Operations ............................................................................................... ............................. 22 Commutative and Associative Behavior ............................................................................................. 24 Type Casting ............................................................................................... ......................................... 25 Cast Operators
  • 157.
    ............................................................................................... ..................................... 26 CheckPoint 2.3 ............................................................................................... .....................................26 Data Streams and System Console I/O ........................................................................... 27 The Scanner Class ............................................................................. .................. ................................. 28 Checkpoint 2.4 ............................................................................................... ..................................... 29 Documentation First Programming ................................................................................ 30 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter%202%20- %20Reading%20Writing%20and%20Arithmetic/JLK%202%201 2%2031%208%20am.docx%23_Toc407776762 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter%202%20- %20Reading%20Writing%20and%20Arithmetic/JLK%202%201 2%2031%208%20am.docx%23_Toc407776765 file:///C:/Users/user/Documents/jlk/Dec%202014%20edition/Ch apter%202%20- %20Reading%20Writing%20and%20Arithmetic/JLK%202%201 2%2031%208%20am.docx%23_Toc407776767 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 3
  • 158.
    Lab 2A –Console I/O: Age in Days ............................................................................................... ........... 33 JOptionPane Pop-Up Dialog Windows ............................................................................ 38 Using the JOptionPane Message Dialog Window ............................................................................... 38 Using the JOptionPane Input Dialog Window ..................................................................................... 40 Parsing Numbers from Strings ............................................................................................... ............. 41 Exceptions When Parsing Numbers from Strings ............................................................................... 43 Lab 2B – Pop Up Windows Dialog: Age in Days ................................................................................ ...... 44 Key Terms in Chapter 2 ............................................................................................... ............................ 48 Chapter 2 - Questions ............................................................................................... .............................. 49 Chapter 2 – Exercises ............................................................................................... ............................... 50
  • 159.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 4 The Java Learning Kit: Chapter 2 Reading, Writing, and Arithmetic This chapter introduces some of the basic elements needed to create Java programs. Lessons 1, 2 and 3 discuss data types and simple arithmetic in Java, including assignment statements and math expressions. Lesson 4 looks at console I/O, which is text input and output based on data streams. We won’t learn how to read and write data files in this chapter – that comes later – but the text data streams used for reading input from the keyboard and writing output to the screen are the basis for working with text data files in Chapter 6. Lesson 5 shows an alternative method of I/O – using pop-up dialog windows, which are more interesting and attractive than console I/O, and are fairly simple to use. Lesson 6 is about the importance of documentation and how to
  • 160.
    use documentation astool to help design and build software. The two labs in the chapter will provide you with some practice using most of the material covered in the chapter. The first lab is based on console I/O and the second lab uses pop-up dialog windows. Chapter 2 Learning Outcomes Upon completion of this chapter students should be able to: • describe the concept of a data type; list and describe the primitive data types in Java; • describe the difference between primitive data types and classes of objects, and how the String data type is unique in this regard; • describe the mathematical concepts of integers, rational numbers, and real numbers, and how they are implemented in Java; • describe the concepts of variables and constants, scope rules for variables, and Java naming conventions for variables; • declare and assign values to primitive and String variables in Java; • describe the benefits of frontloading declarations in Java methods;
  • 161.
    • describe theconcept of type casting and how type casting works in Java; • create Java expressions to perform integer and floating point addition, subtraction, multiplication and division, and the remainder operation for integers; • create Java code that uses methods from the java.lang.Math class; • describe the concept of a data stream and stream tokenization, and how console input and output data streams are handled in Java; • create Java code to allow applications to read data from a keyboard as console input; • describe what a pop-up dialog window is and how to create message and input dialogs windows in Java, including how to parse numbers from input Strings. • create Java code that implements a dialog with the user via JOptionPane pop-up dialog windows. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 5 Data Types A data type is a format used to store data, including instructions for operations that can be performed
  • 162.
    on the data,along with an acceptable range of values for the data. Formats for data depend on what the data means and how the data will be used. Numbers, for example, are stored in formats that allow the computer to quickly perform arithmetic with the data. Using different data types allows computers to process data more efficiently – using less memory to store data and less time to process data. Generally, object-oriented programming languages have two main categories of data types – primitive data types and reference data types. A primitive data type is built into the programming language and may be used by a programmer without first defining the data type. A reference data type refers to an object, which needs to be defined by a programmer before it can be used. Reference data types are also called user-defined data types. Each class of object in Java is essentially its own user-defined data type. There is one exception – the String class in Java is a special class of objects, built into the language. We may use String as a primitive data type, even though it is actually a reference data type. The
  • 163.
    primitive data typesand the String class are together known as Java’s built-in data types. Common Data Types in Java Most programming languages have data types that each fall into one of four different categories of data: • Boolean data is used to keep track of true and false values. • text data is composed of characters – the symbols we use in human languages, such as the Latin alphabet used for the English language. • integer data is numeric data without fractions. • floating point data is numeric with fractions, most often as decimal numbers with a decimal point. Java has nine built-in data types that each fall into one of these categories, as shown Figure 1. Eight of built-in data types shown in the chart – boolean, char, byte, short, int, long, float, and double – are Java’s primitive data types, described in this chapter. The ninth built-in datatype is the String class of objects, which may be used as primitive data type. Notice that the names of most of the nine data types each start with a lowercase letter while the “S” in
  • 164.
    String is capitalized.This is because the names of classes in Java are usually capitalized, while the names of primitive data types are not capitalized. We will use Strings starting in this chapter, then learn more about the String class in in subsequent chapters. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 6 Variables, Constants, and Literals Data may be represented in Java code as variables, constants or literals. A variable is a memory location holding a specific value, similar to a variable in algebra. A variable has a symbolic name in Java source code, which refers to the value stored in memory. The value, or the link between the variable name and the stored value, can be changed, hence the name variable. A constant refers to a value stored in memory which, once initialized, cannot be changed, hence the name constant. A literal is a source code representation of a specific value of a built-in data type. The phrase “Hello
  • 165.
    World!” used inLab 1 in Chapter 1 is an example of a String literal. Java’s built-in data types are described briefly in the following sections. For more detailed information about Java data types, see the data types section of the Java online tutorial at: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatyp es.html Boolean Data Java’s boolean data type is named “boolean” with a lowercase ‘b’ while the general term is Boolean, with an uppercase “B”, named after George Boole. A boolean variable may hold the values true or false used to keep track of whether something is true or false. It has the smallest range of any data type. The answer to any true or false question, or the equivalent, such as yes corresponding to true and no corresponding to false, can be stored as boolean data. A checkbox on a job application keeping track of whether or not the applicant has a driver’s license, for example, can be coded in Java as boolean data. Figure 1 – Java data types
  • 166.
    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatyp es.html JLK Chapter 2– Introduction DRAFT October 2019 pg. 7 Figure 2 shows two questions from the Pennsylvania Voter Registration Form that each are Boolean questions – they have yes or no answers that can correspond to the boolean values true or false. Boolean data can be represented by a single bit of storage space, but often computers use a byte to speed up software since most memory is byte addressable. Byte addressable means that each byte of memory has its own memory address, making it faster for the computer to address an entire byte than to address a bit within a byte. Each machine’s JVM handles Boolean data according to the rules of the host system. Some use only a single bit to store a boolean value, but most use an entire byte. There are only two literals for boolean data – true and false, lowercase with no quotes. Text Data Text data is made up of characters. A character is a single symbol from the alphabet of a language. In
  • 167.
    English, the name“John”, for example, is made up of four characters – J, o, h, and n. Unicode and the older ASCII character set (American Standard Code for Information Interchange) are the most commonly used codes for storing text data. Java stores characters using UTF-16, a 16-bit version of Unicode. This means that each Java character is 16 bits (two bytes) long. See The Unicode Consortium Website at: http://www.unicode.org/ for more information. Java has two built-in data types for storing text data: • char – char is a primitive Java data type used to store a single UTF-16 character. The char data type has a length of 16 bits (two bytes). Char literals are enclosed in single quotes – ‘X’. • String – a Java String is a set of Unicode characters stored as an instance of the String class of objects. Special support is built into Java for String objects. 16 bits, (two bytes) are needed for each character in a Java String. Notice that the names of the primitive data types all start with a lowercase letter, while String starts with an uppercase ‘S’ because it is the name of a class of
  • 168.
    objects and classnames are capitalized. A String literal is a string of characters in quotes. It can be used anyplace a String value or variable can be used in Java, such as in output statements. “Hello World!” is an example. Strings literals are indicated by enclosing them in double quotes – “name”. Figure 2 – Boolean questions http://www.unicode.org/ JLK Chapter 2 – Introduction DRAFT October 2019 pg. 8 Any UTF-16 character can be used as a Java character or in a Java String. The term alphabetic character refers to upper and lowercase letters, usually in reference to the Latin alphabet used for English. The term numeric character refers to decimal numeric digits 0 through 9. The term alphanumeric character refers to the two together – alphabetic characters and numeric characters but it does not include special characters, such as $, !, ? or #. All characters that are not decimal numeric digits 0 through 9 are called non-numeric characters.
  • 169.
    The String andchar data types are used for information that is not normally used to perform arithmetic. Names, labels, and messages are most often stored using the String and char data types. This includes ID numbers used as labels identifying people or things, such as Social Security numbers, student numbers, and product serial numbers. Even though we call them numbers, they are really used as text data and often include non-numeric characters. We also don’t want them to be rounded off or truncated, as numbers sometimes are. X = √��� ���� + ������ �������� ������ � ? Representing ID Numbers ID numbers are numbers that identify a person, place or thing, such as social security number or zip code. They are not stored as numeric data because they will not normally be used for arithmetic. (When is the last time you needed average student number, or the square root of your
  • 170.
    zip code?) They arereally labels, and as such are Strings. In fact they should be Strings so they can include non-numeric characters, and so they aren’t rounded off, as some numeric occasionally is. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 9 Special Characters in Strings Θ α π ‫ب‬ ‫א‬ ☛ ☺ Escape sequences are codes for special characters. They are called escape sequences because they originally involved the use of the escape key on computer terminals. They were defined as part of the ASCII code and are now part of Unicode. They can be used as text data in Java and most other modern programming languages. Many are control codes, which do not print a character but control the way characters are printed. Each Unicode character has a code number, usually expressed as a hexadecimal number A character can be included in a Java String literal by typing the backslash followed by its escape
  • 171.
    sequence character, orby typing a backslash followed by a u, followed by its Unicode hexadecimal code number. For example, this Java statement prints a String starting with a tab and ending with an alpha: System.out.println(“t This prints a Greek alpha u03b1.”); Here are examples of some Unicode control characters with escape sequences and Unicode non- Latin printable characters. All can be represented using their UTF-16 values. Control Codes (escape codes) name sequence Unicode (hexadecimal) Backspace b 0008 Tab t 0009 Linefeed (new line) n 000a Form feed (new page) f 000c Double quote ” 0022 Single quote ’ 0027 Backslash 005c Printable Characters (non-Latin)
  • 172.
    name charcter Unicode (hexadecimal) Greek uppercasetheta Θ 0398 Greek lowercase alpha α 03b1 Greek lowercase pi Π 03c0 Hebrew alef 05 ‫א‬d0 Arabic alef 0627 ‫ب‬ pointing hand ☛ 261b smiley face ☺ 263a There are Unicode UTF-16 characters from many alphabets (Arabic, Cyrillic, Greek, Hebrew, etc.) and for many special characters. The null value is Unicode 0000, which is distinguished from a blank space (0020), or a zero digit (0030). The non- printing control characters are used for special purposes, such as in data communications and to format output. For more information, see: The Unicode Consortium Website at: http://www.unicode.org and the interactive Unicode Character Code pages online at: http://www.unicode.org/charts http://www.unicode.org/ http://www.unicode.org/charts
  • 173.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 10 Integer Data Java has four primitive integer data types: byte, short, int, and long: • A byte is an 8-bit value representing a signed integer with a minimum value of -128 and a maximum value of +127. It is the shortest of all integer data types, using only a single byte (8 bits) for each value. • A short integer has a minimum value of -32,768 and a maximum value of +32,767. It requires 16 bits of memory (two bytes) to store each value. • int data has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647, using 32-bits of memory (four bytes). It is the most commonly used integer data type. • A long integer has a minimum value of - 9,223,372,036,854,775,808 and a maximum value of longest primitive integer data type, using 64 bits of memory (eight bytes) for each value. Integers are entered in Java by typing the digits, with no commas for thousands, etc. A negative sign
  • 174.
    should be usedfor negative numbers. All primitive integers in Java are stored using two’s complement arithmetic, studied in more detail in computer-related Math courses, such as Math 121 or Math 163 at Community College of Philadelphia. Java does not have primitive data types for unsigned integers, as some languages, such as C++, do. The only difference between any two Java integer data types is the length of the number, as determined by its storage space. The most commonly used integer data type is int. The short or byte data type can be used to save memory, such as in an embedded processor in a small chip with little memory. The long data type can be used when integers beyond the range of the int data type are needed. Floating Point Data Java’s floating point numbers are stored using a mantissa- exponent format similar to scientific notation with a mantissa, an exponent, and two signs, one for the mantissa and one for the exponent. For example, the value 437.65, which would be 4.3765 x 102 in base-ten scientific notation, would be stored as +4.3765E+02 as a Java floating point number. The value
  • 175.
    before the Eis the number’s mantissa and the value after the E is its exponent. It has become customary in Computer Science to refer to the mantissa as the significand in a floating point number to distinguish it from the mantissa in a logarithm. Floating point numbers are not stored in logarithmic formats, they are stored in a log-linear format, so what is called the mantissa in a floating point number is not the same thing as a mantissa in a number stored in a logarithmic format. Floating point number formats in Java are compliant with the IEEE’s Standard for Binary Floating-Point Arithmetic (IEEE 754-2008). JLK Chapter 2 – Introduction DRAFT October 2019 pg. 11 IEEE Floating Point Numbers The IEEE’s Standard for Floating-Point Arithmetic (IEEE 754) defines formats for floating point numbers and rules for operations on those numbers. Java uses two binary formats from the standard for binary floating point numbers: the 32-bit binary format for the float data type, and
  • 176.
    the 64-bit binaryformat for the double data type. Values are stored in a binary format but displayed by default in a decimal format. Floating point numbers are similar to scientific notation: +4.3765E+02 is 4.3765 x 102, four point three seven six five times ten to the second power. An IEEE floating point number has: • a sign indicating if the value is positive or negative. • a significand containing the significant digits of the number. The significand is more formally known as the mantissa of a floating point number, but is often called a significand to distinguish it from the mantissa in a logarithm, Floating point numbers are in a log-linear format, not a logarithmic format. • an exponent. IEEE 754 uses an offset for the exponent which accounts for the sign, so the sign of the exponent is not stored separately. • The base, which is always 10, is not stored. 32-bit format used for float values Sign Exponent Significand
  • 177.
    1 bit 8bits 23 bits The 23-bit significand is always accurate to at least six decimal digits, sometimes seven, depending on the exact value. It is safe to rely on six digits of accuracy. The 8-bit exponent is in the binary range of -127 to +127, roughly equivalent to the decimal range 10- 64-bit format used for double values sign Exponent Significand 1 bit 11 bits 52 bits The 52-bit significand is always accurate to at least 15 decimal digits, sometimes 16, depending on the exact value. It is safe to rely on 15 digits. The 11-bit exponent is in the binary range of -1023 to +1023, roughly equivalent to the decimal range 10- Java floating point formats are based on the 1985 standards (IEEE754-1985). The standard was expanded in 2008 (IEEE754-2008) and adopted by the ISO. The old formats are a subset of the new definition, and floating point values in Java are compliant with the newer standard.
  • 178.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 12 There are two primitive data types in Java for floating point numbers: • float – a single precision floating point value that is accurate to six decimal digits, with values ranging from roughly 10-38 to 10+38. A float requires 32-bits of storage space (four bytes). • double – a double precision floating point value that is accurate to fifteen decimal digits, with values ranging from roughly 10-308 to 10+308. A double requires 64-bits of storage space (eight bytes). The name double comes from the fact that it uses double the memory, not that the mantissa or exponent are double the accuracy. Floating point numbers may be typed in Java as decimal numbers, such as 1234.56, or in their significand-exponent format: +1.23456E+06. The significand is normalized, which means there is only one significant digit before the decimal point. 45.654E+02 would be normalized to 4.5654E+03.
  • 179.
    Floating point numbersall have decimal points. 0.0 is a floating point value. 0 is an integer value. CheckPoint 2.1 1. What are Java’s nine built-in data types and how do they fit into four major categories? 2. Which Java built-in data type is not a primitive data type? 3. How do each of Java’s integer data types differ from one another? 4. What is a literal and how are literals represented for different built-in data types? 5. Describe the formats used to store floating point data in memory. Note: Be careful about answers that are correct, but incomplete. For example, float and double are the names of the formats used for floating point data, but questions 5 asks for more than just their names. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 13 Numbers from the Real (and Imaginary) World
  • 180.
    We’ve looked atinteger and floating point numbers in Java, but what about other kinds of numbers, such as whole numbers, real numbers, and so on? It turns that some are well-defined and some are subject to interpretation. An integer is numbers without a fraction {…, -3, -2, -1, 0, 1, 2, 3, …}. Any of Java’s integer datatypes can be used to represent integers, within the range of values for each type. The terms whole numbers, natural numbers and counting numbers are without universally agreed upon definitions. Some mathematicians say whole numbers and integer mean the same things, while others say whole numbers start at zero. Some say natural numbers start at zero and include only the positive integers. Others say natural numbers start at one. The same is true for counting numbers – some say they start at zero, some say at one. Mathematicians and computer scientists who wish to be precise use the terms positive integers and non-negative integers to define two subsets of integers: the positive integers start at one {1,2,3,…}, while the non-negative integers start at zero {0,1,2,…} The
  • 181.
    non-negative are alsocalled unsigned integers. Java does not have a special data type for unsigned integers as some languages do. A rational number is any number that can be represented by a ratio of integers; basically a fraction whose numerator (top) and denominator (bottom) are both integers. (The denominator cannot be zero.) Integers are a subset of the rational numbers. A real number is any number that can be represented on a number line. Basically, if we can draw a line of a certain length, even if the length cannot be expressed exactly as a rational number, it is a real number. The hypotenuse of a right triangle with two sides each 1 unit long is √2, which is a real number that does not exactly equal any rational number. Such numbers are known as irrational numbers. An irrational number is any real number that cannot be represented exactly by a ratio of integers, such as π or √2. We cannot represent all real numbers in Java, but we can represent a decimal approximation of real numbers using floating point numbers. For example, π is 3.14159265358979 as the 15 digit double
  • 182.
    value +3.14159265358979E+00, whichis accurate enough to calculate the radius of a sphere the size of the Earth within one-millionth of an inch. Numbers that involve negative square roots are imaginary numbers, since negative values have no square root. Complex numbers combine real and imaginary numbers. They are important in fields such as electronics. Basically, if you need to use them you know what they are, if not, then don’t worry about it for now. The Apache Commons website has a complex number API used by scientists and engineers. ( See: http://commons.apache.org/proper/commons- math/userguide/complex.html ) http://commons.apache.org/proper/commons- math/userguide/complex.html JLK Chapter 2 – Introduction DRAFT October 2019 pg. 14 Variables and Constants The variables and constants mentioned in the discussion of data types are an essential element of computer programming.
  • 183.
    In addition toa data type, each variable and constant in Java has a scope of existence. The scope of existence, or simply the scope, of a variable or constant is that part of a program in which it exists and can be used. Variables may be local variables within a method or they may be used to refer to the properties of objects, such as the color of a car or the name of a person. In the rest of this section we will focus on local variables. The properties of objects are discussed in later chapters, but for now you should know that they also have a name and a data type, just as local variables do. Local Variables The variables in Java methods are called local variables. The scope of a local variable is determined by its lexical context, which means it depends on the variable’s place within specific language. A local variable can only be used within the block of code in which it is declared. The beginning and end of Java blocks of code are marked by braces { … } as we saw in Lab 1 chapter 1. A method is a block of code, since it begins and ends with braces. We may also have blocks within blocks, such as a block of code to
  • 184.
    be repeated ina loop, or a block of code to be executed by an if command. A variable only exists and can only be used in the block of code in which it is declared. A variable declared inside one method does not exist in another method and cannot be used in another method. Another method could have a different variable with the same name, but they would be different variables, referring to different memory locations. To declare a variable means to state the name and data type of a variable, and possibly give it an initial value. Here are three examples: int sum; // the sum of the test scores double angle = 47.63; // angle of elevation String zipcode; // the customer’s zipcode In the first example, the variable named sum is declared to be an int variable. It has no initial value. A variable without a value is a null variable – it is not equal to zero, it has no value. There is a difference. In the second example, angle is declared to be a variable of type double, with an initial value of 47.63. All variables for primitive data types and Strings can be
  • 185.
    initialized in thisway when they are declared. The value should be a literal of the same data type as the variable, or an expression yielding a value of the correct data type. In the third example, the variable zipcode is declared as a String variable. Notice that the name zipcode is lowercase, as are almost all variable names. String with an uppercase ‘S’ is the name of a class; zipcode refers to an instance of the String class. In this example, zipcode in not initialized, so it will have a null value until it is used in the program. The inline comments in the variable declarations above make it easier for people reading the code to understand it – including the code’s author, reading the code months or years after it was written. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 15 Variable declarations may appear almost anywhere in a Java program, but it is a good programming practice to declare all variables for a method at the beginning of the method with a comment describing each variable. This practice, known as front loading declarations, does two things:
  • 186.
    1. It createsa data dictionary at the beginning of a method, making it easier for people who read the code to find out what variables are used in the code and what they represent. 2. It makes it easier to read a program. Data declarations in the middle of code can sometimes make the code harder to follow, in a subtle way. Constant Declarations A constant in Java is declared and used just as a variable is, except that its value cannot be changed. We designate a constant by putting the keyword final in front of the type in its declaration, as in these examples: final double PI = 3.141592653589793; final String PAGENOTE = “© 2014 – All rights reserved”; final int CLASS_SIZE_LIMIT = 36; Notice that constant names are all uppercase, with an underscore character separating parts of a compound name. This a Java programming convention. Hardcoding Putting a data value directly into your code is known as
  • 187.
    hardcoding data, and isgenerally frowned upon by good programmers (and instructors who will be grading your assignments). It is a bad habit to develop, because it can lead to errors and inefficiency. Imagine that you will use 365.25 as the number of days in a year many places in a program. Instead of typing 365.25 many times or copying and pasting it many times, you can declare a constant DAYS_PER_YEAR, and just use it each time. The same holds true for String values used repeatedly like “Northwest Philadelphia Regional Center” in CCP software, or “Aleksandr Isayevich Solzhenitsyn” in an application about Russian dissidents who won the Nobel Prize for literature in 1970. It is good programming practice to develop the habit of using constants instead of hardcoding values in software. Variable and Constant Names – Java Identifiers
  • 188.
    A Java identifieris a string of Unicode characters that identifies something in Java code. Identifiers are used to name variables, methods, classes, and so on. The Java Language Specification (JLS)1 section 6.2 describes the acceptable syntax of a Java identifier and also suggests programmers follow common naming conventions. 1 Available online from Oracle at: http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls- 6.2 http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls- 6.2 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 16 According to the JLS, Java identifiers must start with a letter of the Latin alphabet (a-z), an underscore character (Unicode 005F), or a dollar sign (Unicode 0024). The use of the underscore and dollar sign are for historic reasons, and the JLS discourages their use as the first character in an identifier in modern code. The remaining characters in an identifier may also include decimal numeric digits (0-9), so they may be any the alphanumeric characters or the underscore or
  • 189.
    dollar sign. There aretwo forms of names in Java, simple names and qualified names. A simple name is a single identifier. A qualified name is a sequence of two or more simple names separated by periods. Qualified names identify the context in which a simple name is used. For example, a property lastName for an instance of the Student class named student1 would have the qualified name student1.lastName. Simple names are used most of the time for local variables in Java code. Qualified names are used when the context needs to be specified, such as when code refers to properties or methods from a class. There are four primary naming conventions in Java: • names should be meaningful. Minimize the use of x, y, a, b, or things like num1 or num2. • class names are in Upper CamelCase, such as HelloWorldApp, Math, or Student. • variable and method names are in lower camelCase, such as sum, realRoot1, or hourlyRate • constants are named in all UPPERCASE, using an underscore to separate part of a compound name, such as PI, GROWTH_RATE, or MAX_WEIGHT. This clearly distinguishes constants.
  • 190.
    Java Keywords arepart of the language and are meaningful to the compiler. They may not be used as identifiers in Java. Some examples are int, class, double and if. Keywords are also called reserved words. Java has a relatively small set of 50 keywords: abstract continue for new switch assert default if package synchronized boolean do goto private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const float native super while By comparison, C++ has 86, C# has 79, Swift has 71, Python 2.0 had only 31 and COBOL has over 400. CheckPoint 2.2 1. What determines the scope of a local variable? 2. What is the difference between the way constants and variables are declared? 3. What is hardcoding and why is it better to use constants than to hardcode data? 4. What is a qualified name and why does it have more than one part?
  • 191.
    5. What arethe benefits of frontloading variable and constant declarations? JLK Chapter 2 – Introduction DRAFT October 2019 pg. 17 Assignment Statements and Expressions An assignment statement assigns a new value to an existing variable. It has two parts, separated by an equal sign: variable = expression; The only thing to the left of the equal sign is the name of the variable. An expression describing the value to be assigned is to the right of the equal sign. Here are three examples: angle = 45; // int assignment, hardcoded grossPay = hours * rate; // math expression city = “Philadelphia”; // String assignment Expressions tell a computer how to determine or calculate a value. Numeric expressions often look like expressions in elementary algebra and most of the rules are the same as in elementary algebra. The computer will attempt to resolve the expression to end up with a
  • 192.
    single value ofthe required data type, then assign that value to the variable. An expression should yield a value of the same data type as the variable to which it is assigned. If not, type casting may occur. Type casting is discussed in more detail later in this section. Expressions have operands, which are the values used in an expression, and operators, which are symbols or functions indicating the operations to be performed in an expression. In the expression sum = a + b, the terms sum, a, and b are the operands, while the plus sign is the operator indicating the addition operation. Instructions included as part of a data type tell the computer how to perform basic operations on that type of data, such as addition, subtraction, multiplication, and division for integer data. The symbols used in assignments statements indicate these operations. Functions are methods that return a value, such as a math function to return the square root of a number or a String function to convert a String to all uppercase characters. The nature of an operation depends on the data types of the
  • 193.
    operands being usedwith the operation. For example, The Math library’s round function can be used to round off a double or float to the nearest integer, but there is no need for such an operation for Strings: x = Math.round(17.6) results in x being set to 17. x = Math.round(“Hello world!”) doesn’t work, because “Hello world!” is a String, not a number, and the round operation is not defined for Strings. Polymorphism Sometimes a symbol for an operation or the name of a method in a method call can trigger one operation for one data type and another operation for a different data type. In computer programming, this is a form of polymorphism, which means the same name or symbol can stand for different operations on different data types. The meaning of the plus sign + depends on the data types of its operands. The plus sign is polymorphic because it performs different operations on different types of data: JLK Chapter 2 – Introduction DRAFT October 2019 pg. 18
  • 194.
    • The Javainstruction System.out.print(12 + 16) prints the number 28. The operands 12 and 16 are int values, so the computer will perform the operation associated with the plus sign for integers — simple integer addition. • The Java instruction System.out.print(“Joe” + “Smith”) prints the String “JoeSmith”. “Joe” and “Smith” are Strings, so the computer will perform the operation associated with String data — concatenation, sticking the two strings together to form a new longer string. The plus sign signifies addition for int values but concatenation for Strings. It has multiple meanings, with its meaning bound to the data types of its operands. This is an example of what is known as ad hoc polymorphism, in which the meaning of symbol or a method call depends on the data type of its operands. Ad hoc polymorphism is also called operator overloading and function overloading. Polymorphism is studied In more detail in CSCI 112 and 211, where students learn about parametric polymorphism, which means a generic method has been written to work with any data type. Ad hoc
  • 195.
    polymorphism is limitedto a few specific data types, while parametric polymorphism will work with any data type. For now, it is enough to have a general idea of what polymorphism is – the same method name or symbol can trigger different operations for different data types. Polymorphism is one of the key aspects of object-oriented programming. Arithmetic Operations Java has several built-in arithmetic operations that can be performed on integer and floating point data: • Addition + (the plus sign) • Subtraction - (the minus sign) • Multiplication * (the asterisk) • Division / (the slash) • The remainder operation % (the percent sign) • Unary negation - (the minus sign) • Unary increment (prefix and postfix) ++ (two plus signs with no space) • Unary decrement (prefix and postfix) -- (two minus with no space) Addition, subtraction, multiplication and division are similar to the same operations in elementary
  • 196.
    algebra. Each ofthese operations takes two operands. sum = addend1 + addend2; difference = minuend – subtrahend; product = multiplier * multiplicand; quotient = dividend / divisor; Java does not understand implied multiplication, z = 3x + y must be written as: z = 3*x + y; JLK Chapter 2 – Introduction DRAFT October 2019 pg. 19 Quotients and Remainders A quotient from integer division will be an integer, the remainder is lost. For example, 20 divided by 3 is 6 remainder 2. The result will be the quotient, 6. The remainder of 2 is lost. The modulus operation, also called the remainder operation returns the remainder, not the quotient. The remainder is called
  • 197.
    the modulo ofa number (17 modulo 5 = 2). The operator is the percent sign instead of the slash: Remainder = dividend % divisor; This is read as “Remainder equals dividend modulo divisor.” Here is an example of how the modulus can be useful. Let’s assume that we have 20 feet and want to know how many yards there are in twenty feet and how many feet will be left over. There are three feet in a yard. 20 divided by 3 is 6, remainder 2. Division tells us how many whole yards, 6. Modulus tells us how many feet will be remaining, 2. In general, we could use two instructions in a method like the one below to capture quotient and remainder, assuming the operands are integers: public static void main( String[] args ) { int oldFeet; // the initial distance in feet; int yardsInOldFeet; // the yards in the distance int feetLeftOver; // the number of feet left over final int FEET_IN_YARD = 3; // constant 3 ft. = 1 yd. // insert some code here to get old feet from the user yardsInOldFeet = oldFeet / FEET_IN_YARD; // calculate yards
  • 198.
    feetLeftOver = oldFeet% FEET_IN_YARD; // remaining feet // inset code here to beautifully display the results } // end main() The result of floating point division is a floating point value: 20 / 6 = 3.33333. The modulus operation may also be used to return the remainder from floating point data. 20.0 % 6.0 = 2.0. Unary Operations Several of the operations on integers are unary operations. A unary operation only has one operand. Negation, increment and decrement are unary operations. Negation means reversing the sign of a number; a positive value becomes negative and a negative value becomes positive. We do this by simply putting a minus sign immediately in front of an integer value. For clarity, the value might be placed in parentheses, like this: loss = -(gain); If gain is positive, loss will be negative. If gain is negative, loss will be positive. The Increment operation increases the value of an integer or floating point value by one. If count is ten,
  • 199.
    then incrementing countmakes it eleven. The increment operator is a double plus sign. Increment can be used alone as an instruction, as in this example: count++; // increment count (add 1 to count, equivalent to count = count+1) The new value of count will be the old value of count plus one more. Figure 3 calculating quotients and remainders JLK Chapter 2 – Introduction DRAFT October 2019 pg. 20 The increment operation can also be used in an expression, such as: total = count++; // total = count, then increment count If the operator is after the variable this is called a postfix increment. A Postfix Operation occurs after the variable is used. The value of count is assigned to total, then count is incremented. If the old value of count was 10, then after the instruction, total will equal 10, count will equal 11.
  • 200.
    Increment can alsobe a prefix operation. A Prefix Operation occurs before the variable is used. Like this: total = ++count; // increment count, then assign the value to total In this case, count will be incremented first, then the value of count is assigned to total. If the old value of count was 10, then after the instruction, total and count will both equal 11. The decrement operation decreases the value of an integer or floating point by one. The decrement operator is a double minus sign. It is similar to the increment operation except it subtracts instead of adds, It can be used prefix or postfix, just as increment can be. Total = count--; // total = count, then decrement count Total = --count; // decrement count, then assign the value to total Java also has compound assignment operation. A compound assignment operation combines an arithmetic operation with an assignment statement to add, subtract, multiply, or divide a fixed value with the existing value of the variable, then assign the resulting value to the variable, such as: X += 5; // compound assignment, equivalent to x = x + 5;
  • 201.
    How does thiswork? Consider the statement x = x + 1. In Java, the new value of x equals the old value of x plus one. The expression on the right side of the equals sign is evaluated, then the value is assigned to the variable on the left. This works even if the same variable is on both sides. We have just seen that an increment statement x++ can take the place of x = x + 1. In a similar manner, x = x + 5 can be replaced with X += 5. There are five compound assignment operators: addition assignment subtraction assignment multiplication assignment division assignment modulo assignment += -= *= /= %= Note that there are no spaces between the arithmetic operator and the equals sing in compound
  • 202.
    assignment statements. The JavaMath Class The Java programming language supports elementary arithmetic, but to do more advanced mathematical computation, such as working with exponents, logarithms, or trigonometry, Java provides a library of methods in the Math class, which is part of the java.lang package in the JDK. The java.lang package is a set of classes with features to support Java programming. It is unique because it is the only external package that does not require an import statement. We will learn more about import statements and using other packages later in this chapter. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 21 The Math class has a set of methods that perform math functions. The Math class methods are static methods, which means they are each invoked using the name of the class as part of their qualified name, not an instance of the class. Square root is an example of this. It has the simple name sqrt. Its
  • 203.
    qualified name includesthe class name: Math.sqrt. This table shows some methods available in the Math class in java.lang. The values in parentheses are the data types of a method’s parameters, the values after the method are the type the method returns. java.lang.Math abs(int x): int abs(long x): long abs(float x): float abs(double x): double the absolute value of x cos(double x): double the cosine of x radians exp(double x): double ex where e is 2.71828 hypot(double x, double y): double square root of ( x2 + y2) log(double x): double natural log of x log10(double x): double base 10 log of x max(int x, int y): int max(long x, long y): long max(float x, float y): float max(double x, double y): double the greater of the two arguments min(int x, int y): int
  • 204.
    min(long x, longy): long min(float x, float y): float min(double x, double y): double the lesser of the two arguments pow(double x, double y): double xy x to the y power sin(double x): double the sine of x radians sqrt(double x): double the square root of x tan(double x): double the tangent of x radians todegrees(double x): double converts x degrees to radians toradians(double x): double converts x radians to degrees Notice that several of the functions in the Math class are polymorphic, which means they work with more than one data type. Polymorphic functions are actually different functions with the same name, but their parameters have different data types. If two functions have the same name, the compiler will decide which function to use based on the data types of their parameters. Two functions cannot have the same name and identical parameters. If the name is the same, the parameters must be different.
  • 205.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 22 The Math class also has two defined double constants accurate to six decimal places: • Math.E = 2.718281828459045, the closest double value Euler’s number, the basis for natural logarithms • Math.PI = 3.141592653589793, the closest double value to π For a full description of the Math class, see the oracle Math class reference: http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html The Math class is also discussed in the Oracle Java tutorials, online at: http://docs.oracle.com/javase/tutorial/java/data/beyondmath.htm l Here is an example showing how to use the square root function from the Math class in a Java method: public static void main(String[] args) { double squareArea; // the area of a square double side; // the length of the side of the square squareArea = 100.0; // 100.0 is floating point
  • 206.
    side = Math.sqrt(squareArea);// uses the square root function // output result – Strings and variables concatenated into one String System.out.println("The side of a square with area " + squareArea + " is " + side); } // end main() The output looks like this: The side of a square with area 100.0 is 10.0 The variables in this method are both double. To keep the example simple, squareArea is simply set to 100.0. (Normally this value would come from somewhere else, such as user input.) Notice that it is 100.0 instead of 100 to avoid type casting from an integer value to a floating point value. The method sqrt, which calculates a square root, is invoked from the Math library in the statement side = Math.sqrt(squareArea); Math is the name of the class, and sqrt is the name of the method. We use the qualified name Math.sqrt to access a method in another class. squareArea is an argument of the sqrt function, or in terms of Java,
  • 207.
    a parameter thatis passed to the method. The method will use the value of squareArea to calculate a square root and then return the value of the square root, which will be used in our expression. In this case, it is the only value in the expression, so side is set to the value returned by the sqrt() function. Order of Operations The order of operations in a programming language is affected by three things: • order of evaluation • operator precedence • grouping symbols 610 992 5620 Figure 4 using Java's Math class http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html http://docs.oracle.com/javase/tutorial/java/data/beyondmath.htm l JLK Chapter 2 – Introduction DRAFT October 2019 pg. 23 The order of evaluation for a language is basically the direction of the language – left to right for Java, just as it is for English. (Hebrew and Arabic are examples of
  • 208.
    languages that areread from right to left, while some Asian languages are read from top to bottom.) Order of evaluation is superseded by operator precedence. Operator precedence is the precedence given to one operator over another by a compiler as it evaluates expressions. Here is part of the table of operator precedence from Oracle’s Java Documentation: Operator Precedence unary postfix expr++ expr-- unary prefix ++expr --expr -expr multiplicative * / % additive + - The table above shows us that for elementary math operations Java will evaluate multiplication and division before addition and subtraction, but that multiplication and division have the same precedence, and addition and subtraction have the same preference. Does MDAS sound familiar? It is the same order of operations for elementary math in elementary algebra. Here is an example:
  • 209.
    x = 20+ 4 / 2; What does x equal? Normally we perform operations in order from left to right, but division has precedence over addition, so we should do the division first. The correct answer, in elementary algebra and in Java is x = 22, not x= 12. We can explicitly change the order of operations by using parentheses, as in this example: X = (20 + 4) / 2; In this case, X = 12, not 22. The parentheses tell the computer to evaluate the addition before the division. Parenthesis are a grouping symbol in math. We can always use parentheses to explicitly tell the computer to evaluate one operation before another. Parentheses are also very important when translating fractions into a programming language. In elementary algebra, the fraction bar is a grouping symbol just as parentheses are grouping symbols. Consider the following example: � = 3 + 9 3−1
  • 210.
    What does xequal? 3 + 9 = 12, 3 - 1 = 2, and 12 2 is 6. The fraction bar tells us to evaluate the terms in the numerator and denominator before dividing. But what happens if we translate this into Java? Many people would simply enter: X = 3 + 9 / 3 – 1; JLK Chapter 2 – Introduction DRAFT October 2019 pg. 24 However this is not correct, because division has precedence over addition and subtraction, yielding: 3 + 9 3 - 1, which is 3 + 3 - 1, which is 5. The correct form of � = 3+9 3−1 translated into Java would be: x = (3 + 9) / (3 -1);
  • 211.
    This example showsus that parentheses should be placed around the numerator and the denominators of fractions with operations in them when we are translating the fractions into expressions in Java. In general, if you are not sure what the computer will do first, you can tell the computer what you want it to do first by using parentheses. Note that functions with expressions in the argument of the function will resolve the argument to a single value before invoking the function. For example, in X = Math.sqrt(4 + 20); The computer will evaluate 4 + 20 to a single value before it uses the square root function. Commutative and Associative Behavior Most Java arithmetic operations are commutative and associative in the same manner as their counterparts in elementary algebra. Commutative means two operands can exchange positions and the result of the operation is the same; in other words, the order of the operands does not affect the result. (A+B = B+A) Addition and multiplication are commutative, subtraction and division are not. The order of the
  • 212.
    operands in subtractionand division (including the modulus operation) affects the results. Even when the operation is commutative, computer programmers should still try to be consistent in the order in which they use operands. This is related to Crewton Ramone’s corpulent midget rule. 2 Carpenters always specify length, then width, then height when listing dimensions. Even though W x L is the same as L x W, if a carpenter gets the numbers in the wrong order on a job site, we could end up with a door for corpulent midgets ( 3 feet high and 7 feet wide instead of 7 feet high and 3 feet wide). The order of two values might make a difference in how a person interprets the data, even when it doesn’t make a difference in the result of a commutative operation. Associative means that if the same operation is used several times in a row, such as A+B+C, then it does not matter which operation is performed first: (A+B)+C = A+(B+C). Java is left associative, meaning that it will perform A+B then add the result to C, but if B+C were added to A, the result would be the same. Addition and multiplication are associative, but subtraction and division are not.
  • 213.
    2 Crewton Ramoneis a math educator in Hawaii. See Crewton Ramone’s House of Math, online at: http://www.crewtonramoneshouseofmath.com/ JLK Chapter 2 – Introduction DRAFT October 2019 pg. 25 Type Casting Type casting is the conversion of data from one type to another, according to rules embedded in the compiler. Unnecessary casting should be avoided, because it wastes time during the execution of a program, and could lead to errors. The following code shows examples of type casting: double base = 6.3; double bonus; int result; . . . bonus = 2 * base; // 2 is an int value – type casting will occur bonus = 2.0 * base; // 2.0 is a double value – no type casting occurs result = base; // result is int, base is double. the fractional part of base will be lost.
  • 214.
    In the firsttwo assignment statements, If 2 is used instead of 2.0, the expression casts the type from int to double since bonus and base are double and 2 is an int literal. It is better to use 2.0, a double literal. In the third assignment statement, a double value is being assigned to an int variable. In this case, result will equal 6, and a loss of accuracy occurs. If operands are of different data types, then the computer will attempt to resolve the expression using conversions by type casting. In general: • int values can be cast to double values with no loss of accuracy (only a loss of time). The int value 137 can become the float value 1.37E+02 (equal to 137.0) with no loss of information. • all floating point values cast to any integer type will be truncated, with a loss of information. The fractional portion after the decimal point in the regular (not scientific notation) equivalent of the value will be lost. The double value 4.13297E+03 ( = 4132.97) becomes the int value 4132. • both integers and floating point values can be cast as Strings, in which case they will become the String expression of the characters in the decimal value. 10.75,
  • 215.
    becomes the String“10.75”. The String is the set of characters ‘1’, ‘0’, ‘.’, ‘7’, and ‘5’, not a numeric value. Often this happens in console or file output. Since I/O operations are slow in any case, casting in I/O operations is usually not a big concern in examining the efficiency of a program outputting data. Casting Strings to integers or floating point values can be tricky. There are special methods in the String library to parse numeric values from Strings, which we will study in another section. Converting a value from a data type of greater accuracy and range to a data type of lesser accuracy and range in known as a narrowing primitive conversion. The following are the narrowing primitive conversions in Java: • short to byte or char • char to byte or short • int to byte, short, or char • long to byte, short, char, or int • float to byte, short, char, int, or long • double to byte, short, char, int, long, or float
  • 216.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 26 According to the JLS3, “A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.” Data errors caused by a loss of information from a type conversion, or by mixing up units (such as feet and meters), or by misplaced minus signs, could have serious consequences. Computers are used in important situations – medical systems, antilock braking systems in cars, passenger airplane controls, the military, and so on. We can help save time, save money, and even save lives by minimizing the chances for data errors in software we create. Cast Operators A programmer can force type casting by including a cast operator in an expression before a value to be cast. A cast operator is a data type in parentheses explicitly telling the computer to perform type casting, as in this example. int hours; // hours worked
  • 217.
    double rate; //hourly pay rate double gross; // gross pay . . . // part of the code here is not shown gross = (double) hours * rate; In this case, hours is cast to a double value from and int value before the multiplication is performed because double is used as a cast operator. This prevents a loss of precision in the multiplication operation. CheckPoint 2.3 1. What is on each side of the equal sign in a Java assignment statement? 2. What does the term polymorphism mean in object oriented programming? 3. What does the % indicate in a math expression and what data types work with this operation? 4. What is the difference between the following two statements: a. y = x++; b. y = ++x; 5. convert each of the following to Java assignment statements: a. ��� = � �+� �
  • 218.
    � � variables: doublesum; int a, b, c, d b. � = √�2 + �2 variables: double a,b,c c. � = ��2 variables: double a, r; constant π d. � = �0 � ���(�ℎ���) − 1 2 g �2 variables double y, v0, t, theta; constant g= 9.8 e. ������ = ��������� (1 + ���� � ) � � variables: double principal, rate; int n, t 3 see section 5.1.3 of the JLS, online at: http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls- 5.1.3 http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls- 5.1.3 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 27 Data Streams and System Console I/O In chapter one, we used system console output to display a
  • 219.
    message on acomputer screen. Here we will briefly look at system console I/O in more detail. System I/O uses data streams, also called I/O streams. A data stream is just a sequence of data flowing from a sender to a receiver. Input data streams bring data in from external sources; output data streams send data out to external destinations. Java has a variety of packages supporting such I/O. A raw data stream contains unformatted binary data. A tokenized data stream contains tokens and delimiters. A token is a piece of data. A delimiter is a marker that separates one token from another in a data stream. In most modern computers, a delimiter is a Unicode character or a string of Unicode characters. When a person types a list, for example, commas often are used as delimiters. Java I/O data streams use whitespaces as delimiters. A whitespace is: • a blank space, such as you get by pressing the spacebar (Unicode 0008) • a set of consecutive blank spaces • a tab character (Unicode 0009)
  • 220.
    • a newline(line feed) character (Unicode 000a) • a formfeed (page feed) character (Unicode 000c) • or any of several other technical characters related to file I/O, which we’ll see later. We have already seen the System.out.print and System.out.println statements for sending output to the system console, which is the system’s standard set of input and output devices: System.out.print(“The cursor is on this line after print. ”); System.out.println(“The cursor is on a new line after println.”); A system’s standard output device is usually a display screen. print and println when used with System.out usually send unformatted text data to a display screen. Input is a little tougher because the receiving device for an I/O data stream decides what to do with the data it receives. When we send data out to the console, the operating system decides what to do with the data, so system output is relatively simple, but when data comes into an application, the application needs to decide how to process the data. We need to tell our Java application how to handle the input data stream. There are many ways to do this; one of the simplest
  • 221.
    is using theScanner class. Figure 5 I/O data streams JLK Chapter 2 – Introduction DRAFT October 2019 pg. 28 The Scanner Class A Scanner class object processes an incoming data stream so that data can be put into variables. There are several input methods in the Scanner class that do this. The methods we will use read tokens of data into variables. The chart below describes some of these methods. java.util.Scanner next(): String reads the next token and returns it as a String value nextInt(): int reads the next token and returns it as a int value nextLong(): long reads the next token and returns it as a long value nextFloat(): float reads the next token and returns it as a float value nextDouble():
  • 222.
    double reads the nexttoken and returns it as a double value nextLine(): String reads an entire line and returns it as a String value (A line ends with a new line character.) close() closes the stream associated with the Scanner object The blank parentheses in the chart above indicate methods that do not need a parameter. Except for the close method, the methods are each functions that return a value, whose return type is indicated. To use the Scanner class methods, we must create an instance of the Scanner class by declaring a local variable to be of data type Scanner. The local variable represents the instance of the Scanner class in our method. We can then use the methods from the Scanner class in association with that variable. Scanner kb = new Scanner(System.in); When we use a method from the Scanner class, we use the qualified name of the method, which includes the name of the instance variable and the name of the method. // get the user’s name from the keyboard System.out.println("Please enter your name: ");
  • 223.
    name = kb.nextLine(); Theprintln command before the nextline command prompts the user to enter data. This creates a prompt and capture pair of instructions for user input. The nextline() method returns a String, so we assign the value it returns to a String variable. Most methods that capture data from a data stream work this way. We should also close the Input data stream for this instance when we are done with it. keyboard.close(); The following code demonstrates the use of the Scanner class to capture keyboard input. Note that this example uses the variable keyboard as the name of a Scanner class object associated with an input stream from the standard system input device (System.in). The name keyboard was chosen by the author of the code. It is a variable name that has no special meaning in Java. Many programmers use a simpler name for the same purpose, such as kb.
  • 224.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 29 /* keyboardTest.java * java code for CSCI 111 with a simple keyboard input example. * last edited Dec 21, 2014 by C. Herbert */ package keyboardtest; // one of the following import statements is needed to use the Scanner class import java.util.*; import java.util.Scanner; public class KeyboardTest { public static void main(String[] args) { String name; // String to holds user’s name // create a new Scanner class object, associated with console input Scanner keyboard = new Scanner(System.in); // get the user’s name from the keyboard System.out.print("Please enter your name: " );
  • 225.
    name = keyboard.nextLine(); //echo the name back to the screen System.out.println("Hello " + name); // close input stream keyboard.close(); } // end main() } // end class KeyboardTest Notice the import statements in the code above. An import statement tells a Java compiler to add bytecode from outside of the current source code to the bytecode for the software being compiled. This allows the use of external classes and methods in our Java code. We may import an entire package or import a single class from a package. In this case, we wish to use the Scanner class in the java.util utilities package. The first import statement – import java.util.*; – imports the entire package. The second import statement – import java.util.Scanner; – specifically imports just the Scanner class. Only one of the two is needed, both are included in this code for demonstration purposes. Theoretically, it is more efficient to
  • 226.
    import only thespecific classes that are used rather than importing an entire package. However, most Java compilers are optimizing compilers, which will import the minimum code needed. In this case, the resulting class file is 993 bytes long, with either import statement when compiling this software using IntelliJ Checkpoint 2.4 1. How is a tokenized data stream different from a raw data stream? 2. Describe how to open and close a data stream for console I/O. 3. Which functions from the Scanner class capture tokens into variables of the following types? a. String (single token) b. String (all tokens on one line as one variable) c. int d. double 4. Give an example of an import statement and describe what an import statement does. 5. Give an example of a “prompt and capture pair” of statements for console IO and how it works. Figure 6 console I/O code
  • 227.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 30 Documentation First Programming An important aspect of engineering, including software engineering, is captured in the phrase: “Design it before you try to build it.” Documentation first programming is a simple design-first approach to software development in which we begin by writing comments to describe what the software should do, then create code to do what the comments say to do. We start documentation first programming by developing an outline of what the software should do from the specifications for the software, then we turn the outline into a set of comments. We then use those comments in a Java development project as the basis for the code needed to implement the software. If necessary, we refine the comments as we go along. This section contains a simple example of documentation first programming. In this example, we wish to create software for a simple road trip calculator that will tell us the average speed and gas mileage for
  • 228.
    an automobile journey.The specifications call for a program to: 1. get the distance in miles, driving time in hours, and fuel used in gallons during a long car trip. The data will be input by the user. 2. calculate the average speed (miles per hour), and mileage (miles per gallon) for the trip. 3. display the distance, time, average speed, and mileage for the trip. This is an example of an I-P-O program – Input, Processing, Output – get some input, process the data, output the results. Many short programs fit the I-P-O pattern. It is a simple example of what’s known in software engineering as a design pattern. To create the road trip software using a documentation first approach, we start with an outline: 1. declare variables 2. set up program to read from keyboard 3. get user input a. distance in miles b. driving time in hours c. fuel used in gallons
  • 229.
    4. calculate a. averagespeed (MPH) b. fuel mileage (MPG) 5. output results a. distance and time b. MPH c. MPG Next, we create a set of Java comments matching the outline, or copy and paste the outline into an IDE, refining it into comments as we go along. The result should look something like this: JLK Chapter 2 – Introduction DRAFT October 2019 pg. 31 // Road Trip Calculator // by C. Herbert for CSCI 111 // declare variables – all double // distance traveled in miles
  • 230.
    // total drivingtime in hours // total fuel used in gallons // mileage - average miles per gallon MPG // average speed – miles per hour MPH // declare an instance of Scanner to read the data stream from the keyboard. // get distance in miles // get driving time in hours // get fuel used in gallons // calculate Fuel mileage (MPG) // calculate Average speed (MPH) // print results – distance and time, MPH and MPG // close the input Stream Our next step is to create code to do what each of the comments says to do. Our method might then look something like the code on the next page. An import statement and introductory comments that
  • 231.
    were not includedin the outline have been added to the code. This approach – starting with the documentation – saves work, makes programming easier to understand, and reduces errors. Comments first help us to design the program, then serve to document what we did after we are finished This approach separates the process of designing from building, and is a simple way to design something before you try to build it. It is much better than “cowboy coding”, in which we try to design the software as we code and then add comments later. Many new programming students are tempted to engage in cowboy coding because the first few programs they write are simple and the design is easy, but it is better to develop good programming habits from the beginning. Remember, we’re not here to learn how to write short simple programs, we’re here to learn habits that will serve us well in the long run. Documentation first programming is one step in that direction. Here is an example of the output from the RoadTrip program showing the dialog:
  • 232.
    Figure 7 comments describingcode Figure 8 console I/O output JLK Chapter 2 – Introduction DRAFT October 2019 pg. 32 /* RoadTrip.java * program to calculate average speed and mileage for a road trip * last edited Dec. 26, 2014 by C. Herbert for CSCI 111 * package roadtrip; import java.util.*; public class RoadTrip { public static void main(String[] args) { double distance; // Distance traveled in miles
  • 233.
    double time; //Total driving time in double fuel; // total fuel used in gallons double mileage; // mileage - average miles per gallon MPG double speed; // average speed – miles per hour MPH // declare an instance of Scanner to read the data stream from the keyboard. Scanner keyboard = new Scanner(System.in); // get Distance in miles from the keyboard System.out.println("Please enter the distance (miles): "); distance = keyboard.nextDouble(); // get Driving time in hours System.out.println("Please enter the total driving time (hours): "); time = keyboard.nextDouble(); // get Fuel used in gallons System.out.println("Please enter the total fuel used (gallons): "); fuel = keyboard.nextDouble();
  • 234.
    // Calculate Fuelmileage (MPG) mileage = distance / fuel; // calculate Average speed (MPH) speed = distance / time; // print results - distance and time, MPG and MPH System.out.println("You traveled " + distance + " miles in " + time + " hours."); System.out.println("Your average speed was " + speed + " MPH."); System.out.println("Your mileage was " + mileage + " MPG."); // close the input stream keyboard.close(); } // end main() } // end class
  • 235.
    Figure 9 the roadtrip program chapter file: RoadTrip.zip JLK Chapter 2 – Introduction DRAFT October 2019 pg. 33 Lab 2A – Console I/O: Age in Days In this step-by-step programming exercise we will create a program with console I/O to ask for the user’s name and age in years, then return the user’s name and age in days. We will use 365.25 days per year as a constant value in the code. This exercise includes the use of String and numeric data types, variables and constants, simple arithmetic in assignment statements, and console I/0. The program should: • get the user’s name • say hello to the user by name and ask for the user’s age in years • calculate the user’s age in days • print the results – the user’s age in days.
  • 236.
    STEP 1. Open IntelliJand Start a new IntelliJ Java project named ageDays. If any other projects are open in IntelliJ, use the File menu to close them before continuing. The source code generated by NetBeans will be similar to the source code in Figure 10. Figure 10 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 34 STEP 2. Change the comments in the code as follows: • Remove the comment on lines 14-16 identifying method parameters • Remove the comment on lines 8-11 identifying the author • Change the introductory comment at the start of the source code to include identifying information – the name of the source code file, the nature and
  • 237.
    purpose of theproject, when it was last edited and by whom, as shown in Figure 11. • Add inline comments labeling the ending braces for the method and the class. Your code should now resemble that in Figure 11. STEP 3. Add the following comments to the main method in place of the TODO comment in the main method. // declare variables // user name // age (in years) // age (in days) // constant days per year // declare an instance of Scanner to read the data stream from the keyboard. // say hello to the user and ask for the user’s name // say hello to the user by name.
  • 238.
    // ask forthe user’s age in years // Calculate how many days are in the number of years entered Figure 11 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 35 // print results // close the input stream The code should now resemble that shown in Figure 12. You will need to use the tab key to indent comments properly. When the comments are in place, we can begin to create code to do what the comments say to do. STEP 4. Add declarations to the code as the comments indicate, and remove the declare variables comment: • a String called name for the user’s name,
  • 239.
    • a doublecalled years for the age in years, • a double called days for the age in days. • final double DAYS_PER_YEAR = 365.25; to establish the necessary constant. Figure 12 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 36 STEP 5. Declare an instance of the Scanner class below the appropriate comment: Scanner kb = new Scanner(System.in); Also, add an import statement right after the package directive near the beginning of the code to make this work: import java.util.*; STEP 6. Add code below the comment // say hello to the user and ask for the user’s name to do what the comment says:
  • 240.
    System.out.println("Hello, please enteryour name: " ); name = kb.nextLine(); (Can you figure out why we are using the nextLine() method instead of just next() ?) STEP 7. Add code below the comment // say hello to the user by name to do as the comment says. System.out.println("Hello, " + name); STEP 8. Add code below the next comment to ask for the user’s age in years. System.out.println("How many years old are you ?”); years = kb.nextDouble(); STEP 9. Add code in the appropriate location to calculate the user’s age in days. days = years * DAYS_PER_YEAR; STEP 10. Add code to print the result, in a format similar to this: Joe, you are 9865.75 days old.
  • 241.
    System.out.println(name + “,you are” + days + “days old.”); STEP 11. Add code to close the input stream. kb.close(); STEP 12. Figure 13 on the next page shows the complete program. Build, run, and debug your code as necessary until it runs correctly. Testing reveals the out could look better. Modify the code by adding blank println() commands to separate the different parts of the output, so that it looks something like this: Hello, please enter your name: Joe Hello Joe, please enter your age in years: 27 Joe, you are 9865.75 days old. When your program runs correctly, you are finished with this exercise.
  • 242.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 37 Figure 13 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 38 JOptionPane Pop-Up Dialog Windows The Swing API is one of several used for Graphical user Interface (GUI) programming. It includes the JOptionPane class, which provides a set of objects for complete pop-up dialog windows, such as the message dialog window and the input dialog window shown below: Each window has a title, an icon, a text message, and one or more buttons. A JOptionPane input window also contains a text entry box. The color and style of the pop-up windows depends on settings in each computer’s operating system. You will notice that not all of the windows in the examples in this section have the same look and feel.
  • 243.
    There are fourdifferent types of JOptionPane pop-up dialog windows: • message dialog window – simply displays a text message • input dialog window – gets user input as String • confirm dialog window – asks a question with confirmation buttons, such as yes/no/cancel • option dialog window – a programmable dialog window that can be used for various purposes. In the remainder of this section we will focus on the message dialog window and the input dialog window for use with simple user I/O. More detailed information about JOptionPane pop-up dialog windows can be found on the JOptionPane Class documentation page online at: http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPa ne.html Using the JOptionPane Message Dialog Window JOptionPane has many methods that can be used to create dialog windows for various circumstances. We will use the showMessageDialog() method, which displays a pop-up message dialog window. The specifications for the code are shown by the method header
  • 244.
    from the JOptionPaneclass: static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) The parameters for this method are: • parentComponent – leave this as null for a simple stand-alone pop-up window. The parent component of the window would be named in more complex GUI programming. • message – the message to be displayed in the window. It is most often simply a String message. • title – a String with the title to be displayed in the top of the window. The default is “Message”. http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPa ne.html JLK Chapter 2 – Introduction DRAFT October 2019 pg. 39 • messageType – affects the look of the Window, including which icon is displayed. The JOptionPane class has several messageType constants that can be used: messageType constant Java icon ERROR_MESSAGE
  • 245.
    INFORMATION_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE PLAIN_MESSAGE no iconis shown The default messageType is INFORMATION_MESSAGE, The icon for an information message will be shown by default If you do not include a messageType constant in the parameters. Remember, Java is a multi-platform language; some operating systems will override the Java icons and use their own versions of each icon. • icon – This parameter allows a custom icon to be used. We will skip this for now. The showMessageDialog() method may be used as an instruction in a Java program to create a pop-up message window, since it is a void method that does not return a value. The following examples show
  • 246.
    samples of Javacode and the resulting dialog windows. JOptionPane Import Statement JOptionPane windows are part of Java’s Swing package, used for building graphical user interfaces (GUIs). Their use requires an import statement, such as the following: import javax.swing.*; JOptionPane Example 1 – Default Message Dialog Window In this example, the message is specified and the parameters that follow are not used. The default INFORMATION_MESSAGE icon and title will be shown. // message dialog window with default title and icon JOptionPane.showMessageDialog(null, "This is a message dialog window.nHello World!"); JLK Chapter 2 – Introduction DRAFT October 2019 pg. 40 JOptionPane Example 2 – Plain Message Dialog Window This example includes the PLAIN_MESSAGE parameter with a custom title. No icon will be shown.
  • 247.
    // plain messagedialog window with custom title; no icon is shown in a plain message JOptionPane.showMessageDialog(null, "This is a plain dialog window.", "custom title", JOptionPane.PLAIN_MESSAGE); The same code generated all three windows. the look and feel of each was set by the operating system. JOptionPane Example 3 – Warning Message Dialog Window This example shows a WARNING_MESSAGE with a custom title and warning icon. // warning message dialog window with custom title and the warning icon JOptionPane.showMessageDialog (null, “Warning, danger Will Robinson! Danger!", "Lost in Space Warning", JOptionPane.WARNING_MESSAGE); JOptionPane Example 4 – Error Message Dialog Window
  • 248.
    This example showsan ERROR_MESSAGE with a custom title and error icon. // error message dialog window with custom title and the error icon JOptionPane.showMessageDialog(null,"We need a bigger boat.”, "Jaws Warning", JOptionPane.ERROR_MESSAGE); Using the JOptionPane Input Dialog Window The JOptionPane showInputDialog window will accept user input from the keyboard as a String. There are many variations of this method, but the most straightforward is a question-message dialog with one parameter – the question-message to be displayed in the window. Here is the method header: static String JOptionPane.showInputDialog(Object message); JLK Chapter 2 – Introduction DRAFT October 2019 pg. 41 The method returns a String equal to whatever the user enters in the text entry box in the window. The message parameter is a String, as is the value returned by the method. We use a String variable to
  • 249.
    capture the input. JOptionPaneExample 5 – Input Dialog Window (String input) // input dialog window getting the user's name. The variable must be a String // whatever the user enters will be captured as String. name = JOptionPane.showInputDialog("What is your name?"); This simple, easy to use method works well, but what if we want numeric input? The answer is to use a two-step process: 1. get the user input as a String. 2. convert the String into a numeric value using a parsing method. Parsing Numbers from Strings In linguistics, to parse a sentence means to break the sentence down into its component parts of speech. Compilers do something similar with statements in a programming language, by parsing a statement into its component parts. We can also parse Strings, which is what we will do here. To parse a String is to convert the information in a String, or part of a String, into a value of another data type.
  • 250.
    Java has severalNumber classes corresponding to each of the primitive numeric data types. Each one provides a parsing method to parse a String into the corresponding numeric data type as follows: • static byte parseByte(String) is part of the Byte class • static short parseShort(String) is part of the Short class • static int parseInt(String) is part of the Int class • static long parseLong(String) is part of the Long class • static float parseFloat(String) is part of the Float class • static double parseDouble(String) is part of the Double class Since these parsing methods are each static, they are used with the name of the class, such as Int.parseInt() or Double.parseDouble(). By far, parseInt() and parseDouble() are the most commonly used parsing methods, as shown in the examples below. If a parsing method cannot find a valid numeric representation in the String, the parsing method will create a NumberFormatException, which we learn how to handle later this semester.
  • 251.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 42 JOptionPane Example 6 – Input Dialog Window (double input) // input dialog window getting a double value // first, get a String ageString = JOptionPane.showInputDialog("How old are you?"); //next, parse a double value from the string age = Double.parseDouble(ageString); in Example 6, a JOptionPane input dialog window is used to get user input as a String, then a parsing function is used to parse the String into a double value. Example 7 is similar, except that the input String is parsed to an int value. JOptionPane Example 7 – Input Dialog Window (int input) // input dialog window getting an integer value (image shows user input) // first, get a String answer = JOptionPane.showInputDialog("What is the meaning of life,
  • 252.
    the universe, andeverything?"); //next, parse a double value from the string adamsNumber = Int.parseInt(answer); Input dialog windows are convenient, but they do not take the place of a more complete graphical user interface, which we will study later in a later chapter. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 43 Exceptions When Parsing Numbers from Strings What happens if we try to parse a number from a String that does not have a numeric value? In NetBeans, the exception that is created will cause the program to fail, and we will see an error: Exception in thread "main" java.lang.NumberFormatException: For input string: "nine hundred years old" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecim al.java:1241)
  • 253.
    at java.lang.Double.parseDouble(Double.java:540) at joptionpanedemo.JOptionPaneDemo.main(JOptionPaneDemo.ja va:36) Java Result:1 This message tells us a NumberFormatException was created by the input String "nine hundred years old" in the readJavaFormatString method, called by the parseDouble method, called by the main method in our JOptionPaneDemo program. The first line tells us the kind of exception created. The last line tells us the ultimate cause of the error – line 36 in the method JOptionPaneDemo.main. Line 36 is not wrong, but that is the line which was being executed when the error occurred. This is line 36: age = Double.parseDouble(inputString); The computer could not parse inputString “nine hundred years old”, because it has no numbers to parse. Exceptions are objects, so before learning to handle exceptions in java code, you need to learn more about objects. These topics will be covered later in this course and in Computer Science 112. CheckPoint 2.6
  • 254.
    1. What doesthe JOptionPane class provide? 2. Describe the four different types of JOptionPane pop-up dialog windows. 3. What determines the look and feel of JOptionPane pop-up dialog windows? 4. What datatype does a JOptionPane input dialog window return? 5. Describe how to parse text from JOptionPane input dialog windows into numeric data types. Figure 14 Exception warning JLK Chapter 2 – Introduction DRAFT October 2019 pg. 44 Lab 2B – Pop Up Windows Dialog: Age in Days In this exercise we will modify the code from the ageDays program in Lab 2A to use JOptionPane windows for input and output in place of console I/O. Here is a sample of the I/O from the resulting program.
  • 255.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 45 The new code will have four JOptionPane windows: two message windows, and two dialog windows. The code for the calculation will be in our program between the code segments for the last two windows. The windows shown above resulted from running the code on a Windows 8.1 system. The operating system set the look and feel of the JOptionPane windows. STEP 1. Download and unzip the ageDaysComplete NetBeans project included with the files for this chapter, then open the project in NetBeans. It contains the completed ageDays project from Lab 2A. You should unzip the project folder in a place that will be easy to access from within NetBeans, such as the desktop. The source code for the project is shown in figure xx on page 35. The comment at the top of the code refers to the original code. Change the comment as follows:
  • 256.
    1. delete theword starting on line 3 2. update the date to the current date 3. update the most recent editor’s name to be your name The existing import statement on line 8 is needed for console I/O, but not for JOptionPane I/O. Instead we need an important statement that will enable the use of Swing objects. STEP 2. Replace the existing import statement – import java.util.*; – with an import statement to enable the use of Swing objects: import javax.swing.*; STEP 3. There is no need to declare a Scanner class object in this program. Delete the code in the main method that declares a Scanner class object and the comment above it: // declare an instance of Scanner to read the datastream from the keyboard. Scanner kb = new Scanner(System.in); You should also delete any extra blank lines so the code now looks something like this:
  • 257.
    public static voidmain(String[] args) { String name; // user name double years; // age (in years) double days; // age (in days) final double DAYS_PER_YEAR = 365.25; // constant days per year // say hello to the user and ask for the user’s name System.out.print("Hello, please enter your name: "); name = kb.nextLine(); // say hello to the user by name. System.out.println("Hello, " + name); // ask for the user’s age in years System.out.println("How many years old are you ?"); years = kb.nextDouble(); Figure 15
  • 258.
    JLK Chapter 2– Introduction DRAFT October 2019 pg. 46 Several code segments in the method perform console I/O. Now we need to replace these with code to do the same things using JOptionPane input dialog windows. STEP 4. The first console I/O code segment to be replaced is just below the constant declaration where we find a comment and two lines forming a prompt and capture pair to ask for the user’s name. Replace the two statements for the first prompt and capture pair in the source code with a statement to do the same thing with a JOptionPane input dialog window: name = JOptionPane.showInputDialog("Hello. What is your name?"); This part of the code should now look like this: final double DAYS_PER_YEAR = 365.25; // constant days per year // say hello to the user and ask for the user’s name name = JOptionPane.showInputDialog("Hello. What is your
  • 259.
    name?"); // say helloto the user by name. System.out.println("Hello, " + name); // ask for the user’s age in years System.out.println("How many years old are you ?"); years = kb.nextDouble(); STEP 5. Replace the println() statement that says hello to the user by name with code for a JOptionPane message dialog window to do the same: JOptionPane.showMessageDialog(null, "Hello, " + name + “.”); STEP 6. Replace the prompt and capture pair of statements with a statement to do the same thing using a JOptionPane input dialog window: ageString = JOptionPane.showInputDialog("How many years old are you ?”); Notice that the variable is named ageString. We have not yet declared this variable. The input from a
  • 260.
    JOptionPane input dialogwindow is always a String. We need to declare this variable near the top of the method so that we can use it. We will also need to add code after the code for the JOptionPane input dialog window to parse the String value ageString to the double value years. Figure 16 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 47 STEP 7. Add a statement to the code near the top of the method to declare ageString as a String variable to be used in the method, so that the variable declarations near the beginning of the method look like this: public static void main(String[] args) { String name; // user name String ageString; // age as a String from user input double years; // age (in years)
  • 261.
    double days; //age (in days) final double DAYS_PER_YEAR = 365.25; // constant days per year STEP 8. Add a statement after the code for the JOptionPane input dialog window to parse the String value ageString to the double value age. years = Double.parseDouble(ageString); The input and the calculate segments of the code should now look like this: // say hello to the user and ask for the user’s name name = JOptionPane.showInputDialog("Hello. What is your name?"); // say hello to the user by name. JOptionPane.showMessageDialog(null, "Hello, " + name +”.”); // ask for the user’s age in years ageString = JOptionPane.showInputDialog("How many years old are you ?");
  • 262.
    years = Double.parseDouble(ageString); //Calculate how many days are in the number of years entered days = years * DAYS_PER_YEAR; Next, we need to convert the output from console I/O to JOptionPane I/O. We can also remove the close command leftover from the scanner class, since it is no longer needed. STEP 9. Replace the println() statement showing the result of the calculation with code for a JOptionPane message dialog window to do the same: JOptionPane.showMessageDialog(null, name + ", you are " + days + " days old."); STEP 10. Delete the close statement and the comment that precedes it. Adjust the line spacing as needed. // close the input stream kb.close(); STEP 11. Your program is now complete.
  • 263.
    Test and debugthe project as necessary before closing the project and exiting NetBeans. Figure 17 Figure 18 JLK Chapter 2 – Introduction DRAFT October 2019 pg. 48 Key Terms in Chapter 2 After completing this chapter, You should be able to define each of the following key terms: ad hoc polymorphism, 18 alphanumeric character, 8 ASCII, 7 assignment statement, 17 associative, 24 boolean, 6 built-in data types, 5 byte (data type), 10
  • 264.
    byte addressable, 7 castoperator, 26 char, 7 character, 7 commutative, 24 compound assignment, 20 concatenation, 18 confirm dialog window, 38 constant, 6 data type, 5 declare a variable, 14 decrement, 20 delimiter, 27 documentation first programming, 30 double (data type), 12 final, 15 float (data type), 12
  • 265.
    front loading declarations,15 function overloading, 18 functions, 17 hardcoding, 15 import statement, 29 increment, 19 Input data streams, 27 input dialog window, 38 int (data type), 10 Java identifier, 16 java.lang package, 20 JOptionPane, 38 Keywords, 16 literal, 6 local variables, 14 long (data type), 10 mantissa-exponent format, 10
  • 266.
    Math class, 21 messagedialog window, 38 modulus operation, 19 narrowing primitive conversion, 25 negation, 19 non-numeric characters, 8 null variable, 14 operands, 17 operator overloading, 18 operator precedence, 23 operators, 17 option dialog window, 38 order of evaluation, 23 output data streams, 27 parametric polymorphism, 18 parse, 41 polymorphism, 17
  • 267.
    postfix operation, 20 prefixoperation, 20 primitive data type, 5 prompt and capture, 28 qualified name, 16 raw data stream, 27 reference data type, 5 remainder operation, 19 Scanner class, 28 scope of a variable, 14 short (data type), 10 significand, 10 simple name, 16 String literal, 7 String, 7 token, 27 tokenized data stream, 27 type casting, 25
  • 268.
    unary operation, 19 Unicode,7 UTF-16, 7 variable, 6 whitespace, 27 IntelliJ Notes – Backing Up Project Files The project folder for each NetBeans project contains the files needed for the project. It a good idea from time to time to make a backup copy of the project folder – especially for any important projects and for any projects recently edited. Two copies of any important IntelliJ project should be stored in different locations on different devices to prevent a loss of the project in case of a systems failure. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 49 Chapter 2 - Questions
  • 269.
    1. Why dowe have different data types? How can a programmer determine which data type to use for a variable? What is the range of values for a data type related to? What is the difference between a primitive data type and a reference data type? 2. What data types are built into Java in each of the following categories: Boolean data, numeric data, and text data? 3. What is the minimum storage space needed for a boolean value? Why is a boolean variable in Java stored as a byte rather than a bit? 4. How are integers entered in Java? How are they stored? What special data type does Java have for unsigned integers? What is the only difference between any two of the four integer data types in Java? Which of the Java integer data types is used most often? 5. What formats does Java use to store floating point numbers? What is the accuracy and range of values for Java’s two floating point formats? Which of the two Java floating point data types is used most often? 6. Where can we find out more about data types in Java?
  • 270.
    7. What characterset is used for char and String data in Java? Where can String literals be used in Java? How do we indicate String literals in Java? 8. How is the scope of a local variable determined in Java? 9. How is a constant different from a variable in Java? How are constants declared in Java? When does Java replace constants in code with their values? Why is hardcoding rather than using constants a bad habit to develop? 10. What rules determine how Java identifiers are named? What is camel case? How should camel case be used in naming variables, methods and classes in Java? What is the difference between a simple name and a qualified name in Java? What characters may be used in the names of Java variables? 11. What do we find to the left of the equals sign in a Java assignment statement? What do we find on the right? What will happen if an expression yields a value that is not of the same data type as the variable to which it is being assigned? Why is this a bad idea? 12. What is the difference between an operator and an operand in an expression in Java? What actually
  • 271.
    determines which operationwill be performed in Java expressions? What is this a form of? What operation will be performed on String operands with the plus sign (+) as an operator? 13. What is a narrowing primitive conversion, and why is it such a problem in computer programming? 14. What are the eight arithmetic operations that may be performed on numeric data in Java? Which of these are unary operations, and what does that mean? 15. What is the difference between postfix and prefix increment operations? Illustrate your answer with examples that show the difference. 16. What are some of the methods in the java.lang.Math class, and how are they used in Java programs? How do some of these methods exhibit polymorphism? Where can we find out more about the Java Math class? JLK Chapter 2 – Introduction DRAFT October 2019 pg. 50 17. How is the order of operations determined in a programming language? What is the order of precedence for arithmetic operations in Java? How should fractions with operations in the numerator
  • 272.
    and the denominator,such as � + 3 � − 3 , be entered in Java as numeric expressions to preserve the intended order of operations? 18. Which arithmetic operations in Java are commutative and associative? Which two-operand arithmetic operations are not commutative and associative? 19. How are Java I/O data streams usually organized? What do they use as delimiters? What are some of the Scanner class methods we can use to read data from an I/O stream? What must we do to use them in Java? 20. What is the difference between a message dialog window and an input dialog window? What are the five message type constants used for JOptionPane message dialog windows and what are the icons that go with each of them? Chapter 2 – Exercises 1. Identify appropriate data types for each of the following situations with a reason for your choice:
  • 273.
    a. hours, rate,and gross pay in a payroll program. b. the number of people in each census district; the average number of people in each census district. c. the number of people on a 40-passenger SEPTA bus. The code will run on a small processor embedded in the bus’s electronic passenger counter. d. Serial numbers in a program to keep track of digital recordings. e. each of the following fields in a student data base program – first name, last name, student number, city, state, zip code, major, GPA, currently enrolled? 2. In the following list of variable names, describe which are invalid in Java and why, which are valid but violate programming conventions and why, and which are valid. x, sum, sum1, float, name$, name_42, native, joeSmith, 1root, BattingAverage, status?, GPA 3. Show the output for each of the following: a. [Note: all variables are double – the square root of 10 is 3.162278] num = 10.0;
  • 274.
    square = num*num; sroot= Math.sqrt(num); System.out.println("numbertsquaretsquare root"); System.out.println(num + ”t” + square + ”t” + sroot); JLK Chapter 2 – Introduction DRAFT October 2019 pg. 51 b. System.out.print("This assignment "); System.out.print("is due on "); System.out.print(“September, ”); System.out.println(“8th.”); c. System.out.print("This assignment "); System.out.print("is due on"); System.out.println(“September, ”); System.out.println(“8th.”); d. System.out.print("This assignment "); System.out.print("is due onn"); System.out.print(“tSeptember, ”);
  • 275.
    System.out.println(“8th.”); 4. Rewrite eachof the following formulas as Java assignment statements: a. C = 5 9 (F - 32) Fahrenheit to Celsius conversion b. payment = �� 1−(1+�)−� loan payment (a = loan amount, r = rate, n = periods) c. root = −�±√�2−4�� 2� calculating two roots of a quadratic equation d. dist = √(�2 − �1)2 + (�2 − �1)2 distance from (x1,y1) to (x2, y2) e. haversine = 1−cos (�) 2 haversine function used in maritime navigation
  • 276.
    5. The yardsand feet conversion program in section 2.3 is incomplete. Finish the program and get it to run in NetBeans. Make sure it is properly documented. JLK Chapter 2 – Introduction DRAFT October 2019 pg. 52 I-P-O software A common simple design pattern in programming is input- processing-output (I-P-O). In problems 6 through 10, create interactive I-P-O software that asks the user for some input, processes the data, then outputs the result. You should use variable names that are more meaningful than those in exercise 3, above, or in the formulas below. Use constants where appropriate. Make your output look attractive, useful to the user, and easy to understand. Keep your code readable, easy to understand, and well-organized. 6. World City Temperature Celsius to Fahrenheit Converter Input:
  • 277.
    • ask fora city name • ask for the current temperature in the city temperature in degrees Celsius, using the name of the city Processing: • convert to degrees Fahrenheit using the formula: F = ( 9 5 C) + 32 Output: • a statement of the form: The current temperature in London is 20 ⁰C, which is 68 ⁰F [ Note: the degree symbol is Unicode u00b0 ] 7. Monthly Loan Payment Calculator Input: • the address of the property • the amount of the loan • annual interest rate, (Entered as a decimal. For example, 4.5% is .045)
  • 278.
    • number ofmonthly payments Processing: • calculate the effective monthly interest rate by dividing the annual rate by 12.0 • calculate the monthly payment using the formula in exercise 4b, above Output: • the amount of the loan • the annual interest rate • the number of monthly payments • the amount of each monthly payment [Note: test data – $100,000 at 5% for 30 years is a payment of $536.82] JLK Chapter 2 – Introduction DRAFT October 2019 pg. 53 8. Change for a dollar. Input: • using short integers, ask the user for a number of cents less than 1 dollar
  • 279.
    Processing: • calculate thenumber of quarters, dimes, nickels and pennies in the amount. We do this using the division and remainder operations. Think about how you would do it, then design a program to do the same. How many quarters? How much is left over? How many dimes in that amount, and so on? Output: • a neatly organized statement of the form: 87 cents is: 3 quarters 1 dime 0 nickels 2 pennies 9. Area, Volume, and Surface Area Input: • ask the user to input a distance in inches Processing: • calculate the area of:
  • 280.
    o a circlewith that radius area = πr2 o a square with that side area = s2 • calculate the volume of: o a sphere with that radius volume = 4 3 πr3 o a cube with that side volume = s3 • calculate the surface area of o a sphere with that radius surface area = 4 πr2 o a cube with that side surface area = 6 s2 Output: • an attractive and neatly organized display of the results. 10. Identify five errors in the code on the next page that will stop the program from compiling or running: JLK Chapter 2 – Introduction DRAFT October 2019 pg. 54
  • 281.
    — End ofChapter 2 —