CISC 1115
Introduction to Programming Using Java
Lecture 1
A Whirlwind Tour of Basic Java
What is Programming?
We want to develop a mechanism that allows for the specification and development of algorithms that can be performed by a machine
- computer: a machine capable of carrying out a sequence of operations (typically arithmetic and logical)
- arithmetic and logical because that was the motivation for calculations: census tables, ballistic trajectory tables for canon,
nuclear reaction calculations, etc
- As it turns out ALL computer-based calculations (including sound, image, video, etc) reduce to arithmetic and logical operations
- The original use of the word computers was for humans … Computer (Occupation
- programming: the act of specifying a sequence of actions/commands to be carried out/executed by a computer
- program: a sequence of such commands
- A program is also sometimes known as an app
- programmer: a person trained in the field of programming
An Overview of the Programming Process
We will see there are three basic types of operations required to carry out any task:
- Actions (imperatives)
- Decisions (conditionals)
- Repetition (iteration)
Examples
- Making an omlette:
- Breaking the eggs: action
- Beating the eggs: repetition together with decision (when is it enough)
- Heating the pan: action together with a decision (hot enough)?
- Adding the eggs to the pan: action with repetition and decision (keep pouring until cup is empty)
- Stir eggs until set: action (stir) repetition with decision
- Add cheese: action
- flip out of pan: action
Notice that the lines between the three basic types of operation are blurry (e.g., we can think of stirring the eggs as an action composed of a simpler action -- a single rotation of the fork
repeated over and over again).
Algorithms
An algorithm is a step-by-step solution to a task problem
- Examples
- the above omlette recipe
- calculating your GPA
- determining youngest person in class
Specifying Computer Algorithms
We want to be able to specify algorithms that a machine will perform for us.
Unlike a person, a computer cannot fill in missing details, resolve ambiguities, or decide for itself what we probably meant.
We therefore need a formal mechanism for specifying exactly what we want the computer to do. That mechanism is a programming language.
- A programming language is a language that allows to specify algorithms in a manner that can be carried out by a computer
What We Need from a Programming Language
If a programming language is to let us specify algorithms that a computer can carry out, what must it provide?
- Our instructions must be:
- Unambiguous
3 + 4 * 7 … how do we calculate this expression?
- we can't permit multiple plausible meanings
- Precise
- Print the student's GPA … to haw many places?
- we must know exactly what to do
- The above two are quite similar; don't worry about the exact distinctions; the important thing is both properties
are required if we're going to write programs that do exactly what we want them to do
- We need to be able to specify:
- Steps performed in sequence
- Decisions about which steps to perform
- Steps that are repeated
These are the essentials. Programming languages provide many other features
that help us write programs that are clearer, easier to maintain, and able to
grow as the problems we solve become larger.
There have been many such programming languages developed over the decades; the one we will be investigating is Java.
- Why more than one language developed; their differences, and their evolution is the subject of later courses, on p[articular a course in programming language history and design.
A Quick Introduction to Java
Basic Java Program Structure
Java programs have a basic common structure; every program (at least in this course) will have a similar layout and common text:
1. public class <ClassName> {
2. public static void main(String [] args) {
3. …
4. }
5. …
6. }
- All Java programs (at least in this course) will follow the above pattern.
- ClassName is a description in that it
describes what goes in that location (rather than being the actual text that will go into that location.
- For the program, it would the notion of a 'class'; 3115 is where you learn about it in detail
- We will also learn more about the actual meaning of this common structure
- The …'s represent locations in the program where we will put our sequence of operations
- Initially, we will place instructions only at the location of the first …;
eventually we will use the second location as well.
- The rest of the text is always present in exactly that form (at least for our programs in 1115); we call such fixed text
boilerplate
- The line public class <ClassName> {
is known as a class header and the code between the method header and the corresponding closing }
(on line 4) is called a class
- The line public static void main(String [] args) {
is known as a method header, and the code between the method header and the corresponding closing }
(on line 6) is called a method
- We'll have more to say about these two down below and in subsequent lectures
- Take note of the indentation; Java programs have a specific format, much like essays
- We will have much more to say about that as we proceed
The Simplest Possible Java Program (App)
The simplest legal Java program does nothing … it consists of the above boilerpolate and nothing else; all that has been added is an actual class name:
Write a program that does nothing except contain the required boilderplate; i.e., the empty program
public class EmptyApp {
public static void main(String [] args) {
}
}
- This program does absolutely nothing — there is no output
- we've included it simply to show the minimal working program, and to show how to provide the program (application) name
- In this case the name is (appropriately) EmptyApp
- In general, the above is how we will present programs in these notes:
- Instructions / Statement of the problem
- This will always be present
- the code
- optional input to the program
- the output
- various explanatory notes
A More Substantial Program
Write a program that displays the text Hello world on the screen.
- Again, we will always be providing instructions (statement of the problem) for our programs
- The level of precision will depend on the problem and what we expect our output to be
public class HelloWorld {
public static void main(String [] args) {
System.out.println("Hello world");
}
}
Hello world
- The statement
System.out.println("Hello world");
causes the text Hello world to be displayed on the screen
- We will have more to say about
System.out.println after our introduction
- Statement are the actions of the program; again, we will have more to say about them later.
- We named our program
HelloWorld because that is what it does … prints "Hello world" to the screen.
A Program with a Calculation
We will introduce each of the above categories (actions, decision, repetition) individually, in programs of increasing
functionality.
- We will use grading as a unifying theme for the programs.
Write a program that calculates the average of a midterm grade of 78 and a final exam grade of 86.
public class ExamAverager {
public static void main(String [] args) {
System.out.println((78+86)/2);
}
}
82
- operators — such as
+ (addition) and / (division)
are symbols that accept operands (values), and produce a result (the sum for addition,
and the quotient for division).
- The four basic arithmetic operators are
+, -, *, /
- As these operators accept 2 operands, the are callled binary operators
- Note the use of parens (
()'s);
- the usual rules of precedence apply (
*, / before +, -)
- parentheses for overriding.
- Unlike our recipe this program does not contain any decisions or repetition, only actions (the arithmetic calculation).
Making the Output More Readable
We'd like to add some descriptive text to out output to let the user know what they're looking at:
Write a program that calculates the average of a midterm grade of 88 and a final exam grade of 92 for the student Gerald Weiss and prints out
the result together with some descriptive text.
public class ExamAverager {
public static void main(String [] args) {
System.out.println("Gerald Weiss received an 88 and a 92 for an average of " + (88 + 92) / 2);
}
}
Gerald Weiss received an 88 and a 92 for an average of 90
All we've done here is add some descriptive text to the println
When at least one of the operands of + is a String, the operator
is called the concatenation operator.
The action of the concatentation operator is to textually join the first and second operands
- For example,
"Hello " + "world" results in "Hello world" (notice the trailing blank at the end of the string "Hello ".
- If one of the operands is a string and the other is something else (right now, the only other thing we have is a number), the
number is treated as text, and concatenated to the string. Some examples:
"The number is " + 15 produces "The number is 15"
"The average is " + (2+4)/2 produces "The average is 3"
"The sum is " + 2 + 4 produces "The sum is 24"?!
- This last example shows us we need to be careful about using parentheses when concatenating
Adding a Decision (Conditional)
Let's add an example of the second category of operations: decision-making.
Write a program that calculates the average of a midterm grade of 88 and a final exam grade of 92 for the student Gerald Weiss, and prints
whether the student has passed or failed the course based on a passing grade of 60.
public class ExamAverager {
public static void main(String [] args) {
System.out.println("Gerald Weiss received an 88 and a 92 for an average of " + (88 + 92) / 2);
if ((88 + 92) / 2 >= 60)
System.out.println("Gerald Weiss passes");
else
System.out.println("Gerald Weiss fails");
}
}
- A conditional is introduced with the word
if
- We will have more to say later on about words in Java with special meaning
- The
if is followed by a condition — an expression that evaluates to true or false
- In our example it is the expression
(88 + 922 / 2 >= 60)
- The condition of the conditional is always enclosed in parens (
()'s)
- The condition typically contains an equality or relational
operator
- The equality operators are :
== and !=
- The relational operators are:
<=,>=,
<, >
- For most practical purposes we think of equality and relational operators in the same way, i.e. an operator that
results in a true/false)
Gerald Weiss received an 88 and a 92 for an average of 90
Gerald Weiss passes
Introducing Variables and Types
In the above code, all the values are hardcodedi; i.e., the actual values are written directly into each statement that uses them.
This has several drawbacks, each of which points us toward the same solution.
Avoiding Redundant or Repetitious Values
- The above program repeated the student's name, as well as the values of the exams.
- Making a typo would result in us using one value in one place and a different one elsewhere
- For example, misspelling 'Gerald' in one of the prints, or typing '80' in one place
and '88' in another would produce inconsistent and thus incorrect output.
- Similarly, we wrote the expression for the average twice, again inviting the possibility of
making a mistake with one of them, producing inconsistent and incorrect results.
Allowing Different Names and Exam Values
The above program only provides information for a student named Gerald Weiss who received exam grades of 88 and 92.
- We typically want to be able to perform the above calculations on on other students with different exam grades
- As an aside, the conditional is almost silly if it is only applied to the grade of 90; in that situation, it will never
print
fails.
We might simply want to be able to quickly change the name and grades and run the program again.
- If the values are hardcoded AND repeated, this quickly becomes a nuisance
- We also might eventually want to run this program once on many successive names and grades; this can't be done with hardcoded values
Making the Code More Readable
Looking at the original (88 + 92) / 2 program, it takes a bit of imagination to realize that an average is being
taken and then even more so that it is the average of two exam grades. We would like that notion to be clearer.
- Associated with this is the notion of avoiding putting 'magic numbers' into our code, i.e., numbers
that seem to come from nowhere. We will have more to say about this later, when we discuss proper
program design and style.
The Exam Averager Program Using Variables, Types, and Declarations
Write a program that calculates the average of a midterm grade of 88 and a final exam grade of 92 for the student Gerald Weiss,
and prints whether the student has passed or failed the course based on a passing grade of 60. The program should use variables for the values.
public class ExamAverager {
public static void main(String [] args) {
String name = "Gerald Weiss";
int midterm = 88;
int finalExam = 92;
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
Gerald Weiss received an 88 and a 92 for an average of 90
Gerald Weiss passes
- We replace the hardcoded values
Gerald Weiss, 88, 92,
with placeholders known as variables
- This allows us to easily change the name and exam grades
- It also allows us to code the calculation of the average only once
- Variables are locations in the computer's memory that can hold values
- Variables are restricted as to the sort of values they can hold; e.g., strings or numbers
- This category of value the variable can hold is called the type of the variable
- We have encountered two types so far:
int for variables holding integers (numbers)
String for variables holding text (strings)
- Java requires that one declare, i.e., state one's intention to use, any variables used in the program
- The declaration includes the name of the variable preceded by is type
- for example, in the above code:
String name and int midterm
- A declaration of a variable can also include an initialization, i.e., and initial value for the variable
- We will discuss variables, types, declarations, and initializations in more detail after this introductory lecture
Introducing variables addresses and resolves the issues presented at the beginning of this section:
- Storing the 'arbitrary' value in a variable allows one to retrieve it by name rather than having to repeatedly code the value
- Using a variable which can contain different values (at different times) allows one to perform the same calculations (e.g. computing an average)
on different values
- Using variables with intuitive names makes the code more understandable
Making Use of the 'Variable' In Variable
- We can now use variables to apply our logic to different values; the question remains however as to populate the variables with those values.
- Even with variables and initialization, the programs — as currently written — have the values hardcoded into the code
- While its true the values only appear in the initialization of variables (and are thus isolated from the rest of the program) ,
it is still the case that to change the value requires editing and recompiling the program
- We need some way of providing different sets of values without having to constantly be changing our code
- We do this by having the user supply data; for the moment we're going to do that from the keyboard
Reading Values (Input) From the Keyboard
- One would guess that if there is a
System.out.println to print things out, there should also be a System.in.readln (or something like that) to
read things in.
- It's close but not quite … a bit more work need to be done to read in values from the keyboard.
- For the moment, we will simply present the code as boilerplate again, but we WILL explain shortly
import java.util.Scanner;
public class <ClassName> {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
…
String name = scanner.next(); // next reads in text typed at the keyboard (until a blank is encountered or 'return' key is pressed)
int midterm = scanner.nextInt(); // nextInt reads in an integer typed at the keyboard
…
}
}
Prompting the User at the Keyboard
next and nextInt simply wait for the user to enter a value (and press the 'return' (↵) key)
- Without anything further, the user would:
- be presented with a blinking cursor, but no other inidicatio the system is waiting and thus …
- … would not realize the system is expecting them to input anything
- even if they realized the system is waiting, they would have no idea WHAT they are supposed to input (i.,e., a name?, an exam grade?, which exam?)
- To solve this problem, we introduce the notion of a user prompt, i.e., a message displayed to the screen telling (prompting)
the user the both input is expected and furthermore, what sort of input.
- For example, if we wish the user to type in a name, we would code:
System.out.print("Name? ");
String name = scanner.next();
- The
print vs println: the ln stands for line and indicates the
cursor should move to the beginning of the next line after the print; leaving it out causes the cursor to remain where it is
(after the last character displayed).
- We do this so the user's input is on the same line as the prompt (that's why there is a blank space after the
? of the prompt).
This is so we save vertical real estate; some programming conventions don't care and have the user's
input be on the next line.
- When looking at the program output, one therefore sees the prompts as well as the actual output; while they are both produced by
System.out.print**'s,
we usually distinguish between prompts and the actual output (i.,e., the results calculated by the program logic).
- We will discuss during the lab how to read program output containing prompts when it appears in CodeLab's Output Comparsion window
Notice that no new Java was introduced to solve this problem, merely understanding the issue and applying a clever / common-sense approach. We'll call such an approach
a technique; we will encounter many such techniques over the course of the semester.
The Exam Grader With Input From the Keyboard
We can now present a program that prompts the user and accepts data typed in from the keyboard.
Modify P01.6 so the data is read from the keyboard.
import java.util.Scanner;
public class ExamAverager {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Name? ");
String name = scanner.next();
System.out.print("Midterm? ");
int midterm = scanner.nextInt();
System.out.print("Final? ");
int finalExam = scanner.nextInt();
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
Weiss
88
92
Name? Midterm? Final? Weiss received an 88 and a 92 for an average of 90
Weiss passes
- We include all the input-related boilerplate discussed in the previous subsection, the
import, and declaration of scanner
- Up until now, the program's values were all self-contained as hardcoded values within the program. Now, however, they are read in from the keyboard
when the program is run (i.e., they are not know prior to actually running the program and getting the values).
- It is now necessary, when showing the program's execution output, we first have to show the values input at the keyboard; as the output
depends on those values.
- Notice the change from
Gerald Weiss to Weiss. This because next only reads until the next blank space. Were we to type in
Gerald Weiss and then hit return (the data is not sent to the machine from the keyboard until you press return), next would only
read Gerald and stop at the blank.
The Interactive Session
The above
Input and
Output showed exactly what is typed in at the keyboard and printed out by the
System.out.println's
(and
System.out.print's) of the program. However, since what is typed at the keyboard is echoed on the screen, what you see displayed looks somewhat different
than the above output:
Here is a sample execution of the program.
User input is in bold. Your program should replicate the prompts and output:
Name? Weiss
Midterm? 88
Final? 92
Weiss received an 88 and a 92 for an average of 90
Weiss passes
- This difference is important for you to understand because CodeLab matches only and exactly your
System.out output.
- The exercise instructions on the lab web pages show you this interactive session, i.e., the display you actually see: output and echoed input merged together.
- CodeLab display the interactive output as well, but you can also select to see either the input alone, or the output alone
Adding Repetition
- Now that we have variables that can hold different values, and are able to populate them using input from the keyboard (rather than hardcoded values), we
can now introduce the facility to repeat our logic on different values and apply our grading logic to each set of data input
Repeating Sections of Code — the for Loop
The conditional we introduced back in Program P01.5 is actually introduce in all its glory in Lectur 3, and repetion — the for loop — is not discussed in detail until Lecture 9. We're
presenting 'bay versions' of them now for several reasons:
- Being able to make very simply decisions as well as performing very simple repetitions will make our examples and lab assignments less boring
- It's not a bad idea for you as programmers to occasionally use something you don't immediately understand. These will grow on you as you use them
so by the time we really present them they won't seem so strange
The Grading Program for Three Students
We can now present a program that repeats our grading logic for several students. A for loop will provide the repetition and we will use a Scanner
to read the sets of data from the keyboard.
Modify P01.7 so it processes three students before terminating.
import java.util.Scanner;
public class ExamAverager {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 3; i = i + 1) {
System.out.print("Name? ");
String name = scanner.next();
System.out.print("Midterm? ");
int midterm = scanner.nextInt();
System.out.print("Final? ");
int finalExam = scanner.nextInt();
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
}
- We use a 3-repetition
for loop to read in three sets of student data
- The loop body consists of our (by now familiar) grading logic; supplemented with prompts and keyboard input logic
- Something important to notice: we are reusing our variables each time through the loop
- When we are finished with our processing of an individual student, and have printed out the results
for that student, we no longer need the values contained in the variables, and can reuse them for the next
time around
Weiss
88
92
Arnow
75
95
Cox
80
100
Name?
Midterm?
Final?
Weiss received an 88 and a 92 for an average of 90
Weiss passes
Name?
Midterm?
Final?
Arnow received an 75 and a 95 for an average of 85
Arnow passes
Name?
Midterm?
Final?
Cox received an 80 and a 100 for an average of 90
Cox passes
The Grading Program: Letting the User Decide How Many Students to Process
- The above
for loop program finally illustrates the power of the computer, with a trivial modification we can have the program perform the grading computation for one million
students.
- However, a similar problem arises to the one that motivated us to introduce variables: regardless of three, ten, or a million students, our program is again limited; this time to the
number of students processed.
- A better approach would be to allow the user to tell us in advance how many students they want to process.
- We will do this by prompting the user to enter how many students and then using that value as the terminating value of our for loop.
- The logic of the loop body does not change whatsoever
Modify P01.8 so that the user is prompted for the number of students to process.
public class ExamAverager {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many students do you wish to process? ");
int howMany = scanner.nextInt();
for (int i = 1; i <= howMany; i = i + 1) {
System.out.print("Name? ");
String name = scanner.next();
System.out.print("Midterm? ");
int midterm = scanner.nextInt();
System.out.print("Final? ");
int finalExam = scanner.nextInt();
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
}
3
Weiss
88
92
Arnow
75
95
Cox
80
100
How many students do you wish to process?
Name?
Midterm?
Final?
Weiss received an 88 and a 92 for an average of 90
Weiss passes
Name?
Midterm?
Final?
Arnow received an 75 and a 95 for an average of 85
Arnow passes
Name?
Midterm?
Final?
Cox received an 80 and a 100 for an average of 90
Cox passes
- As with prompts, this did not require any new language features, but rather another technique using
language facilities we already knew
- It is often recognizing the application of an existing technique, or coming up with a new one, that
is the most challenging thing about programming
Summary
The above examples illustrated all three fundamental coding tools: actions, decisions, and repetition. Starting with the next lecture,
we bring examining the three basic operations: imperative actions, conditionals, and repetition. We will also be examining other important
language features that help us prganize oue programs as they get larger and more complex, as well as features to allow us to work with large amounts of data.