By C. L. Tang and K. A. Larson
Copyright © 2016 by C. L. Tang.
All rights reserved.
Table of Contents
CLASSES AND METHODS
Many programming languages you have heard of are known as high-level. High-level programming languages such as C#, Python, and Java resemble native languages and fall into either of two major categories: object-oriented approach or procedural approach. Java is a high-level, object-oriented programming language. What began as machine and assembly languages (also known as low-level languages) culminated in increasingly more approachable and powerful code.
To write Java applications and applets, you must install the Java Development Kit (JDK). This package includes a Java Virtual Machine (JVM) and the Java Runtime Environment (JRE), both of which are necessary to run a Java program. The Java Runtime Environment consists of useful packages and a java compiler. The compiler translates Java into byte code.
As well, you may find an IDE useful when writing or running your code. IDEs such as NetBeans or Eclipse are considered to be development environments, which also includes UNIX/Linux and DOS environments. Unlike the latter two, IDEs combine the compiler, debugger, and JVM into a single application. Within the development environment, programs can be written into two types of user interfaces: graphical user interface (GUI) or terminal I/O. GUIs are arguably more user-friendly, but terminal I/O is for the most part easier to implement.
This text was designed as a review book, but it can also be used as an introductory complement with another textbook. The rationale behind this book is that we learn by solving problems ourselves, rather than by being told exactly what to do and how to do it. Thus each chapter will contain several exercises of increasing difficulty to be attempted before looking at the source code. Throughout the lesson, we will be able to understand why the code works and to write similar programs using what we have learned. Chapter 1 (Java Basics) covers the proper use of syntax and control statements. Chapter 2 (Classes and Methods) explores the importance of writing methods and explains when and how they should be applied. Chapter 3 (Arrays) introduces arrays and establishes their necessity.
OBJECTS AND PRIMITIVE DATA
Before starting your first programming project, it is important to be aware of comments and white space, both of which are not read by the compiler. So why use them? Comments are used to clarify confusing statements. Likewise, the purpose of white space is to make code easier to understand; it should be used such that the program’s meaning and structure is as clear as possible. For example, indenting helps other programmers understand what you are trying to say when they are reading your code.
There are two data types in Java: primitive data and reference types. Primitive data consist of int, double, char and boolean; reference types include objects and strings. However, only primitive data and strings are literals – they do not change. Thus when the value of a variable is changed, it has in actuality been replaced.
Before using a variable, its type must first be declared. If the variable has not initialized, then its default value is automatically set to 0 or null. Once the variable has been given a value, it acts as a separate entity in which many operations can be performed. For example, casting is a useful way to round doubles. You can cast a variable to a more specific type (for example, from int to double). Variables can also be concatenated, or combined, with other variables. This technique is often used to print the value of the variable or to construct yet other variables.
Keep in mind that Java is case-sensitive, which means that total is different than Total; constants are usually denoted in all capitals. Try to use meaningful names so that what each variable represents is as clear as possible. Also, remember that Java reserved words cannot be used as object names because they already have pre-defined meanings. The following is a list of all the Java reserved words:
The Java standard class library provides pre-written code that can be called at run-time. Packages are a collection of related classes that can be imported to make writing code much more simple and straightforward. To import a specific section or class from a package, you must import the package followed by the section name followed by the class name. You can use an asterisk in place of the class name if you want to import all classes in the package.
One immensely useful class for writing interactive programs is the Scanner class, which allows the user to enter values from the keyboard. The value(s) can then be stored as a variable and be used as seen fit.
Two other useful classes include the Math class and the String class. The Math class allows us to perform basic operations.
The String class, on the other hand, provides several operations that we can perform on strings. Unlike the Scanner class, both the Math class and the String class do not require you to manually import these classes for you to be able to use them.
Loops and conditionals are called control statements. The conditions of control statements are boolean expressions, meaning that they are either true or false. If the condition is true, the statements in the body are executed; if the condition is false, the statements in the body are skipped.
Java provides three logical operators that produce boolean results. The logical AND operator (&&) is true if both operands are true, and false if one or both of the operands are false. The logical OR operator (||) is true if one or both of the operands are true, and false if both operands are false. The logical NOT operator (!) simply inverses the boolean value.
If statements and if-else statements are called conditionals, and are useful when you want to perform a specific action given that the contingency is true. If-else statements are extensions of if statements in that they provide an alternative if the condition is false:
Similar to if statements and if-else statements, loops execute if their condition is true – the most apparent difference is that they keep executing until they are false. A loop has 4 components: initiation, body, update, and termination. There are two types of loops you should be able to use interchangeably, the while loop and the for loop.
You can use either the while loop or the for loop in the same situations – both essentially perform the same things in different ways. To exit a loop before the condition is false, use the break statement. This is mostly used to construct efficient programs, such as if the target of a given list has already been found, then the rest of a list does not need to be checked.
It is also good practice to use <, >, <=, or >= than or != to minimize the probability of off-by-one errors and infinite loops. Use .equals() instead of to compare strings.
You may nest control statements if you want to check yet another condition given that the initial condition is either true or false; nested statements work in much the same way. However, keep in mind that whenever you nest if-else statements, each else matches with the nearest unmatched if.
In addition, although you may drop the braces if the body of a conditional or a loop consists of a single statement, using braces is good practice since it minimizes unintended errors.
Earlier in the chapter, we discussed the Math class and the String class. Another class, the Random class, is useful for generating random numbers.
You may need to construct a counter within your program to keep track of the number of iterations. Fortunately, this is relatively easy to do. You can initialize a variable and increment it as necessary.
The following chart lists some essential Java operators and their precedence.
WHAT IS A CLASS
When you write a program, you are compiling code in classes. Classes define methods. A method is a collection of statements that allow a program to be more efficient by preventing you from having to write the code over and over again. All programs must have a main method in order to execute – this is always found in the main class. In this chapter, we learn how to write our own classes; unlike the previous classes we have utilized, the Coin class and the MDAS class are not part of the Java standard class library.
STRUCTURE OF A CLASS
Local variables act within a method, and cannot be used anywhere else; instance variables are used throughout the class. Null variables do not reference anything.
Constructors allow us to initialize instance variables. They are of the same name as the class itself, but do not have a return type. If you do not define a constructor when writing your code, a default constructor will be assigned that does not take any parameters.
The types and the number of parameters must correspond with those in the method that you want to call. When a method is called, the code within the method is executed; then the program continues where it left off. For now, you can see calling methods as a shortcut to more code.
It is important to keep in mind that the reference to an object is passed to the method, not the object itself. If the visibility of a variable or method is assigned to be public, it can be accessed outside the class; on the other hand, if the visibility is assigned to be private, the variable or method can only be used within its own class. Because of this, private methods are also known as support or helper methods because they assist other methods in their class. Usually, the message of a variable or method is sent to the object, unless the keyword static is applied, in which it is sent to the class instead. The return type specifies what is returned by the method (for example, int returns an integer, void returns nothing), but is not part of the method signature. It should be the last line of the method.
As an example, let us analyze the main method. Its visibility is public, which means that any object can call it. Its message is sent to the class, since it is static. Its return type is void, indicating that it does not return a value. And its parameter is an array of String objects.
INTRODUCTION TO ARRAYS
Objects and primitive data can be easily managed through arrays. Arrays can be seen as lists; it holds data in much the same way, and can thus be accessed as such. Like variables, arrays can also be initialized immediately after instantiation.
Elements in an array are referred to by their index, or position. For example, array0 is the first element in the array; array1 is the second element in the array; and so on. However, all elements in the array must be of the same type. Since arrays are objects, if the array has not been initialized, its elements are 0 or null by default. We can find the size of an array by writing
Fortunately, you can apply an if statement to prevent an out-of-bounds exception. You can use either a for loop or an enhanced for loop to go through the array. An enhanced for loop is essentially the same as a for loop except that the increment has already been set to 1. Keep in mind that the variable in an enhanced for loop is the same as the type of the array. Do NOT use an enhanced for loop if the array is not full.
Parallel arrays are simply two or more arrays that correspond with each other. Parallel arrays are used to record respective elements by taking advantage of the same positions within the arrays.
Just as one-dimensional arrays can be seen as lists, two-dimensional arrays can be seen as tables. Nested for loops can be used to set and return array values in two-dimensions. You can call an element in a two-dimensional array by writing
When looking for a target in a given array, we can choose to use either linear search or binary search. Linear search goes through all the elements in the array (from the first element to the last), while binary search starts at the middle and “halves” until it finds the target. In general, binary search is faster than linear search, but it only works if the array is sorted. Fortunately, the Arrays class offers the method Arrays.sort that automatically sorts the array alphabetically and from smallest to largest.
The Arrays class also consists of a toString method that allows the user to display the array.
Many programming languages you have heard of are known as high-level. High-level programming languages such as C#, Python, and Java resemble native languages and fall into either of two major categories: object-oriented approach or procedural approach. Java is a high-level, object-oriented programming language. What began as machine and assembly languages (also known as low-level languages) culminated in increasingly more approachable and powerful code. This text was designed as a review book, but it can also be used as an introductory complement with another textbook. The rationale behind this book is that we learn by solving problems ourselves, rather than by being told exactly what to do and how to do it. Thus each chapter will contain several exercises of increasing difficulty to be attempted before looking at the source code. Throughout the lesson, we will be able to understand why the code works and to write similar programs using what we have learned. Chapter 1 (Java Basics) covers the proper use of syntax and control statements. Chapter 2 (Classes and Methods) explores the importance of writing methods and explains when and how they should be applied. Chapter 3 (Arrays) introduces arrays and establishes their necessity.