CISC 1115
Introduction to Programming Using Java
Lecture 2
Basic Concepts / Basic Java
Reading from the Text
Chapter 2
- Sections 2.6 and 2.7 deal with floating point type and the rounding errors they can cause
Appendix A
- The text uses Dr Java as their IDE. There's no harm in reading it; it presents many concepts
and aspects of an IDE that is applicable to IntelliJ as well. However, don't get hung up on
any of it — if you're OK developing and running your program, you're fine.
- Software development
- Literals
- Variables
- Types
- Declarations
- Initialization vs Assignment
- Constant
- Expressions
- Comments
What You're Going to Learn in this Class
- Problem Solving
- Critical Thinking
- Elementary Java
Software Development: Some Basic Terminology and Concepts
Problem Statements
Let's look at a variation on the Hello World program:
Write a program that prompts the user for their first name and displays a welcoming message to the screen.
- The above is called a problem statement.
- Problem statements are typically presented in informal language (i.e.,
English, not code)
- However, the statement must be precise in order for the programmer to be able
understand what is expected of them
- Notice I specified the first name (as opposed to their last name, or full name)
- The level of precision may depend on the actual needs of the entity making the problem statement:
for example if you were to submit to CodeLab, you would need the exact text of the welcoming message;
if it was just an informal exercise, you could get away with anything that seems welcoming and
contains the name.
Developing an Algorithm
- The programmer must then create a step-by-step solution to the problem
- This is known as an algorithm
- It is this step where the problem-solving and critical thinking come into play
- The problem solving is to be able to take the problem an produce the algorithm
- The critical thinking is to have a sense of the issues one will face as well as
deciding whether one's solution is indeed a solution
- The eventual goal is to have a computer carry out (execute) the
steps of the algorithm
- The above example has a trivial algorithm:
- Prompt for and read the name
- Display the name with a welcome message
Implementing the Algorithm: Programming Languages
- Once an algorithm is constructed, the programmer implements the
algorithm in a programming language, i.e., transforms it into a
formal written specification in a language suitable (directly or indirectly) for
being run on a computer.
- A programming language is a language that is conducive to being read by humans,
but is also formal enough to provide precise specification of algorithms
- In other words, it is a way of writing precise instructions that is at the same
time meant to be read by people.
Source Files and Editing
- The file containing the text of the algorithm written in the programming language is called a
source file, and we speak of the (program) text as source code
- Java source files usually have a single class within them, and have the same name as the class with a suffix of
.java
; e.g. if we name the class of our Hello World program HelloWorld
, it would
reside in a file named HelloWorld.java
- The source file is created and subsequently modified (edited using a program known as an editor)
Compilation
- While the source file is human-readable, it is not conducive (nor efficient) for execution; rather
the source file is translated into another target language suitable for execution by the machine.
- The process of translating the source language to the target language is known as compilation,
and is carried out by a program (piece of software) known as a compiler
- In many cases, the target language is the actual language of the computer's
hardware (known as the hardware's instruction set), and thus is called machine language
- The resulting file containing machine language is called an executable file
- For Java, the source code is compiled into a language known as byte code and
is stored in a file known as a class file (because our Java source files contains classes
and each class is compiled to one of these files).
- Class file names typically match the source file name but end with the suffix
.class
rather than .java
; e.g. HelloWorld.class
Execution and Interpretation
- Once one had produced the executable or class file, one can execute the program
- An executable file can be run directly on the hardware (this is essentially what happens when you run Word, a video editor,
and many other programs; i.e., you double click the icon on the desktop, or select the program from a menu or directory.
- For Java, the class file does not run directly on the hardware; rather it is run by yet another piece of software,
know as the Java interpreter. This piece of software creates a virtual machine,
a simulation of a machine in software. For Java, this machine is known as the Java virtual machine — JVM,
and this software-based 'machine' views the byte code in the class file as its machine code.
- The process of running on a virtual machine is strictly called interpretation;
i.e., the interpreter program is interpreting the byte code instructions as if they were
hardware instructions; we often loosely refer to this as execution as
well.
Testing
In production programming environments, all the above is a small part of the software development process; the major portion — by far —
is the testing and subsequent debugging (finding and repairing errors) phase.
- testing is performed at many levels and in many ways:
- individual components (methods), classes and full applications all require testing, and the testing at each level
is different in nature
- testing is also done by the programmer, their immediate team, and typically a QA team
- testing can be performed by eyballing the code; i.e., reading it over and looking for problem,
running the code on various test cases, and using special software created specifically for the purpose of code-testing
Debugging
Once an error has been detected, the programmer must determine the exact nature of the error, what part of the system is causing the error, and how to
fix it There are standard techniques and tools to aid the programmer in this task:
- diagnostic prints: the programmer places print statements ate strategic points in the program in
an attempt to determine what is going wrong.
- the programmer uses a debugger that permits them to step through the program and examine the contents of memory.
If the debugger is able to display the names (i.e., symbols) of the variables (to make it easier for the programmer to examine them), it is called a
symbolic debugger.
- Debuggers vary widely in capability and the support they provide to the programmer
Integrated Development Environments (IDE)
The above steps: editing, compiling, executing, testing, debugging, were all traditionally handled using separate tools. Eventually,
as the sophistication and complexity of software evolved, these tools were combined into a single software development tool
known as an integrated development environment or IDE. Examples of IDE's are:
- IntelliJ
- Eclipse
- NetBeans
- Dr Java
- Code::Blocks
The first three are industry-level development environments, Dr Java is aimed at students beginning in Java, and Code::Blocks is
somewhere in between (and mainly for C++).
Basic Imperative Java
Lecture 1 was a whirlwind tour of the basic elements of computation: imperatives, conditionals, and iteration. In the process,
a number of specific language elements were introduced. We present, elaborate, and expand on the imperative aspects in the rest of this lecture.
Basic Programming Elements
Programming involves sequences of the following three operations:
- Actions or imperatives
- Decisions or conditionals
- Repetition or iteration
Anything that can be computed can be represented as a sequence of the above three
Organizational Elements
As the program sequences get larger, they require organizational techniques for them to be comprehensible
and maintainable by human programmers.a The two basic organizational elements are:
Methods
Methods are sequences of code typically comprising a subtask. They are the 'atomic' building block of
program organization in Java.
- As the representation of a subtask, a method can be called or invoked,
i.e., one can initiate the performance of the subtask by name.
- As an example,
nextInt
is a method of the Scanner
class. Once calls
nextInt
by writing: scanner.nextInt()
- The exact details of the rest of that code fragments, i.e., the use of
scanner
as well as the .
, and ()
's will be explained below.
Classes
Classes consist of methods and data (typically variables) that are logically related. They are the
basic unit of organization in Java.
- For example, the
Scanner
class is a set of logically-related methods who purpose is to
provide the functionality of reading input.
- Classes are used to create object or instances of the class
- We create such object using the
new
keyword followed by the name of the class, followed
by optional additional information necessary for the creation.
- For example, to create a
Scanner
object capable of reading input from the keyboard,
we write:
new Scanner(System.in)
the System.in
is additional information supplied to the creation process informing it
that the input is to come from the keyboard.
Basic Program Structure & Boilerplate
Java programs are composed of classes working in unison; each class consisting of (as mentioned above) methods and possibly
data/variables.
Indentation
Indenting the various levels of our code provides a logical structure for the human reader; without it, program code
would quickly become impossible to comprehend.
- In our boilerplates above, we see that a class is composed of methods (and data). Each method is indented relative to the class header.
- In turn, the method body is indented relative to the method header
- We will see further indentation in the context of conditionals and loops.
public class ClassName {
public static void main(String [] args) {
…
…
if …
…
else
…
…
…
for … {
…
if …
…
else
…
}
…
}
}
Imperative Java
The imperative (actions) portion of Java consists of statements instructing the machine:
- calculate this expression
- test this condition and then do this if the condition is true
- repeat this body of code if this condition is true
- declare this variable
Literals
- An entity whose value is literally what it is written as
- Integer, string, floating point
0
, 15
, "Hello"
, ""
, 1.5
, 3.14
Variables
- Location in the memory of the computer that can contain a value
- Associated with a variable is it's name, known as an identifier
- Identifiers:
Types
- Specifies the set of values a variable can contain
int
, String
Arithmetic Expressions
- The basic arithmetic operators are
+ | addition
|
- | subtraction
|
* | multiplication
|
/ | division
|
- The symbol
*
is used as the multiplication operator —
we need x
for the symbol representing the 24'th lowercase letter of the alphabet.
*
and /
have higher precedence than +
and -
and there are always parentheses for overriding that precedence
- e.g.
a + b / 2
vs (a + b) / 2
- There is also a modulo (remainder) (
%
) that we will introduce later
The String +
(concatenation) Operator
- Multiple values to be sent to
System.out
may be concatenated using the
(String) +
operator
- If one of the operands of a
+
operator is a String (a) the operator is a concatenation operator (and not an
addition operator), (b) the other operator is turned into a String (if it isn't one already)
Expressions
An expression is a sequence of symbols and values that are evaluated into a result value:
3 + 5
evaluates to 8
x * y
evaluates to the product of the values contained in the variables x
and y
z == x + 1
evaluates to true if z
is equal to the value contained in x
plus 1
- Operators, operands, evaluation (result/value of an expression), subexpressions
- operands are the values manipulated (by operators)
- literals, constants, variables, results of method calls, subexpressions
- operators are typically symbols that act upon their operands
- In the above terms, an expression is a sequence of one or more operands with their operators
x + 1 * y
- expressions are evaluated and the result is called the value of the expression
- subexpression is an expression within a larger (surrounding) expression
a * b + c
- a subexpression is usually an operand of an operator of the larger expression
- In the above example
a * b
is a subexpression, and is the left operand of the +
operator
Integer Division
If both operands are integer, the result if an integer as well, and the division performed is integer division,
i.e., any fractional portion is truncated (discarded).
- This is why
(88+91)/2
evaluates to 89
- This is not an error, rather it is the semantics of integer division
P02.2 — Integer Division
Write an application that illustrates the truncation caused by integer division.
1. public class IntegerDivision {
2. public static void main(String [] args) {
3. System.out.println("30/3: " + 30/3);
4. System.out.println("10/3 + 10/3 + 10/3: " + (10/3 + 10/ 3 + 10/ 3));
5. System.out.println("1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3: " +
6. (1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3));
7. }
8. }
30/3: 10
10/3 + 10/3 + 10/3: 9
1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3: 0
- The expression in line 3 is an even divide of
30
by
3
- Line 4 performs a mathematically equivalent expression; however in this case, each of the
addends of the sum is an unevenly divided value (i.e., results in a fractional result). As
the fractional portion is truncated (i.e., the remainder is discarded, the result of the sum
is less than the original (line 3) expression.
- Line 5 is the extreme case - again, mathematically equivalent, but this time each operand results in
0, and thus the entire expression evaluates to 0.
Floating point
So named because the decimal point can 'float' among the digits; i.e., it is not in a fixed position
double
, float
- When is floating point appropriate?
- Integer, floating point, (fixed point), and mixed mode arithmetic
- floating point literals
- Back to semester average problem
- counting (integers/exact number) vs measuring (floating point/approximation)
Declarations
Getting Values into Variables: Initialization & Assignment
Initialization
- A variable may be given an initial value when it is declared:
int x = 12;
String word1 = "Hello", word2 = "Goodbye";
- Initializations may also be expressions (of already declared and initialized variables):
int num1 = 13, num2 = 15;
int average = (num1 + num2) / 2;
System.out.println("The average of " + num1 + " and " + num2 + " is " + average);
Assignment
- Following its declaration, the value of a variable may be modified using the assignment operator
int x = 12;
int y;
y = x;
System.out.println(y); // prints 12
- The value on the right-hand side of the
=
is assigned to the
variable on the left-hand side.
- The value in the left hand variable prior to the assignment is overwritten as a result of the assignment
- The right-hand-side (RHS of the assignment can be any expression; the left-hand=side (LHS)
must be a variable.
- An equivalent version of the above
num1
, num2
, and average
example using assignment:
int num1, num2;
num1 = 13;
num2 = 15;
int average;
average = (num1 + num2) / 2;
System.out.println("The average of " + num1 + " and " + num2 + " is " + average);
- Initialization may be used if the value of the variable is known at declaration time
- After the declaration, assignment must be used.
Statements
- Statements are the basic units of execution
- Unlike expressions, statements do not result in a value
- Some statement contain other statement, e.g. the
if
statement, and the for
statement
- As a general rule statements that do not contain other statements end with a semicolon (
;
); those that DO contain other statements do not
Method Calls
The line System.out.println("Hello world!");
consists of a statement
that displays/prints the text Hello world
(without quotes) on the screen.
System.out
is a pre-defined object representing the screen
- By pre-defined, we mean something that has been provided for you by the system
- The code
println("Hello world!")
is a message we are sending to the
System.out
object, requesting it to display the text Hello world
- A message consists of a name (
println
), followed
by the contents of the message ("Hello world!"
), known as the arguments.
- In this message there is only one argument
- The
println
message requests that the argument be displayed on the screen
- The screen is properly known as the standard output
- (The keyboard is known as the standard input; we'll introduce it later)
- We would thus say: The
println
message with the argument "Hello world!"
is being sent to the object System.out
- The text is enclosed within quotes (
"…"
) to allow us to determine where it begins and ends ("Hello world!"
vs
" Hello world!"
vs " Hello world! "
)
- Statements in general are terminated with a semicolon (
;
)
Screen (Console) Output
Keyboard (Console) Input
- pre-defined keyboard object
System.in
, analogous to System.out
- requires a bit more work to use than
System.out
:
- A
Scanner
object must first be created, and then THAT is what we send messages to:
import java.util.*; // At top of source file -- more boilerplate required when using Scanner
…
…
Scanner scanner = new Scanner(System.in);
- Note this is our first example of an object that is NOT pref-defined — rather we are creating it
- Messages that can be sent to
Scanner
objects:
nextInt
— // retrieves the next value typed in at the keyboard (must be an int)
next
— // retrieves the next value typed in at the keyboard
int x;
x = scanner.nextInt(); // takes the next value typed in at the keyboard (must be an int) and places it into x
String s;
s = scanner.next(); // takes the next value typed in at the keyboard (a string) and places it into s
Put together, the following is the basic pattern for obtaining data from the keyboard
import java.util.Scanner; // at top of source file … before class header
…
public class … {
public static void main(String [] args) {
…
Scanner scanner = new Scanner(System.in);
…
… = scanner.next(); // or nextInt
…
}
}
A Comment About Comments
- Comments: why, where, and how
- 'Useless' comments
Adding Some Additional Features to our Grading Program
What we're going to spend our time on:
- Want to be able to assign a letter grade based on average
- Need to be able to make decisions (if the average is greater than 90, the grade letter is an 'A')
(conditionals)
- How about a weighted average: project 20%, midterm 30%, final 50%
- More elaborate arithmetic (no longer simply add and divide by 3)
(precedence, additional arithmetic operators)
- How about class average, highest grade in class, lowest grade in class
- More decisions (is this grade the largest so far?) (cascaded/nested conditionals)
- Need some sort of memory to keep running totals, or highest grade so far (variables)
- Enough of these things to remember, it would be better to recall them by a name than a memory number
- 20 projects-- project average is the average of the highest 10 that were submitted on time
- More complicated decision making (switch/logical operators)
- Group of projects (arrays)
- Wife wants to help-- give her this subtask to do while I do something else (methods)
- Add student id and email address to roster
- Notion of the set of data associated with a particular student-- student data now in individual folders
(classes)
The Essentials
- Manipulating values (calculations)
- Numbers: arithmetic operations and expressions, various mathematical functions (e.g. absolute value)
- Strings: string operations and expressions: extracting specific characters or sequences of characters; combining strings
- Making decisions (conditionals)
- Are two values equal? Are we finished reading data? Is a number even? Does a string contain a vowel? Is a number a prime?
- Repeating actions (iteration)
- Calculate grades for 10 students; calculating grades for 100 … 1,000 … 1,000,000 students; read in addresses until an address
outside of New York is encounter.
- Dividing up a problem into simpler, individual task (methods)
- Grade calculations as:
- read in grades
- calculate average
- calculate letter grade
- print result