// Fig. 2.1: Welcome1.java
public class Welcome1 {
public static void main(String[] args) {
System.out.println("Welcome to Java Programming!");
}
}College of Computing and Informatics · Study summary
DS 230: Object Oriented Programming
In [1]:public class Course { public static void main(String[] args) { System.out.println("DS 230: Object Oriented Programming"); } }
Every week of the course in plain language, from your first Hello World to inheritance, polymorphism, strings and recursion. Each week has the key ideas, short Java examples with their output, the mistakes to watch for, and a quick check. The course follows Java: How to Program (Late Objects) by Deitel & Deitel.
Introduction to Computer Science and Programming
Big picture. Before writing Java you need to know how a computer is organized, how programming languages differ, and what happens between typing a .java file and seeing the result. Java’s big idea: write once, run anywhere.
Hardware and software
Hardware is the physical devices of a computer system. Software is the programs that run on it. Computers follow sequences of instructions called programs, written by programmers.
Six logical units of a computer
| Unit | Job | Examples |
|---|---|---|
| Input unit | Receives data | Mouse, keyboard |
| Output unit | Shows results | Printer, monitor, speakers |
| Memory unit | Holds data and programs while running | RAM |
| ALU (arithmetic and logic unit) | Performs calculations | |
| CPU (central processing unit) | Supervises the other devices | |
| Secondary storage unit | Long-term storage | Hard drives |
The data hierarchy
Storage units: 1 KB = 1024 bytes; 1 MB = 1024 KB; 1 GB = 1024 MB; 1 TB = 1024 GB; then PB, EB and ZB, each 1024 times the previous.
Programming languages
| Level | What it is | Translator |
|---|---|---|
| Machine language | The only language a computer understands directly. Strings of 1s and 0s, machine dependent. | None |
| Assembly language | English-like abbreviations for elementary operations. | Assembler |
| High-level language | Single statements do substantial work; looks like English and math. | Compiler (translates the whole program first) or interpreter (executes directly) |
Compiler vs interpreter.Compiling a big program takes time, but compiled programs run fast. An interpreter avoids the delay of compilation, but programs run slower.
Operating systems and Java
- An operating system makes computers easier to use and lets applications run safely, efficiently and concurrently. Its core component is the kernel. Examples: Windows, Linux, macOS, Android.
- Java was developed by Sun Microsystems in 1991; Oracle acquired Sun in 2010.
- Editions: Java SE (desktop and server applications) and Java EE (large-scale distributed and web applications).
- Java class libraries (Java APIs) contain classes with methods that do tasks and return information, so you build programs from pieces that already exist.
The 5 phases of a Java program
- Edit. Write the program in an editor or IDE. Source files end in
.java. IDEs: Eclipse, NetBeans, IntelliJ IDEA, BlueJ. - Compile.
javac Welcome.javaturns source code into bytecodes stored inWelcome.class. - Load. The JVM’s class loader moves the
.classfiles into memory. - Verify. The bytecode verifier checks that bytecodes are valid and do not break Java’s security restrictions.
- Execute. The JVM runs the bytecodes using interpretation plus just-in-time (JIT) compilation of frequently used “hot spots” into machine language.
| Machine-language code | Bytecode |
|---|---|
| Platform dependent, not portable | Platform independent, portable |
| Must be recompiled on a new machine | No need to recompile on a new machine (the JVM handles it) |
A virtual machine (VM) is software that simulates a computer and hides the real hardware and OS from the programs on it. The JVM is part of the JDK.
Runtime errors.Errors like division by zero happen while the program runs. A fatal runtime error ends the program immediately. A nonfatal one lets it finish, often with wrong results.
Object technology in one minute
Objects are reusable software components that model real-world things (people, cars, phones). They have attributes (size, color) and behaviors (make a call, stop the engine). Object-oriented design (OOD) models objects and how they communicate, encapsulates data and functions together, and uses information hiding with well-defined interfaces. Programming this way is OOP, and Java is an object-oriented language.
The Internet began over three decades ago with DOD funding to connect a few main computers. The World Wide Web lets you locate and view multimedia documents.
Quick check
Name the six logical units of a computer.
Input, output, memory, ALU, CPU and secondary storage.
What is the difference between a compiler and an interpreter?
A compiler translates the entire high-level program to machine language first. An interpreter executes the program directly, avoiding compile delay but running slower.
What does javac produce?
A .class file containing bytecodes.
Why is bytecode portable?
It is platform independent. The JVM on each machine runs it, so no recompiling is needed.
Order the five phases.
Edit, compile, load, verify, execute.
Introduction to Java Applications I
Big picture. Write your first program, print text in different ways, read input from the keyboard, import library classes, comment your code and trace errors with a debugger.
Your first program
Welcome to Java Programming!
- Every Java program has at least one user-defined class.
classis a keyword (a reserved word) followed by the class name. - The file name must match the class name plus
.java:Welcome1.java. - The left brace
{begins the body of a class or method and the right brace}ends it. - Applications begin executing at
main. The parentheses show thatmainis a method. System.outis the standard output object.printlndisplays a line of text. A String is a series of characters inside double quotes.- Every statement ends with a semicolon
;.
Identifiers (names)
A series of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit and has no spaces. Valid: Welcome1, $value, _value, button7. Invalid: 7button. Java is case sensitive: a1 and A1 are different.
Compile and run
javac Welcome1.java # creates Welcome1.class (bytecodes) java Welcome1 # runs it; the .class extension is omitted
Three kinds of comments
| Type | Syntax | Use |
|---|---|---|
| One line | // text | Short notes |
| Traditional (multi-line) | /* text */ | Longer notes |
| Javadoc | /** text */ | Embeds documentation. The javadoc tool turns it into HTML pages. |
Comments are ignored when the program runs. Blank lines, spaces and tabs (white space) are ignored by the compiler too, but white space inside a String is not.
Displaying text
| Statement | Behavior |
|---|---|
System.out.print(...) | Keeps the cursor on the same line |
System.out.println(...) | Prints, then moves to the next line |
\n inside a String | Newline character: moves the cursor to the next line |
System.out.printf(...) | Formatted output |
System.out.println("Welcome to\nJava\nProgramming!");Welcome to Java Programming!
printf
Format: %[flags][width][.precision]conversion-character
| Conversion | Meaning |
|---|---|
%s | String |
%d | Decimal integer |
%f | Floating-point number |
%b / %B | Boolean (true / TRUE) |
%t | Date/time |
%n | Line separator |
System.out.printf("Hello %s!%n", "World");
System.out.printf("'%5.2f'%n", 5.1473);
System.out.printf("%,d %n", 10000);Hello World! ' 5.15' 10,000
width is the field width (e.g. %15s right-aligns in 15 characters). .precision is the number of digits after the point.
Reading input with Scanner
A variable is a location in memory that stores a value. To read what the user types:
import java.util.Scanner; // tells the compiler where Scanner is
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your age: "); // prompt
int age = input.nextInt(); // read an integer
System.out.println("Age is: " + age);
}
}| Method | Reads |
|---|---|
nextInt() | An integer |
nextDouble() | A double |
next() | One word (a String) |
nextLine() | A whole line |
new Scanner(System.in) creates a Scanner object. System.in is the standard input object that reads bytes typed at the keyboard.
Importing libraries
The Java API is a rich set of predefined classes grouped into packages, so you do not need to “reinvent the wheel”. An import declaration tells the compiler where to find a class, such as the package java.util for Scanner.
Debugging and tracing errors
Debugging is locating and removing bugs. A debugger lets you pause a running program and look inside it.
Breakpoint
Suspends execution at a line so you can see variable values, the call stack, and step through line by line. Toggle it by clicking the left side of the editor.
Exception breakpoint
Stops whenever a specific exception occurs, such as NullPointerException or ArrayIndexOutOfBoundsException.
Watchpoint
Stops each time a chosen field or variable is accessed or changed.
Quick check
What must the file name be for public class Welcome1?
Welcome1.java.
Difference between print and println?
print stays on the same line; println moves to the next line afterward.
Is 7button a valid identifier?
No. An identifier cannot begin with a digit.
Which import is needed for Scanner?
import java.util.Scanner;
What does %n do in printf?
Inserts a line separator.
Introduction to Java Applications II
Big picture. Variables store data, operators work on it, and the three kinds of errors (syntax, runtime, logic) show up in different ways.
Variables
A variable is a location in memory that stores a value. Declare it with a type and a name before you use it. A variable’s type tells what kind of information it stores. Declarations end with a semicolon.
int number1; // declare
int number1, number2; // several of the same type
int myNum = 15; // declare and assign
myNum = 20; // change the value
final int MAX = 15; // final: constant, cannot change| Primitive type | Holds | Example |
|---|---|---|
int | Whole numbers. Range −2,147,483,648 to +2,147,483,647 | 72, -1127, 0 |
float, double | Real numbers (with a decimal point) | 3.4, -11.19 |
char | One character, in single quotes | 'D', '7', '*' |
boolean | true or false | true |
All eight primitive types: boolean, byte, char, short, int, long, float, double. String is not a primitive type. float values need an f (5.99f).
final.A final variable is read-only. Assigning to it again is a compile error: “cannot assign a value to a final variable”.
Memory concepts
- A name like
number1corresponds to a location in memory. - Reading a variable does not change it. Assigning a new value replaces the old one.
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ - | Add, subtract | 10 + 40 |
* | Multiply | |
/ | Divide. Integer division truncates the remainder. | 7 / 5 is 1 |
% | Remainder | 7 % 5 is 2 |
Precedence: parentheses first (innermost first), then * / % left to right, then + - left to right.
int a = 5 + 4 * 3 / 2; // 4*3=12, 12/2=6, 5+6 -> 11
int b = (5 + 4) * 3 / 2; // 9*3=27, 27/2=13 -> 13
int c = (5 + 4) * (3 / 2); // 9 * 1 -> 9
int d = (5 + (4 * 3)) / 2; // 17/2 -> 8
// second-degree polynomial a*x*x + b*x + c with a=2, b=3, c=7, x=5
int y = 2 * 5 * 5 + 3 * 5 + 7; // 72Equality and relational operators
A condition is an expression that is true or false.
| Operator | Meaning | With x = 5, y = 3 |
|---|---|---|
== | Equal to | x == y is false |
!= | Not equal to | x != y is true |
> < | Greater / less than | x > y is true |
>= <= | Greater or equal / less or equal | x <= y is false |
Increment and decrement
| Form | Behavior | Example (b = 15) |
|---|---|---|
Pre-increment ++b | Increment first, then use the value | a = ++b; gives a = 16, b = 16 |
Post-increment b++ | Use the value first, then increment | a = b++; gives a = 15, b = 16 |
--x / x-- | Same idea, decreasing by 1 | With x = 10: y = --x gives 9; y = x-- gives 10 |
Assignment operators
= assigns a value. += adds to a variable: x += 5 means x = x + 5. Others: -=, *=, /=, %=.
Operator precedence (so far)
| Operators | Associativity | Type |
|---|---|---|
* / % | left to right | multiplicative |
+ - | left to right | additive |
< <= > >= | left to right | relational |
== != | left to right | equality |
= | right to left | assignment |
The three kinds of errors
| Error | When it appears | Example |
|---|---|---|
| Syntax error | The compiler finds a problem, so you cannot even run the program | Missing semicolon int x=10; undeclared variable; System.out.print; |
| Runtime error | Program compiles, but fails while running; you get an error message | Division by zero |
| Logic error (bug) | Program compiles and runs but does the wrong thing; no message | Wrong operator precedence |
Quick check
What does 7 / 5 give in Java with ints? And 7 % 5?
1 and 2. Integer division drops the remainder.
If b = 15, what is a after a = b++;?
15, and b becomes 16.
Is String a primitive type?
No.
Which error type shows no message at all?
A logic error.
Control Statements I: Decisions
Big picture. Programs normally run line by line, but control statements let them choose between actions. First plan with an algorithm and pseudocode, then code it with if, if…else, switch and ?:.
Algorithms and pseudocode
- An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which they execute.
- Pseudocode is an informal language for developing algorithms without worrying about Java syntax. It does not execute on computers.
// Algorithm: add two numbers
Step 1: Start
Step 2: Declare variables num1, num2 and sum
Step 3: Read values num1 and num2
Step 4: sum = num1 + num2
Step 5: Display sum
Step 6: StopThe three control structures
Sequence
Statements run one after another. Java has this “built in”.
Selection
if, if…else, switch
Repetition
while, do…while, for
Each of these words is a Java keyword. Control statements are single-entry/single-exit.
if and if…else
if performs an action only when the condition is true. if…else also performs a different action when it is false.
int grade = 75;
if (grade >= 60)
System.out.println("Passed");
else
System.out.println("Failed");
int number = 13;
if (number % 2 == 0)
System.out.println("even number");
else
System.out.println("odd number");Passed odd number
Blocks
The body of an if normally holds one statement. To include several, enclose them in braces to make a block.
if (grade >= 60)
System.out.println("Passed");
else {
System.out.println("Failed");
System.out.println("You must take this course again.");
}Nested if…else (else if)
if (studentGrade >= 90)
System.out.println("A");
else if (studentGrade >= 80)
System.out.println("B");
else if (studentGrade >= 70)
System.out.println("C");
else if (studentGrade >= 60)
System.out.println("D");
else
System.out.println("F");Dangling else.The compiler always pairs an else with the immediately preceding if, regardless of how you indent. Use braces { } to force the pairing you intend.
switch…case
Performs different actions based on the possible values of a constant integral expression.
- Switch expression types: byte, short, int, long, enums and String.
- Case values must be unique.
breakis optional but it jumps out of the switch. Without it, execution falls through and runs the next case too.defaultis optional and runs when no case matches.
int number = 20;
switch (number) {
case 10: System.out.println("10"); break;
case 20: System.out.println("20"); break;
case 30: System.out.println("30"); break;
default: System.out.println("Not in 10, 20 or 30");
}
char grade = 'C';
switch (grade) {
case 'A': System.out.println("Excellent!"); break;
case 'B':
case 'C': System.out.println("Well done"); break; // B and C share this
case 'D': System.out.println("You passed");
case 'F': System.out.println("Better try again"); break;
default: System.out.println("Invalid grade");
}20 Well done
Fall-through.With grade = 'D' the code prints “You passed” and “Better try again”, because case 'D' has no break.
The conditional operator ?:
Java’s only ternary operator (three operands). A shorter replacement for simple if…else: condition ? valueIfTrue : valueIfFalse.
int a = 6, b = 12;
String out = (a == b) ? "Yes" : "No"; // "No"
int x = 69, y = 89, z = 79;
int largest = (x > y) ? (x > z ? x : z) : (y > z ? y : z); // 89Quick check
What is pseudocode and does it run?
An informal language for planning algorithms. It does not execute on computers.
What does a missing break in a switch cause?
Fall-through: the following cases also execute until a break or the end.
Which if does an else belong to?
The immediately preceding if, unless braces change it.
What is the only ternary operator in Java?
The conditional operator ?:.
Control Statements II: Loops and Logic
Big picture. Loops repeat a block of code. They save time, reduce errors and make code more readable. Logical operators combine conditions.
What every loop needs
- A control variable (loop counter)
- The initial value of the control variable
- The increment applied each time through the loop (each iteration)
- The loop-continuation condition that decides if looping continues
while, for and do…while
// while: test first
int counter = 1;
while (counter <= 10) {
System.out.printf("%d ", counter);
++counter;
}
// for: all counter details in one line
for (int i = 1; i <= 10; i++)
System.out.printf("%d ", i);
// sum of even numbers from 2 to 20
int total = 0;
for (int number = 2; number <= 20; number += 2)
total += number; // 110
// do...while: test after
int n = 1;
do {
System.out.printf("%d ", n);
n++;
} while (n <= 10);1 2 3 4 5 6 7 8 9 10
Each of the counting loops above prints this line. The even-sum loop leaves total = 110.
| Loop | Tests the condition | Body runs |
|---|---|---|
while | Before the body | Zero or more times (never if the condition is false at first) |
for | Before the body (init; condition; increment in one header) | Zero or more times |
do…while | After the body | At least once |
In a for header, the increment expression acts like a standalone statement at the end of the loop body. You may use arithmetic expressions in the header.
Nested loops
A loop inside another loop. The inner loop finishes all its iterations for each iteration of the outer loop.
for (int i = 1; i <= 3; i++) { // outer loop
for (int j = 1; j <= 2; j++) { // inner loop
System.out.print("(" + i + "," + j + ") ");
}
System.out.println();
}(1,1) (1,2) (2,1) (2,2) (3,1) (3,2)
break and continue
break
In a while, for, do…while or switch: immediately exits the statement. Execution continues with the first statement after it. Use it to escape a loop early or skip the rest of a switch.
continue
In a loop: skips the rest of the loop body and goes to the next iteration. In a for, the increment runs, then the condition is tested.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skip 3
if (i == 5) break; // stop at 5
System.out.print(i + " ");
}1 2 4
Logical operators
| Operator | Name | True when |
|---|---|---|
&& | Conditional AND | Both conditions are true. Stops early if the left side is false. |
|| | Conditional OR | Either or both are true. Stops early if the left side is true. |
& | Boolean logical AND | Like &&, but always evaluates both operands |
| | Boolean logical inclusive OR | Like ||, but always evaluates both operands |
^ | Boolean logical exclusive OR | Exactly one operand is true |
! | Logical NOT | Reverses a condition |
Why use & or |?When the right operand has a required side effect, such as ++age. & and | guarantee it runs even when the result is already decided.
Precedence and associativity so far (high to low)
| Operators | Type | Associativity |
|---|---|---|
++ -- (postfix) | unary postfix | right to left |
++ -- + - ! (prefix, cast) | unary prefix | right to left |
* / % | multiplicative | left to right |
+ - | additive | left to right |
< <= > >= | relational | left to right |
== != | equality | left to right |
& | boolean logical AND | left to right |
^ | boolean logical exclusive OR | left to right |
| | boolean logical inclusive OR | left to right |
&& | conditional AND | left to right |
|| | conditional OR | left to right |
?: | conditional | right to left |
= += -= *= /= %= | assignment | right to left |
Quick check
What are the four requirements of a counter-controlled loop?
Control variable, initial value, increment, and loop-continuation condition.
Which loop always runs at least once?
do…while.
Difference between break and continue?
break exits the loop or switch entirely. continue skips the rest of this iteration and moves to the next one.
Difference between && and &?
&& may skip the right operand if the left is false. & always evaluates both.
Methods (Part 1)
Big picture. A method is a named block of code that does one job. Writing it once and calling it many times makes programs shorter, easier to manage and reusable.
Why use methods? The modules approach
Suppose you need the sum of numbers 1 to 10, 20 to 30 and 35 to 45. Repeating a loop three times is messy. Define a method once:
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
public static void main(String[] args) {
System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 30 is " + sum(20, 30));
}Sum from 1 to 10 is 55 Sum from 20 to 30 is 275
- Divide and conquer: build a program from small, simple pieces.
- Software reusability: use existing methods as building blocks.
- A method is invoked by a method call. When the called method finishes, it returns control (and possibly a result) to the caller.
Declaring a method
public static int methodName(int a, int b) {
// body
}| Part | Meaning |
|---|---|
public static | Modifiers (explained in Week 11) |
int | Return type. Use void when nothing is returned. |
methodName | The name of the method |
int a, int b | The parameter list (formal parameters) |
return value; | Sends a value back to the caller |
Naming convention: start with a verb in lowercase. For several words, capitalize each word except the first: area(), areaOfCircle().
Two kinds of method
- Predefined (built-in, in the class libraries), e.g.
Math.max(9, 7)gives 9. - User-defined, written by you.
Formal vs actual parameters.In int add(int n1, int n2), n1 and n2 are the formal parameters. In the call add(a, b), a and b are the actual parameters (arguments).
public static void main(String[] args) {
int a = 19, b = 5;
int c = add(a, b); // method call
System.out.println("The sum of a and b is= " + c);
}
public static int add(int n1, int n2) {
int s = n1 + n2;
return s; // returning the sum
}The sum of a and b is= 24
A method can take many parameters, separated by commas: myMethod(String fname, int age). A void method returns nothing; a method with a return type uses the return keyword.
Arguments and casting
Pass-by-value
Java passes a copy of the variable’s value to the method. Changing the parameter inside the method does not change the original variable.
Argument promotion
Java can coerce an argument to the type the method needs when no data is lost, such as Math.sqrt(4) receiving an int and treating it as a double.
public static void main(String[] args) {
int number = 1;
tryToChangeNumber(number);
System.out.println(number);
}
public static void tryToChangeNumber(int i) { i = 2; }1
Casting forces a conversion that could lose data. If doubleValue = 4.5 and method square needs an int, call square((int) doubleValue). The method receives 4 and returns 16, not 20.25.
Quick check
What does void mean as a return type?
The method returns no value.
Formal vs actual parameters?
Formal parameters are in the method declaration; actual parameters are the values passed in the call.
If a method changes its int parameter, does the caller’s variable change?
No. Java is pass-by-value, so the method works on a copy.
What is the output of square((int) 4.5) if square returns x*x?
16.
Methods (Part 2)
Big picture. Java’s predefined classes live in packages. Scope decides where a name can be used. Overloading lets several methods share a name.
Java API packages
Packages are groups of related classes. They promote software reuse. An import statement names the classes you use, e.g. import javax.swing.JApplet;. The package java.lang is imported into every program automatically.
| Package | Contains |
|---|---|
java.lang | Core language classes, imported automatically |
java.util | Utility classes (e.g. Scanner), collections |
java.io | Input and output of data |
java.net | Networking over the Internet |
java.sql | JDBC: working with databases |
java.security | Application security |
java.awt.event, java.awt.geom | GUI event handling; 2D shapes |
javax.swing | Swing GUI components |
java.time | Date/Time API |
java.util.function, java.util.stream | Lambdas and streams (Java SE 8) |
Scope of a declaration
The scope of a declaration is the portion of the program that can refer to that entity by its name. Basic scope rules:
- Scope of a parameter declaration: the method body.
- Scope of a local variable: from its declaration to the end of the block where it is declared.
- Scope of a local variable declared in a
forheader’s initialization: thatforstatement. - Scope of a label in a labeled
breakorcontinue. - Scope of a method or field of a class: the whole body of the class.
Method overloading
Several methods can have the same name if each has a different parameter set: a different number of parameters or different parameter types. Java decides which one to call from the arguments.
static int add(int a, int b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }
static double add(double a, double b) { return a + b; }
System.out.println(add(11, 11)); // 22
System.out.println(add(11, 11, 11)); // 33
System.out.println(add(12.3, 12.6)); // 24.9Return type is not enough.Two methods with the same name and the same parameters but different return types is a compile error. Overloading depends on the parameters.
Type promotion: if an exact match is missing, Java promotes a smaller type. With sum(int a, long b) and sum(int a, int b, int c), the call sum(20, 20) promotes the second int to long.
Quick check
Which package is imported automatically?
java.lang.
What defines the scope of a local variable?
The block in which it is declared, from the declaration to the closing brace.
How can overloaded methods differ?
By the number of parameters or by the parameter types.
Arrays
Big picture. An array holds a fixed number of values of the same type under one name. Arrays are objects, so you reach them through a reference.
Primitive vs reference types
Primitive-type variable
Holds exactly one value of its declared type. Assigning a new value replaces the old one.
Reference-type variable
Stores the address of an object in memory. Scanner input = new Scanner(System.in); assigns input a reference to the Scanner object.
Creating, initializing and using arrays
- An array is a data structure. Each element is accessed by an index (subscript) in square brackets. The index must be a non-negative integer or integer expression.
- The first element is at index 0. An array of 12 elements uses
c[0]toc[11].c.lengthgives the number of elements. - Arrays are created with the keyword
new.
int[] c = new int[12]; // 12 elements, all start at 0
int[] d = {10, 20, 30, 40, 50}; // array initializer
String[] b = new String[100], x = new String[27];
c[0] = -45;
int sum = c[0] + c[1] + c[2];
int total = 0;
for (int i = 0; i < d.length; i++)
total += d[i]; // 150
c[5 + 6] += 2; // adds 2 to c[11]Common uses.Summing elements, calculating values to store, drawing bar charts of array data, and using array elements as counters (e.g. counting how many times each die face appears).
Exception handling: try-catch
An exception is a problem that occurs while the program executes. Put code that might throw one in a try block and the handling code in a catch block. The finally block runs regardless of the result.
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The try catch is finished.");
}Something went wrong. The try catch is finished.
Without the try-catch, Java stops with ArrayIndexOutOfBoundsException: 10.
Enhanced for statement
Iterates through the elements of an array without a counter, so you cannot “step outside” the array. The header has a type and an identifier for the current element, then : and the array name.
int[] array = {87, 68, 94, 100, 83};
int total = 0;
for (int number : array)
total += number;
System.out.println(total);432
Passing arrays to methods
Specify the array name without brackets. The call is modifyArray(hourlyTemperatures); and the header is void modifyArray(double[] b).
Pass-by-value vs pass-by-reference
| Pass-by-value | Pass-by-reference | |
|---|---|---|
| What is passed | A copy of the argument’s value | Direct access to the caller’s data |
| Changes inside the method | Do not affect the original variable | Can modify the original data |
| Benefit | Safe | Faster for large data (no copying) |
Java rule.Java does not let you choose. All arguments are passed by value. When the argument is an array or object, the reference is what is copied, so the method can change the array’s elements.
Multidimensional arrays
A two-dimensional array is a table with rows and columns. Rows can have different lengths.
int[][] b = { {1, 2}, {3, 4} }; // b[0][0]=1, b[0][1]=2, b[1][0]=3, b[1][1]=4
int[][] jag = { {1, 2}, {3, 4, 5} }; // row 0 has 2 elements, row 1 has 3
System.out.println(jag[1][2]);5
Quick check
What is the index of the first and last element of an array with 12 elements?
0 and 11.
What does finally do?
Runs after try/catch no matter what happened.
Why use the enhanced for?
It avoids a counter, so you cannot go outside the array.
Does Java pass by value or by reference?
Always by value (for arrays and objects, the reference is copied).
Classes and Objects I
Big picture. A class is a blueprint. An object is one thing built from it. Classes bundle data (attributes) and methods (behaviors) together.
Classes and objects
Class
A group of objects with common properties: a template or blueprint. It is a logical entity. It can contain fields, methods, constructors, blocks, and nested classes and interfaces.
Object
An instance of a class. A real-world, runtime entity with state and behavior.
- Instance variable: declared inside the class but outside any method. It gets memory at runtime, when an object is created.
- Method: represents a behavior of an object.
newcreates an object. The parentheses after the class name are required.
public class Account {
private String name; // instance variable
public void setName(String name) { // setter
this.name = name; // this refers to the instance variable
}
public String getName() { // getter
return name;
}
}
public class AccountTest {
public static void main(String[] args) {
Account myAccount = new Account(); // instantiate
myAccount.setName("Jane Green");
System.out.println("Name is: " + myAccount.getName());
}
}Name is: Jane Green
Each object statement has three parts: declaration (variable of an object type), instantiation (the new operator), and initialization (the call to a constructor).
Access modifiers
| Modifier | Accessible from |
|---|---|
public | Anywhere, including outside the class |
private | Only methods of the class that declares it |
Private means private.Using a private field from another class is a compile-time error. This is why classes use public setters and getters to reach private data.
Default and explicit initialization
- Local variables are not initialized by default.
- Primitive instance variables are: numeric types (
byte, char, short, int, long, float, double) start at 0, andbooleanstarts at false. - You can also initialize an instance variable explicitly in its declaration.
Constructors
A constructor initializes an object when it is created. It has the same name as its class and looks like a method, but has no return type.
class MyClass {
int x;
MyClass(int i) { x = i; } // parameterized constructor
}
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(20);
System.out.println(t1.x + " " + t2.x);10 20
static members
- A static variable belongs to the class as a whole. All objects share it. It gets memory only once, when the class is loaded.
- A static method relates to the class, not to a specific object. Instance methods work on one object’s instance variables.
class Counter {
static int count = 0;
Counter() { count++; System.out.println(count); }
}
new Counter(); new Counter(); new Counter(); // prints 1, 2, 3Why static matters.If count were an instance variable, each object would get its own copy starting at 0, so every object would print 1.
Implementing a test class
A class with main that creates objects of your class and calls their methods is a test class. Example: a bank Account with insert, deposit, withdraw (printing “Insufficient Balance” if amount < amt) and checkBalance. Starting at 1000, deposit 40000 gives 41000; withdraw 15000 gives 26000.
Quick check
Class vs object?
A class is the blueprint. An object is an instance created from it with new.
What is special about a constructor?
It has the class name and no return type, and runs when an object is created.
When does an instance variable get memory?
At runtime, when an object is created.
What is the default value of an int instance variable? And a local int?
0 for the instance variable. A local variable has no default value.
Classes and Objects II
Big picture. Finer points of classes: this, several constructors, composition, enums, memory cleanup, static and final, and packages. Focus: encapsulation and data hiding.
The this reference
When a local variable or parameter has the same name as an instance variable, it shadows it. Use this.name to refer to the instance variable.
rollno = rollno; assigns the parameter to itself. Fields stay 0, null, 0.0.this.rollno = rollno; assigns the parameter to the field. Output 111 ankit 5000.0.class Student {
int rollno; String name; float fee;
Student(int rollno, String name, float fee) {
this.rollno = rollno;
this.name = name;
this.fee = fee;
}
}
class A {
A() { System.out.println("hello a"); }
A(int x) { this(); // calls the no-arg constructor
System.out.println(x); }
}
new A(10);hello a 10
this() invokes another constructor of the current class.
Overloaded constructors
A class can have any number of constructors that differ in the number or types of parameters. The compiler tells them apart by their parameter lists, e.g. Account(int a), Account(int a, int b), Account(String a, int b).
Default and no-argument constructors
- Every class must have at least one constructor.
- If you provide none, the compiler creates a default constructor with no arguments. It sets instance variables to their declared initial values or their default values.
Composition (has-a)
A class can have references to objects of other classes as members. This is composition, the has-a relationship. Example: an AlarmClock has two Time objects; a car has a steering wheel, a brake pedal and an accelerator.
enum types
A special class that defines a set of constants as unique identifiers.
public enum Season { WINTER, SPRING, SUMMER, FALL }
for (Season s : Season.values())
System.out.println(s);
System.out.println(Season.valueOf("SUMMER").ordinal());WINTER SPRING SUMMER FALL 2
Garbage collection
Objects use system resources, such as memory. Java returns memory automatically through garbage collection: an object is marked for collection when no references to it exist. The finalize method (defined in java.lang.Object, no parameters, returns void) lets an object release other resources.
static class members and static import
- static class variable: class-wide information, shared by all objects.
- Access a public static member by qualifying it with the class name and a dot:
Math.PI. - A static import lets you use static members by their unqualified names. Two forms: import one static member, or all static members of a class.
import static java.lang.Math.*;
double r = sqrt(16) + abs(-3); // no "Math." neededfinal instance variables
final means the variable cannot be modified. Any attempt is a compile-time error. It enforces the principle of least privilege.
private final int INCREMENT = 5; // a constantCreating packages
A package is a group of related classes and interfaces. It helps manage complexity, supports reuse and gives unique class names. The convention is the reverse of your Internet domain name, e.g. com.deitel.
package pack; // file A.java
public class A { public void msg() { System.out.println("Hello"); } }
package mypack; // file B.java
import pack.*;
class B { public static void main(String[] args) { new A().msg(); } }Hello
Quick check
What does this.name = name; do?
Assigns the parameter name to the instance variable name.
When does the compiler supply a default constructor?
When the class declares no constructor at all.
Composition is which relationship?
Has-a.
When is an object eligible for garbage collection?
When there are no references to it.
What happens if you assign to a final variable?
Compile-time error.
Inheritance and Polymorphism
Big picture. Inheritance lets a new class reuse and extend an existing class. Polymorphism lets one action work differently depending on the object. Together they make programs reusable and extensible.
Superclasses and subclasses
Inheritance is a mechanism in which one class acquires the properties and behaviors of another. It represents the IS-A relationship (parent-child) and gives software reusability.
| Term | Also called |
|---|---|
| Superclass | Parent class, base class |
| Subclass | Child class, derived class, extended class. Uses the keyword extends. |
- A subclass is a more specialized group of objects. It inherits the superclass behaviors, can customize them, and can add its own fields and methods.
- Direct superclass: inherited explicitly, one level up. Indirect superclass: two or more levels up.
- Single inheritance: one superclass. Multiple inheritance: several superclasses. Java does not support multiple inheritance for classes.
is-a (inheritance)
A subclass object is also an object of its superclass. A car is a vehicle. A CarLoan is a Loan, but not every Loan is a CarLoan.
has-a (composition)
An object contains references to other objects. A car has a steering wheel.
Types of inheritance
| Type | Example |
|---|---|
| Single | class Dog extends Animal |
| Multilevel | class BabyDog extends Dog, where Dog extends Animal |
| Hierarchical | Dog and Cat both extend Animal |
class Animal { void eat() { System.out.println("eating..."); } }
class Dog extends Animal { void bark() { System.out.println("barking..."); } }
Dog d = new Dog();
d.bark();
d.eat(); // inherited from Animalbarking... eating...
protected members and super
| Modifier | Same class | Same package | Subclass | Everywhere |
|---|---|---|---|---|
public | Yes | Yes | Yes | Yes |
protected | Yes | Yes | Yes | No |
| (default) | Yes | Yes | No (other package) | No |
private | Yes | No | No | No |
protected is an intermediate level between public and private. A subclass reaches a superclass member with the keyword super and a dot.
class Superclass {
int i = 20;
void display() { System.out.println("Superclass display method"); }
}
class Subclass extends Superclass {
int i = 100;
void display() {
super.display(); // call parent version
System.out.println("i value = " + i);
System.out.println("superclass i value = " + super.i);
}
}
new Subclass().display();Superclass display method i value = 100 superclass i value = 20
final class: if you do not want other classes to inherit from a class, declare it final. class Main extends Vehicle then gives “cannot inherit from final Vehicle”.
Polymorphism
Polymorphism means “many forms”. It occurs when many classes are related by inheritance and each performs the same action in its own way. You can treat objects in the same hierarchy as objects of the superclass. New classes can be added easily and still be processed.
| Method overloading | Method overriding | |
|---|---|---|
| Where | Same class | Subclass redefines a parent method |
| Same name? | Yes | Yes |
| Parameters | Different | Same as the parent method |
In overriding, which method runs is decided by the object being referred to, not the reference type. Using a superclass reference for a subclass object is upcasting.
class Animal { void eat() { System.out.println("Animals Eat"); } }
class Herbivores extends Animal { void eat() { System.out.println("Herbivores Eat Plants"); } }
class Carnivores extends Animal { void eat() { System.out.println("Carnivores Eat Meat"); } }
Animal h = new Herbivores(); // upcasting
Animal c = new Carnivores(); // upcasting
h.eat();
c.eat();Herbivores Eat Plants Carnivores Eat Meat
Abstract classes and interfaces
Abstract class
A restricted class that cannot be used to create objects. It must be inherited. An abstract method has no body and can only be in an abstract class. The subclass provides the body.
Interface
A completely “abstract class” that groups methods with empty bodies. It must be implemented (implements), and the implementing class provides the bodies.
abstract class Animal {
public abstract void animalSound(); // no body
public void sleep() { System.out.println("Zzz"); }
}
class Pig extends Animal {
public void animalSound() { System.out.println("The pig says: wee wee"); }
}
// Animal a = new Animal(); // ERROR: cannot instantiate an abstract class
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();The pig says: wee wee Zzz
Quick check
Which keyword creates a subclass?
extends.
Does Java support multiple inheritance of classes?
No.
Who can access a protected member?
The class itself, its subclasses, and other classes in the same package.
Overloading vs overriding?
Overloading: same name, different parameters, same class. Overriding: a subclass redefines a parent method with the same signature.
Can you create an object of an abstract class?
No. It must be inherited by a subclass first.
Strings and Characters
Big picture. Text is handled by the String and Character classes. Strings are immutable. Regular expressions let you check or find patterns in text.
Fundamentals
- Characters are the fundamental building blocks of Java source programs. A character literal is written in single quotes, and its value is the integer Unicode value of the character.
- String represents strings. A String is an object, and String objects are immutable: they cannot be changed after creation.
- The String class has constructors that initialize String objects in several ways (empty, from another String, from a char array).
char[] charArray = {'b','i','r','t','h',' ','d','a','y'};
String s1 = "hello";
String s2 = new String(charArray);
System.out.println(s1.length()); // 5
System.out.println(s1.charAt(1)); // e5 e
Comparing strings
== vs equals.== compares references (are they the same object?). equals compares the contents.
String s1 = new String("hello");
System.out.println(s1 == "hello"); // false (different objects)
System.out.println(s1.equals("hello")); // true
String s2 = "hello";
System.out.println(s2 == "hello"); // true (string literal)
System.out.println("hello".equals("Hello")); // false
System.out.println("hello".equalsIgnoreCase("Hello")); // truecompareTo() compares two strings lexicographically. It returns a positive number if the first is greater, a negative number if it is smaller, and 0 if they are equal.
System.out.println("Hello".compareTo("Hello")); // 0
System.out.println("cargo".compareTo("cathode")); // -2 ('r' is 2 before 't')Other String methods (see the book)
| Method | Purpose |
|---|---|
length(), charAt(i), getChars(...) | Size, character at a position, copy characters to an array |
equals, equalsIgnoreCase, regionMatches | Comparing strings or parts of strings |
startsWith, endsWith | Check the beginning or end |
indexOf, lastIndexOf | Locate characters and substrings |
substring | Extract part of a string |
concat, + | Concatenate strings |
String.valueOf(x) (static) | Convert a value to a String |
Tokenizing strings
A tokenizer partitions a string into individual substrings (tokens) using a delimiter. “His Name is Ali” becomes His, Name, is, Ali. Java offers java.util.StringTokenizer (and String.split).
Regular expressions
A regular expression is a sequence of characters and symbols that describes a search pattern. It is useful for validating input and ensuring data has a particular format. In Java, Pattern is an immutable compiled regular expression and Matcher performs the matching.
import java.util.regex.*;
Pattern p = Pattern.compile(".s"); // . = any single character
Matcher m = p.matcher("as");
boolean b1 = m.matches(); // true
boolean b2 = Pattern.compile(".s").matcher("as").matches(); // true
boolean b3 = Pattern.matches(".s", "as"); // true
System.out.println(Pattern.matches(".s", "mk")); // false (2nd char is not s)
System.out.println(Pattern.matches(".s", "mst")); // false (more than 2 chars)
System.out.println(Pattern.matches("\\d", "1")); // true (one digit)
System.out.println(Pattern.matches("\\d", "abc")); // falseCharacter classes
| Pattern | Matches |
|---|---|
[abc] | a, b or c (simple class) |
[^abc] | Any character except a, b, c (negation) |
[a-zA-Z] | a to z or A to Z (range) |
[a-d[m-p]] | a to d, or m to p (union) |
[a-z&&[def]] | d, e or f (intersection) |
[a-z&&[^bc]] | a to z except b and c (subtraction) |
Quantifiers
| Regex | Meaning |
|---|---|
X? | X occurs once or not at all |
X+ | X occurs once or more times |
X* | X occurs zero or more times |
X{n} | X occurs exactly n times |
X{n,} | X occurs n or more times |
X{y,z} | X occurs at least y times but fewer than z times |
Pattern.matches("[amn]", "a"); // true
Pattern.matches("[amn]", "ammmna"); // false (more than one char)
Pattern.matches("A+", "AAA"); // true
Pattern.matches("[a-zA-Z0-9]{6}", "arun32"); // true
Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"); // false ($ not allowed)Quick check
== or equals to compare string contents?
equals. == compares references.
What does s1.compareTo(s2) return when s1 > s2? When equal?
A positive number, and 0.
What does [^abc] match?
Any single character except a, b or c.
What does A* match?
Zero or more A characters, including the empty string.
Are String objects mutable?
No. They are immutable.
Recursion
Big picture. A recursive method solves a problem by calling itself on a smaller version of the problem until it reaches one simple enough to solve directly.
Recursion concepts
A recursive method calls itself directly or indirectly through another method (A calls B, B calls A). It always has two parts:
1. Base case
The simple problem the method knows how to solve directly. It stops the recursion.
2. Recursive step (call)
The method divides the problem into a base case plus a smaller version of the same problem, and calls itself on the smaller one.
No base case, no end.Without a reachable base case, the method keeps calling itself forever (until the program runs out of memory).
Factorial
n! = n × (n − 1)!, and 1! = 1 is the base case. For example 5! = 5 × 4!, 4! = 4 × 3!, …, 1! = 1.
public static long factorial(long number) {
if (number <= 1) // base case
return 1;
else // recursive step
return number * factorial(number - 1);
}
System.out.println(factorial(3));6
Trace of factorial(3): 3 * factorial(2) → 3 * (2 * factorial(1)) → 3 * (2 * 1) = 6. Each call waits for the next to return. Debugging with a breakpoint shows the chain of method calls in the call stack.
Fibonacci series
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … Each number is the sum of the previous two. Two base cases: fibonacci(0) = 0 and fibonacci(1) = 1.
public static long fibonacci(long n) {
if (n == 0 || n == 1) // base cases
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
System.out.println(fibonacci(2)); // fibonacci(1) + fibonacci(0) = 1 + 01
Recursion vs iteration
| Iteration | Recursion | |
|---|---|---|
| Uses | Repetition structures (for, while, do…while) | Selection structures (if, if…else, switch) |
| Repetition by | Explicitly using a loop | Repeated method calls |
| Terminates when | Loop-continuation condition fails | Base case is satisfied |
| Controlled by | A counter | Dividing the problem into a simpler one |
| Cost | Less overhead | More overhead and more memory |
| Code | Usually longer | Often only a few lines |
Anything that can be solved recursively can also be solved iteratively.
long result = 1; // factorial using iteration
for (int i = 2; i <= 5; i++)
result *= i; // 120Towers of Hanoi
Move all the disks to Tower 3. You cannot place a larger disk onto a smaller disk. The problem is naturally recursive: move the top n−1 disks to the spare tower, move the largest disk to the target, then move the n−1 disks onto it. With 3 disks you need 23 − 1 = 7 moves.
Quick check
What are the two parts of a recursive method?
The base case and the recursive step.
What is the base case of factorial?
1! = 1 (or 0! = 1).
Give two disadvantages of recursion compared with iteration.
More overhead and more memory use.
What is the rule of Towers of Hanoi?
Never place a larger disk on top of a smaller one.
Summary of the DS 230 course slides · Based on Deitel & Deitel, Java: How to Program, Late Objects