Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java Programming
with
Computational
Thinking
- Advanced Placement
Computer Science ASyllabus from College Board:
https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap-computer-science-acourse-description.pdf
For further learning, you should always consult Java document such as
https://docs.oracle.com/javase/tutorial/java/index.html
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 1
Contents
Scope of this document ........................................................................................................ 5
Module 1 - Get Started with Java fundamentals
.................................................... 6
Outcome of Day 1 ............................................................................................................. 6
Using commands Shell ..................................................................................................... 6
Software you need:....................................................................................................... 6
Update the PATH Environment Variable in Window command shell ........................... 6
Let’s make our first java HelloWorld program: ............................................................ 8
Let’s make our first java HelloWorld package: .............................................................. 8
Sample - To make a basic package - a folder of classes . .............................................. 8
Description of Java Conceptual Diagram ........................................................................ 10
Java Compiling Process .................................................................................................. 10
Using an IDE ....................................................................................................................11
Fundamentals in programming structure ....................................................................... 12
Break down each chunk of a user-defined method. .........................................................13
Exercises – Polish your Programming Skill ......................................................................13
Interactive Discussion .....................................................................................................13
Practice! Practice! ............................................................................................................13
Module 2 – Classes and Objects
....................................................................... 14
Outcome of Day 2........................................................................................................... 14
Topics to discuss: ............................................................................................................ 14
UML: ............................................................................................................................... 15
Basic I/O.......................................................................................................................... 16
Basic Wrapper Classes - Integer, Float, Double .............................................................. 18
Basics in String Class ...................................................................................................... 21
Keywords (under AP CS A) ............................................................................................. 22
Reference Type Note ...................................................................................................... 27
Exercises ......................................................................................................................... 29
Day 3 Inheritance and polymorphism ................................................................................ 30
Outcome of Day 3 ........................................................................................................... 30
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 2
Topics to discuss: ............................................................................................................ 30
Is-a Relationship / Inheritance ........................................................................................ 30
Has-a Relationship / Composition ....................................................................................31
Realization - Interface / Implementation ........................................................................ 32
Realization – Abstract classes / extends...........................................................................33
Why the order of extends before implements .............................................................33
Polymorphism ................................................................................................................ 34
Short Questions and Exercises: Object-Oriented Programming Concepts ..................... 35
About Composition (has-a) ............................................................................................ 40
Exercises on Inheritance ............................................................................................. 43
Module 3 - Array and Array List
................................................................. 48
Do not use Raw Type: ................................................................................................ 49
Simple Array syntax ........................................................................................................ 50
String Array ........................................................................................................ 52
“How-to” about using ArrayList...................................................................................... 53
Day 4&5 Recursion and Basics in Search and Sorting Algorithms
............................... 61
Search & Sort.................................................................................................................. 61
Recursion ........................................................................................................................ 61
Sequential Search ....................................................................................................... 62
Binary Search.............................................................................................................. 62
Sorting ........................................................................................................................ 63
Selection Sort ............................................................................................................. 63
Insertion Sort .............................................................................................................. 64
Quick Sort ................................................................................................................... 64
Merge Sort .................................................................................................................. 65
Day 5 –Practice! Practice! ............................................................................................... 66
Appendix ............................................................................................................................ 67
Advanced Placement Computer Science Syllabus .......................................................... 67
2016 AP CS A Syllabus ................................................................................................ 67
Java Quick Reference ..................................................................................................... 70
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 3
Answers to Questions in Day 2 ....................................................................................... 72
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 4
SCOPE OF THIS DOCUMENT
-
-
Covers all required by AP Computer Science -A
Covers most important fundamentals about OOPs. Many of these topics are not
covered in this AP CS – A.
The purpose of this document is to educate you the importance of OOPS and the
basic data structure using Java while covering AP CS requirement; not the other way
around.
Topics not required by AP CS-A is marked with .
Important Assumption
-
This is written for students who already have taken at least up to Level I of the
Algorithms in C at SR.
For total beginner, you should consult a Java Tutorial book instead.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 5
MODULE 1 - GET STARTED WITH JAVA FUNDAMENTALS
Outcome of Day 1
-
Compile in command shell and rudimentary understand the folders/path/system
environment requirement
Create:
o a few Java programs using simple text editor
o Nested control structure with if-else and while/for loop.
o Complete a list of QnA Exercises including some from the AP Barons’ book,
and some external ones provided by your instructor.
o a simple class, and methods - - circle, square, rectangle and trapezoid.
o Java doc.
Using commands Shell
Software you need:
Java Development Kit
-
We use Windows x64 platform version
http://www.oracle.com/
Download the latest JDK and install it.
In our case, it is installed at : <your default Program Files folder>\Java\< the latest
version >
IDE :
-
You may download eclipse ; or
In our case, we use notepad++ to edit files, then you build the byte code yourself using
command prompt.
Update the PATH Environment Variable in Window
command shell
Use any text editor such as notepad to create a file setVar.bat with the following:
echo %ProgramFiles%
set jdk=%ProgramFiles%\Java\jdk1.8.0_92
set path=%path%;%jdk%\bin
set classpath=%jdk%\lib;%jdk%\jre\lib;
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 6
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 7
Let’s make our first java HelloWorld program:
1. Open command prompt. For example, your workspace folder is at : z:\s2016\cs\joey\
, you should type in:
cd z:\s2016\cs\joey
2. Edit sayHello.java (note the file name must be same as the class name)
public class sayHello {
public static void main(String[] args) {
System.out.println("Hey! Hello World!");
}
}
3. To Build and Run the code
cd z:\s2016\cs\joey\
javac sayHello.java # to build the byte code
java -cp ./ HelloWorld
Let’s make our first java HelloWorld package:
A package contains a collection of classes, e.g. java.lang contains many commonly used
classes. To include others –
Import packageName.*; or
Import packageName.thisClass;
Import packagename.subpackageName.classname;
Sample - To make a basic package - a folder of classes .
1. Go to your workspace folder, and create a package, i.e. create a folder.
E.g. workspace : z:\s2016\cs\joey
Package name : hey
cd z:\s2016\cs\joey
To make the following folders, e.g.:
mkdir hey
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 8
In each folder, create a java file call sayHello.java as following, e.g English:
package hey.English;
public class sayHello{
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
The only difference in French and Spanish :
o string “Hello World!”. In French – “Bonjour le monde”. In Spanish – “Hola
Mundo”.
o Package name – changed to, e.g., “package hey.French”
To compile them in byte-mode:
C:\>your workshop>
C:\> your workshop>
C:\> your workshop>
javac ./hey/English/sayHello.java
javac ./hey/Spanish/sayHello.java
javac ./hey/French/sayHello.java
C:\> your workshop>
javac -Xlint ./hey/French/sayHello.java
Or
-Xlint : enabled to see the detailed warnings.
To run them:
C:\> your workshop>
C:\> your workshop>
C:\> your workshop>
java -cp
java -cp
java -cp
./
./
./
hey.English.sayHello
hey.Spanish.sayHello
hey.French.sayHello
Watch the classpath ( -cp ./ or cp ../ ) :
C:\hey\> java -cp
C:\hey\> java -cp
./
./
However, you can:
C:\hey\> java -cp ../
French.sayHello
<<< failed to load
hey.French.sayHello
<<< failed to load
hey.French.sayHello
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 9
Description of Java Conceptual Diagram
http://www.oracle.edu)
Java Compiling Process
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 10
Using an IDE
Pay attention the proper style: package name should start with lower-case.
Right click on your class in the Package Explorer and select Run As > Java Application.
The Console view
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 11
Fundamentals in programming structure
-
Identifiers – variables, parameters, constant, user-defined method, user-defined
class.
Primitive data types
Basics in static main Class
Final constant, user-defined method, user-defined class & variables.
Boolean operations and operators
Control structure - if-else, for/while loop
Scope
Standard IO ( IO package)
Throw new exceptions
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 12
Break down each chunk of a user-defined method.
(http://introcs.cs.princeton.edu)
Calling other static methods. Any static method defined in a .java file can call any other static
method in the same file or any static method in a Java library like Math.
Exercises – Polish your Programming Skill
http://learn.stormingrobots.com , locate “AP Computer Science Exercises” . Work on the
Bare Basic Programming in Java.
Interactive Discussion
Problem 1 to 26 in chapter 1. Of the Barron’s book.
Practice! Practice!
-
Be resourceful! Look at the information from
https://docs.oracle.com/javase/7/docs/api/ for more learning about Java
Be curious! Get a sample, and try a few different ways to do the same thing.
Since 75% of the AP CS A covers basic programming and control structure, i.e. basic
array, loop, if-else, while, for, it is important that you will practice basic
programming – refer to http://learn.stormingrobots.com. (Many of SR Algorithms
in C/C++ students, with just Level I completion, score “5” in the exam and with little
extra effort to learn the basic OOP concepts. They all have to do all those exercises
posted under the Computer Science in that link.)
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 13
MODULE 2 – CLASSES AND OBJECTS
Outcome of Day 2
-
Creating user-defined classes/methods, and creation of objects
Experience in rudimentary in designing with UML
Be able to describe and provide examples for major Key terms and concepts in
Objects Oriented Programming Concepts (OOPs)
Additional: Know how to convert from one base to another base - the hexadecimal,
decimal and binary bases.
Know how to use the basic wrapper classes – Integer, Float, Double
Topics to discuss:
-
Bases – hex | dec | binary
Public, Private, Static
Types of methods :
Constructor
Accessors
Mutators,
Static methods vs Instant Methods
Driver Class; Static methods in a Driver class
Methods Overloading
Method Parameters
o Reference vs. Primitive Data Types
o Null Reference
o Formal vs Actual
o Primitive data type as parameters
o Object type as parameters
Know how to convert base-10 to base-16 and base -2
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 14
UML:
It simplifies the complex process of software design, creating a "blueprint" for
construction.
In software development, there is no substitute for simplicity.
One way to achieve simplicity is to develop high-level software structures that limit
the complexity of interactions among components, i.e. software architecture.
System designers can use UML to diagram functional structures.
UML provides a set of diagrams to depict software structures graphically.
UML focuses on three aspects of the functional structures: data, interaction, and
evolution.
o The data is modeled in class diagrams. Classes are central pieces of data
modeling in UML.
o Interaction is modeled with a sequence diagram or a collaboration diagram.
These diagrams describe how classes interact to achieve a specific task of the
application.
o Evolution in this context defines the modeling that explicitly describes states
of the systems and their transitions. Evolution is typically modeled with state
diagrams embedded in objects.
UML offers other diagrams, classes, sequence, and state diagrams strongly define the main
functional structure of the software.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 15
Basic I/O
import java.io.File;
import java.io.FileNotFoundException; // optional
import java.util.Scanner;
Standard Input
Scanner stdin = new Scanner( System.in );
stdin.next(); // to read from standard input
Standard Output
System.out.println("Hello\n”);
File Input
File infp = new File("inFileName.txt");
Scanner sInfp = new Scanner(infp);
Or
Scanner sInfp = new Scanner (new File("inFileName.txt");
String str = stdin.next();
int ct = stdin.nextInt();
or
String line = stdin.nextLine();
// for complete reference: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Before you can use the methods, you need to import the classes:
import java.io.File;
import java.util.Scanner;
// not in AP CS ---------------import java.io.FileInputStream; // the fastest output classes. Or you will need to use JNI
import java.io.FileOutputStream;
import java.io.PrintStream;
//--------------
Note: you can use “BufferWriter”. While it provides much handy methods, it is very slow.
Complete reference:
https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 16
Sample to use standard I/O and file input :
public class tRead {
public static void main(String[] args) {
try {
// create a reference to the standard input and read from stdin
Scanner stdin = new Scanner(System.in);
System.out.print("Enter file name to be read: ");
String fname = stdin.next();
int ct = stdin.nextInt();
System.out.println("You have Entered " + fname + " " + ct);
System.out.println("Hit a key to continue");
System.in.read();
// wait for an enter key
// read from input file
File fp = new File(fname);
// create a file object
Scanner fin = new Scanner(fp); // create a reference to the file object for read
if (ct==0) {
while (fin.hasNextLine()) {
String line = fin.nextLine(); System.out.println(line);
}
}
else {
while (fin.hasNextLine() && ct-->=0) {
String line = fin.nextLine(); System.out.println(line);
}
}
fin.close();
//==now write it back out to another file. But just by byte
fname = fname + "out";
FileOutputStream fos =new FileOutputStream(fname);
fos.write('A'); // cannot write with string
//==unfortunately, you need another stream to write text
final PrintStream ps = new PrintStream(fos);
ps.print(" How Silly!\n");
ps.close();
fos.close();
}
}
}//try
catch (Exception ex) {
System.out.println("UGH!");
ex.printStackTrace();
} // end of try/catch block
// end of main
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 17
Basic Wrapper Classes - Integer, Float, Double
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
java.lang.Integer
(Note: However, you do not need to import that into your code, as java.lang.* is imported
by default . Integer is an intrinsic class, not a primitive type)
int val = 254;
int val = 0xfe;
// same in base16 (hex)
int val = 0b11111110; // same in base2 (binary)
int val = 0376;
// same in base8 (octal)
System.out.println("hex: " + Integer.toHexString(val) );
System.out.println("oct: " + Integer.toOctalString(val) );
System.out.println("bin: " + Integer.toBinaryString(val) );
Output:
hex: fe
oct: 376
bin: 11111110
// these show the min and max value of an Integer object
Integer.MIN_VALUE
Integer.MAX_VALUE
Integer x = new Integer(123456);
Integer obj = new Integer(15); // returns the value of this Integer as an int
int i = obj.intValue(); // you can also do this with “Double”, or “Float”, etc.
java.lang.Double
Float y = new Float(9876f);
Integer x = new Integer(123456);
Double dd = new Double(10.994);
// print their value as double
System.out.println("x as integer :" + x );
System.out.println("x as double:" + x.doubleValue() );
System.out.println("y as float::" + y );
System.out.println("y as double:" + y.doubleValue() );
System.out.println("Double : " + dd.intValue()); // truncate
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 18
Other misc Math methods covered in AP CS:
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 19
What if the value is an one byte integer:
public class Str {
static void prt(int ival)
{
System.out.println("\nValue : " + ival);
System.out.println("hex: " + Integer.toHexString(ival) );
System.out.println("oct: " + Integer.toOctalString(ival) );
System.out.println("bin: " + Integer.toBinaryString(ival) );
if (ival< 0)
System.out.println("abs: " + Math.abs(ival));
}
static void prt(char cval)
{
System.out.println("\nchar Value: " + cval); // get '?' it does not know what to do!
System.out.println("hex: " + Integer.toHexString(cval) );
System.out.println("oct: " + Integer.toOctalString(cval) );
System.out.println("bin: " + Integer.toBinaryString(cval) ); //2 byte print!!!
System.out.println("dummybin: " + Integer.toBinaryString(cval & 0xff) ); // force to one byte
if (cval< 0)
System.out.println("abs: " + Math.abs(cval));
}
public static void main(String[] args)
{
int iVal;
char cVal;
if (args.length < 1) {
iVal = 10;
}
else
iVal = Integer.parseInt(args[0]);
prt(iVal);
prt(-iVal);
cVal = (char)(iVal & 0xffff);
prt(cVal);
prt(-cVal); // become an integer instead
cVal = (char)(-1 * cVal);
prt(cVal); // pass in as char
}
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 20
Basics in String Class
(Again, there are a lot more about String. Consult the online official Java API
documentation.)
String substring(int fromIndex, int toIndex)
// returns the substring beginning at fromIndex to toIndex
String substring(Index); // returns substring byte Index to str.length() . Start from 0, not 1
int indexOf(String str) // returns the index of the first occurrence of str;
// returns -1 if not found
int compareTo(String other)
// returns a value < 0 if this is less than other
// returns a value = 0 if this is equal to other
// returns a value > 0 if this is greater than other
// Compare two strings
new String("test").equals("test")
// true
new String("test") == "test"
// false; they are not the same object
new String("test") == new String("test") // false; not the same object
"test" == "test"
// true ; literals are internalized as same object
// But you should really just call Objects.equals()
Objects.equals( "test", new String("test")) // --> true
Objects.equals( null, "test") // --> false
//=============================================
String foo1 = new String("foo");
String foo2 = new String("foo");
fooString1 == fooString2; // false
fooString1.equals(fooString2);
// true
//=============================================
String nullString1 = null;
String nullString2 = null;
nullString1 == nullString2; // true
nullString1.equals(nullString2);
// throws an exception
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 21
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Keywords (under AP CS A)
Class
A class is a blueprint or prototype from which objects are created
Object
An instant of object - have state and behavior
Inheritance
Different kinds of objects often have a certain amount in common with each
other. Mountain bikes, road bikes, and tandem bikes, for example, all share
the characteristics of bicycles (current speed, current pedal cadence, current
gear). Yet each also defines additional features that make them different:
tandem bicycles have two seats and two sets of handlebars; road bikes have
drop handlebars; some mountain bikes have an additional chain ring, giving
them a lower gear ratio.
Sample to show most of the terms…
public class Employee {
private String name;
private final String ssn;
float wage;
public Employee {
wage = 30000;
}
Keyword:
extends
super
public Employee( float amt) {
wage = amt;
}
subclass
A sub-class “is-a” a super-class, such as;
-
Interface
Class
Staff is a super-class.
Mr. Smith is-a staff.
Mr. Smith extends staff
Mr. Smith is-a subclass of staff
public void setName(String name)
if (name != null && name.length() > 0)
this.name = name;
}
An interface is a group of related methods with empty bodies. Cannot be
substantiated.
public String getName() {
return this.name;
}
Like function prototype in C/C++.
A class implements an Interface class will implement the methods.
Abstract
Class
Just like Interface, except it may contain static instance method.
Package
package is a namespace that organizes a set of related classes and
interfaces.
public String getSsn() {
return this.ssn;
}
A class extends an Abstract class may implement the abstract methods.
you can think of packages as being similar to different folders on your
computer
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
{
908-595-1010
}
Q: ssn : why not just “private String”
Why not “static final”
www.stormingrobots.com
P. 22
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Public:
Allow access the property outside the object.
Sample Class Static method:
Private:
Attributes accessible only within an object itself.
System.out.println(today);
Final:
Single instance can be set only once.
Constructor:
Invoked to create objects from the class blueprint.
You never instantiated the System class and out is
referred to directly from the class. This is because out
is declared as a static variable-
Should have constructor.
Accessors
also known as a getter — returns some property of an object, such
as getPropertyName, isPropertyName
public type / particularly used for validation and notification.
Mutators
also known as a setter — changes some property of an object,
such as setPropertyName
Instance variable:
Date today = new Date();
“today” is an instance variable.
public class Rectangle {
private int x, y;
private int width, height;
Public type / particularly used for validation and notification.
static final
public Rectangle() {
this(0, 0, 1, 1);
}
Constant, e.g. static final double PI = 3.141592653589793
Encapsulation Make some variables/methods Only accessible inside the object –
Such as set attributes private and write getters and/or setters
Method
overloading
define two or more methods within the same class that share the
same name, but their parameter declarations are different
Primitives
int, float , etc.
Reference
type
Data type referring to the address of the data or object type. E.g.
public Rectangle(int width, int height){
this(0, 0, width, height);
}
Employee Joey = new Employee();
// should always free it when you are done with it.
Eg.. Joey = null;
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
}
908-595-1010
public Rectangle(int x, int y,
int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
www.stormingrobots.com
P. 23
Java Programming with Computational
Thinking / AP CS A
Formal vs.
int max(int a, int b) {
parameters
Actual Parameters
Engineering and Computational Thinking For Pre-College
// a & b are formal
if (a > b) return a;
else return b;
(parameters also called }
void doWork( )
arguments)
{
int x = 10, y = 20;
int m = max (x , y); // x & y are actual
parameters
}
Methods and variables
Static
methods
variables
Instance methods
/ Static class method and variable occurs once per class.
Variable / methods associated with the class rather
than with an instance of the class
An abstract method is a method that is declared
without an implementation (without braces, and
followed by a semicolon), like this:
abstract void moveTo(double deltaX, double
deltaY);
If a class includes abstract methods, then the
class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
Instance method and variable occurs once per instance
of a class. (an object)
Methods and variables that are not declared as static
are known as instance methods and instance variables.
this
Within an instance method or a constructor, this is a reference to
the current object
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 24
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Polymorphism Subclasses of a class can define their own unique behaviors and
yet share some of the same functionality of the parent class.
http://docs.oracle.com/javase/tutorial/java/IandI/
polymorphism.html
Is-a
Inheritance
A sub-class is-a superclass.
Has-a
A class has an object (Composition)
http://www.w3resource.com/java-tutorial/inheritancecomposition-relationship.php
Samples about classes declaration:
interface GeometryInterfaces {
// constant declarations, if any
…
void draw();
void resize();
void findArea();
void findPerimeter();
}
abstract class AbsShapes implements GeometryInterfaces{
int x, y;
...
void moveTo(int newX, int newY) {
// this can be method implementation here.
}
Void resize();
{
// must implement it as it is not an abstract method.
}
abstract void draw();
// as it is an abstract method, you do not have to implement
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 25
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
Reference:
http://beginnersbook.com/2014/07/final-keyword-java-final-variable-method-class/
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 26
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Reference Type Note
Best is to show with examples. Let’s take static and instance variable along as example. static means "associated with the type itself,
rather than an instance of the type.
public class Test {
int instanceVariable ;
static int staticVariable;
final static int staticConst = 50;
public static void main(String[] args)
{
Test x = new Test();
Test y = new Test(90);
Test p = y;
System.out.println("x-default: " + x.instanceVariable);
System.out.println("static: " + x.staticVariable);
System.out.println("y-before: " + y.instanceVariable);
System.out.println("static: " + y.staticVariable);
Test ( ) {
// constructor
instanceVariable = 0;
staticVariable = -1;
}
p.instanceVariable = 45;
System.out.println("y-after: " + y.instanceVariable);
System.out.println("static: " + y.staticVariable);
Test (int i) {
instanceVariable = i;
staticVariable = i *10;
}
Test z = new Test();
System.out.println("z-: " + z.instanceVariable);
System.out.println("z-static: " + z.staticVariable);
System.out.println("y-static: " + y.staticVariable);
System.out.println("x-static: " + x.staticVariable);
System.out.println("Test .staticConst = " + Test.staticConst );
}
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 27
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Why “this”?
The this keyword is primarily used in three situations.
in setter methods to disambiguate variable references.
when there is a need to pass the current class instance as an argument to a method of another object. Good for handling of Variable
Hiding.
Is as a way to call alternate constructors from within a constructor.
See the sample on the right.
public class fooThis {
private String name;
What is the output? If not sure, code it.
Or better yet try a few different version.
fooThis( )
Be creative and curious!
fooThis ( String name ) {
{
this("Frank");
}
this.name = name;}
public void demo( ) {
String name = "Joey";
System.out.println("local name: "+ name);
System.out.println( "instance name: "+ this.name);
}
public static void main (String [] args ) {
fooThis test1 = new fooThis ( "John");
test1.demo();
fooThis test2 = new fooThis();
test2.demo();
}
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 28
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Exercises
1) Create your own text file containing N number of words. Write a Java program to read in all words and produce the count of anagrams
and what they are.
e.g
Debit card
Bad credit
XXX
Dormitory
Dirty Room
Astronomer
Moon starrer
School master
The classroom
I am Lord Voldemort
Tom Marvolo Riddle
Your output:
5 sets of anagrams
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 29
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
DAY 3 INHERITANCE AND POLYMORPHISM
Outcome of Day 3
Familiar with the characteristics of inheritance and keywords:
Know Transitive Is-a relationship
Complete writing superclass vs sub classes with keyword “extends”
Sting http://www.tutorialspoint.com/java/java_strings.htm
Topics to discuss:
-
-
Inheritance
o “extends” | is-a
o Method Over-riding and the “super” keywords
o Constructor and “super”
o Declaring subclass objects
Composition - Has-a
Interface Class - implements
Abstract Class - extends
Polymorphism
Optional - Dynamic binding
Is-a Relationship / Inheritance
Employee
Is – a
Headmaster
|
Secretary
extend
| inherit
Administrator
Professors
A child/sub class assumes the same functionalities of the parent/super class. In other words, the
child/subclass is a specific type of the parent class. A child/sub class may contain a lot more information
than a parent/super class.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 30
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Has-a Relationship / Composition
Car
Engine
Detect collision
Windshields
Wheels
Emphasizing the dependence of the contained class to the life cycle of the container class. the contained
class will be obliterated when the container class is destroyed.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 31
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Realization - Interface / Implementation
An interface is a contract: the guy writing the interface says, "hey, I accept things looking that way", and
the guy using the interface says "Ok, the class I write will look that way". Another example: take the wall
socket as an example. Residential socket in USA allow 120V with Type A, B, and C plugs – interface. But,
many manufactures will follow that interface with for various applications/implementations.
An interface is an empty shell, there are only the signatures of the methods, which implies that the
methods do not have a body. The interface can't do anything. It's just a pattern.
Sample show interface implementation
Sample contains 2 files under folder
name motors. To build:
-
javac -cp ./ motors/Car.java
This will generate both Car.class and
MotorVehicle.class in the folder
“motors”.
Note:
package motors;
interface MotorVehicle
{
void run();
int getFuel();
}
Implementing an interface consumes
very little CPU, because it's not a
class, just a bunch of names, and
therefore there is no expensive lookup to do. It's great when it matters
such as in embedded devices.
package motors;
class Car implements MotorVehicle {
int fuel=100;
String color, name;
Car ( ){
color = "Red";
name = "SR";
}
Car (String c, String name) {
color = c;
this.name = name;
}
public int getFuel() {
return this.fuel;
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
public void run() {
System.out.println(color + " "+ name
+ " Wrroooooooom down the road with "
+ "Fuel " + fuel);
}
public void setColor(String color){
color = this.color;
}
public static void main(String []args){
Car mycar = new Car("blue", "coolJoe");
mycar.run(); // why can't you just call run()?
}
} // end of Car class
908-595-1010
www.stormingrobots.com
P. 32
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Realization – Abstract classes / extends
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for
them. It's more about a guy saying, "these classes should look like that, and they have that in common, so
fill in the blanks!".
Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up
to do when you inherit from them. Abstract classes are an excellent way to create planned inheritance
hierarchies.
Putting Abstract class and interface all together:
Modification to the Car example above
package motors;
Changes to the Car driver class:
public class Engine {
public void start(){
System.out.println("Engine
Started:");
}
class Car extends Engine implements MotorVehicle {
public void stop(){
System.out.println("Engine
Stopped:");
}
}
...
public static void main(String []args) {
Car mycar = new Car("blue", "coolJoe");
mycar.start();
mycar.run();
mycar.stop();
}
}
NOTE:
NO multiple inheritance! that's why you can't extend a class from two different classes at the same time.
Rather, you should use multiple interfaces to include additional functionality.
Why the order of extends before implements
When the Java compiler turns a class into bytecode, it must first look to a parent class. That is because the
underlying implementation of classes is to point to the bytecode of the parent class - which holds the
relevant methods and fields. Then it adds in pointers to the code of the child class functions - some of which
are mandated by the 'implements' keyword.
Because the parent class must be compliable, it is easier if the compiler knows up front what that class is.
Further, you can extend only one class but implement any number of interfaces. The compilation time
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 33
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
climbs if the extends keyword can be intermingled amongst any number of implements instructions.
Compilers want to fail as fast as possible to decrease dev time, so this choice is logical. Further, it helps you
think clearly about the class for the same reason.
Polymorphism
Subclasses of a class can define their own unique behaviors and yet share some of the same functionality
of the parent class.
public abstract class Shape {
public class Ellipse extends Shape {
….
}
public Shape(String id)
{ this.id = id; }
public class Polygon extends Shape {
int length ….
}
// must be implemented in the subclass.
public abstract float getArea( );
public abstract float perimeter( );
public class Square extends Polygon {
int length; ….
}
public string getId( )
{
return id;
}
public String toString()
{
// do something..
}
…
public class Circle extends Ellipse {
….
}
*** Cannot instantiate an shape object:
Shape s = new Shape("s1"); // Failed!**
}
Create one of the following. If not, why ?
1) Static variable
2) Static method
3) Final variable
4) Final method
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
Reference for deep learning: from
Carnegie Mellon University.
908-595-1010
www.stormingrobots.com
P. 34
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Short Questions and Exercises: Object-Oriented Programming
Concepts
1.
2.
3.
4.
5.
6.
7.
8.
9.
Real-world objects contain ___ and ___.
A software object's state is stored in ___.
A software object's behavior is exposed through ___.
Hiding internal data from the outside world, and accessing it only through publicly exposed
methods is known as data ___.
A blueprint for a software object is called a ___.
Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.
A collection of methods with no implementation is called an ___.
A namespace that organizes classes and interfaces by functionality is called a ___.
The term API stands for ___?
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 35
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
(Excellent reference: Nanyang Technological University)
Sample Classes
The Circle Class (An Introduction to Classes and Instances)
This first exercise will lead you through all the basic concepts in OOPs.
A class called circle is designed as shown in the following class diagram. It contains:
Two private instance variables: radius (of the type double) and color (of the type String), with
default value of 1.0 and "red", respectively.
Two overloaded constructors - a default constructor with no argument, and a constructor which
takes a double argument for radius.
Two public methods: getRadius() and getArea(), which return the radius and area of this
instance, respectively.
The source codes for Circle.java is as follows:
/*
* The Circle class models a circle with a radius and color.
*/
public class Circle { // Save as "Circle.java"
// private instance variable, not accessible from outside this class
private double radius;
private String color;
// The default constructor with no argument.
// It sets the radius and color to their default value.
public Circle() {
radius = 1.0;
color = "red";
}
// 2nd constructor with given radius, but color default
public Circle(double r) {
radius = r;
color = "red";
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 36
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
}
// A public method for retrieving the radius
public double getRadius() {
return radius;
}
// A public method for computing the area of circle
public double getArea() {
return radius*radius*Math.PI;
}
}
Compile "Circle.java". Can you run the Circle class? Why?
This Circle class does not have a main() method. Hence, it cannot be run directly. This Circle class
is a “building block” and is meant to be used in another program.
Let us write a test program called TestCircle (in another source file called TestCircle.java) which
uses the Circle class, as follows:
public class TestCircle { // Save as "TestCircle.java"
public static void main(String[] args) {
// Declare an instance of Circle class called c1.
// Construct the instance c1 by invoking the "default" constructor
// which sets its radius and color to their default value.
Circle c1 = new Circle();
// Invoke public methods on instance c1, via dot operator.
System.out.println("The circle has radius of "
+ c1.getRadius() + " and area of " + c1.getArea());
// Declare an instance of class circle called c2.
// Construct the instance c2 by invoking the second constructor
// with the given radius and default color.
Circle c2 = new Circle(2.0);
// Invoke public methods on instance c2, via dot operator.
System.out.println("The circle has radius of "
+ c2.getRadius() + " and area of " + c2.getArea());
}
}
Now, run the TestCircle and study the results.
System.out.println("radius is: " + c4.getRadius()); // Print radius via
getter
c4.setColor(......);
// Change color
System.out.println("color is: " + c4.getColor());
// Print color via getter
// You cannot do the following because setRadius() returns void,
// which cannot be printed.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 37
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
System.out.println(c4.setRadius(4.0));
1. Keyword "this": Instead of using variable names such as r (for radius) and c (for color)
in the methods' arguments, it is better to use variable names radius (for radius) and color (for
color) and use the special keyword "this" to resolve the conflict between instance variables
and methods' arguments. For example,
// Instance variable
private double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
// "this.radius" refers to the instance
variable
// "radius" refers to the method's parameter
color = .......
}
// Setter of radius
public void setRadius(double radius) {
this.radius = radius;
// "this.radius" refers to the instance
variable
// "radius" refers to the method's argument
}
Modify ALL the constructors and setters in the Circle class to use the keyword "this".
2. Method toString(): Every well-designed Java class should contain a public method
called toString() that returns a short description of the instance (in a return type of String).
The toString() method can be called explicitly (via instanceName.toString()) just like any
other method; or implicitly through println(). If an instance is passed to the
println(anInstance) method, the toString() method of that instance will be invoked
implicitly. For example, include the following toString() methods to the Circle class:
// Return a description of this instance in the form of
// Circle[radius=r,color=c]
public String toString() {
return "Circle[radius=" + radius + " color=" + color + "]";
}
Try calling toString() method explicitly, just like any other method:
Circle c1 = new Circle(5.0);
System.out.println(c1.toString());
// explicit call
toString() is called implicitly when an instance is passed to println() method, for example,
Circle c2 = new Circle(1.2);
System.out.println(c2.toString());
System.out.println(c2);
// explicit call
// println() calls toString() implicitly,
same as above
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 38
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
System.out.println("Operator '+' invokes toString() too: " + c2);
// '+'
invokes toString() too
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 39
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
About Composition (has-a)
The MyPoint Class
A class called MyPoint, which models a 2D point with x and y coordinates, is designed as shown in the
class diagram. It contains:
Two instance variables x (int) and y (int).
A default (or "no-argument" or "no-arg") constructor that construct a point at the default location
of (0, 0).
A overloaded constructor that constructs a point with the given x and y coordinates.
Getter and setter for the instance variables x and y.
A method setXY() to set both x and y.
A method getXY() which returns the x and y in a 2-element int array.
A toString() method that returns a string description of the instance in the format "(x, y)".
A method called distance(int x, int y) that returns the distance from this point to another
point at the given (x, y) coordinates, e.g.,
MyPoint p1 = new MyPoint(3, 4);
System.out.println(p1.distance(5, 6));
An overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another), e.g.,
MyPoint p1 = new MyPoint(3, 4);
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 40
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
MyPoint p2 = new MyPoint(5, 6);
System.out.println(p1.distance(p2));
Another overloaded distance() method that returns the distance from this point to the origin
(0,0), e.g.,
MyPoint p1 = new MyPoint(3, 4);
System.out.println(p1.distance());
You are required to:
1. Write the code for the class MyPoint. Also write a test program (called TestMyPoint) to test all
the methods defined in the class.
Hints:
// Overloading method distance()
// This version takes two ints as arguments
public double distance(int x, int y) {
int xDiff = this.x – x;
int yDiff = ......
return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
}
// This version takes a MyPoint instance as argument
public double distance(MyPoint another) {
int xDiff = this.x – another.x;
.......
}
// Test program to test all constructors and public methods
MyPoint p1 = new MyPoint(); // Test constructor
System.out.println(p1);
// Test toString()
p1.setX(8);
// Test setters
p1.setY(6);
System.out.println("x is: " + p1.getX()); // Test getters
System.out.println("y is: " + p1.getY());
p1.setXY(3, 0);
// Test setXY()
System.out.println(p1.getXY()[0]); // Test getXY()
System.out.println(p1.getXY()[1]);
System.out.println(p1);
MyPoint p2 = new MyPoint(0, 4); // Test another constructor
System.out.println(p2);
// Testing the overloaded methods distance()
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 41
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
System.out.println(p1.distance(p2));
System.out.println(p2.distance(p1));
System.out.println(p1.distance(5, 6));
System.out.println(p1.distance());
//
//
//
//
which
which
which
which
version?
version?
version?
version?
Write a program that allocates 10 points in an array of MyPoint, and initializes to (1, 1), (2, 2), ...
(10, 10).
Hints: You need to allocate the array, as well as each of the 10 MyPoint instances. In other words,
you need to issue 11 new, 1 for the array and 10 for the MyPoint instances.
MyPoint[] points = new MyPoint[10];
// Declare and allocate an array of
MyPoint
for (int i = 0; i < points.length; i++) {
points[i] = new MyPoint(...);
// Allocate each of MyPoint instances
}
// use a loop to print all the points
Notes: Point is such a common entity that JDK certainly provided for in all flavors.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 42
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Exercises on Inheritance
Ex1 - The Circle and Cylinder Classes
This exercise shall guide you through the important concepts in inheritance.
In this exercise, a subclass called Cylinder is derived from the superclass Circle as shown in the class
diagram (where an an arrow pointing up from the subclass to its superclass). Study how the subclass
Cylinder invokes the superclass' constructors (via super() and super(radius)) and inherits the
variables and methods from the superclass Circle.
You can reuse the Circle class that you have created in the previous exercise. Make sure that you
keep "Circle.class" in the same directory.
public class Cylinder extends Circle { // Save as "Cylinder.java"
private double height; // private variable
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 43
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
// Constructor with default color, radius and height
public Cylinder() {
super();
// call superclass no-arg constructor Circle()
height = 1.0;
}
// Constructor with default radius, color but given height
public Cylinder(double height) {
super();
// call superclass no-arg constructor Circle()
this.height = height;
}
// Constructor with default color, but given radius, height
public Cylinder(double radius, double height) {
super(radius); // call superclass constructor Circle(r)
this.height = height;
}
// A public method for retrieving the height
public double getHeight() {
return height;
}
// A public method for computing the volume of cylinder
// use superclass method getArea() to get the base area
public double getVolume() {
return getArea()*height;
}
}
Write a test program (says TestCylinder) to test the Cylinder class created, as follow:
public class TestCylinder { // save as "TestCylinder.java"
public static void main (String[] args) {
// Declare and allocate a new instance of cylinder
//
with default color, radius, and height
Cylinder c1 = new Cylinder();
System.out.println("Cylinder:"
+ " radius=" + c1.getRadius()
+ " height=" + c1.getHeight()
+ " base area=" + c1.getArea()
+ " volume=" + c1.getVolume());
// Declare and allocate a new instance of cylinder
//
specifying height, with default color and radius
Cylinder c2 = new Cylinder(10.0);
System.out.println("Cylinder:"
+ " radius=" + c2.getRadius()
+ " height=" + c2.getHeight()
+ " base area=" + c2.getArea()
+ " volume=" + c2.getVolume());
// Declare and allocate a new instance of cylinder
//
specifying radius and height, with default color
Cylinder c3 = new Cylinder(2.0, 10.0);
System.out.println("Cylinder:"
+ " radius=" + c3.getRadius()
+ " height=" + c3.getHeight()
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 44
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
+ " base area=" + c3.getArea()
+ " volume=" + c3.getVolume());
}
}
Method Overriding and "Super": The subclass Cylinder inherits getArea() method from
its superclass Circle. Try overriding the getArea() method in the subclass Cylinder to compute the
surface area (=2π×radius×height + 2×base-area) of the cylinder instead of base area. That is, if
getArea() is called by a Circle instance, it returns the area. If getArea() is called by a Cylinder
instance, it returns the surface area of the cylinder.
If you override the getArea() in the subclass Cylinder, the getVolume() no longer works. This is
because the getVolume() uses the overridden getArea() method found in the same class. (Java
runtime will search the superclass only if it cannot locate the method in this class). Fix the getVolume().
Hints: After overridding the getArea() in subclass Cylinder, you can choose to invoke the getArea()
of the superclass Circle by calling super.getArea().
TRY:
Provide a toString() method to the Cylinder class, which overrides the toString() inherited from
the superclass Circle, e.g.,
@Override
public String toString() {
// in Cylinder class
return "Cylinder: subclass of " + super.toString()
toString()
+ " height=" + height;
}
//
use
Circle's
Try out the toString() method in TestCylinder.
Note: @Override is known as annotation (introduced in JDK 1.5), which asks compiler to check whether
there is such a method in the superclass to be overridden. This helps greatly if you misspell the name
of the toString(). If @Override is not used and toString() is misspelled as ToString(), it will be
treated as a new method in the subclass, instead of overriding the superclass. If @Override is used, the
compiler will signal an error. @Override annotation is optional, but certainly nice to have.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 45
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Superclass Person and its subclasses
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 46
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Animal animal1 = new Cat();
animal1.greeting();
Animal animal2 = new Dog();
animal2.greeting();
Animal animal3 = new BigDog();
animal3.greeting();
Animal animal4 = new Animal();
// Downcast
Dog dog2 = (Dog)animal2;
BigDog bigDog2 = (BigDog)animal3;
Dog dog3 = (Dog)animal3;
Cat cat2 = (Cat)animal2;
dog2.greeting(dog3);
dog3.greeting(dog2);
dog2.greeting(bigDog2);
bigDog2.greeting(dog2);
bigDog2.greeting(bigDog1);
}
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 47
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
MODULE 3 - ARRAY AND ARRAY LIST
Characteristics of Simple Array
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 48
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Do not use Raw Type:
List names = new ArrayList();
// this raw type!
names.add("John");
names.add("Mary");
names.add(Boolean.FALSE);
Run time error due to the raw type
for (Object o : names) {
String name = (String) o;
System.out.println(name);
}
// throws ClassCastException!
//
java.lang.Boolean cannot be cast to
java.lang.String
This is not a compilation error,but a run
time error!
You should have used:
List<String> names = new ArrayList<String>();
From now on, you should compile with -Xlint in order to get all the warnings as well.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 49
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Simple Array syntax
(Need to import java.util.Arrays)
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
// initialize to
double[]
for (int
a[i]
}
random values between 0 and 1
a = new double[n];
i = 0; i < n; i++) {
= Math.random();
// print array values, one per line
System.out.println("a[]");
System.out.println("-------------------");
for (int i = 0; i < n; i++) {
System.out.println(a[i]);
}
System.out.println();
System.out.println("a = " + a);
System.out.println();
// find the maximum
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < n; i++) {
if (a[i] > max) max = a[i];
}
System.out.println("max = " + max);
//average
double sum = 0.0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
System.out.println("average = " + sum / n);
// copy to another
double[] b
for (int i
b[i] =
}
array
= new double[n];
= 0; i < n; i++) {
a[i];
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 50
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
// reverse the order
for (int i = 0; i < n/2; i++) {
double temp = b[i];
b[i] = b[n-i-1];
b[n-i-1] = temp;
}
// print array values, one per line
System.out.println();
System.out.println("b[]");
System.out.println("-------------------");
for (int i = 0; i < n; i++) {
System.out.println(b[i]);
}
// dot product of a[] and b[]
double dotProduct = 0.0;
for (int i = 0; i < n; i++) {
dotProduct += a[i] * b[i];
}
System.out.println("dot product of a[] and b[] = " + dotProduct);
// Traverse 2D array
int [][]table = new int[5][6];
int nRows = table.length;
int nCols = table[0].length;
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
table[i][j] = i * j;
System.out.print( table[i][j] + "
}
System.out.println("...");
}
");
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 51
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
String Array
//1D String Array
String[] data = {"banana", "orange", "grapefruit", "kiwi", "apple"};
Arrays.sort(data);
System.out.println(Arrays.toString(data));
// String Argument from main
public static void main(String[] args)
{
int iVal;
int count = args.length;
if (count > 1)
System.out.println("You only need one argument!");
if (length == 1) {
iVal = 10;
}
else
iVal = Integer.parseInt(args[0]);
// do something…
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 52
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
“How-to” about using ArrayList
First of all, you will need to import the packages:
import java.util.ArrayList;
import java.util.Collections;
1- How to create an ArrayList
Just for simple example, we will use only a generic “Stirng” class in our ArrayList .
ArrayList<String> myStringArrayList = new ArrayList<String>( )
// “List” class is immutable. So, you won’t be able change the list.
List<String> stringList = Arrays.asList("zaaa", "abc", "bcd", "ade", "zaab", "cde");
// if you wish the list remains mutable, do the following instead
ArrayList<String> myStringArrayList = new ArrayList<String>( Arrays.asList("zaaa", "abc"));
myStringArrayList.add("xyz");
2- How to add element to ArrayList
You can add elements to ArrayList by calling add() method. Since we are using “Generics”
and this is an ArrayList of String,
Note that the second line will result in a compilation error because this Java ArrayList will
only allow String elements.
myStringArrayList.add("Item"); //no error because we are storing String
myStringArrayList.add(new Integer(2)); //compilation error
3- How to find size of ArrayList
The size of an ArrayList in Java is a total number of elements currently stored in ArrayList.
You can easily find a number of elements in ArrayList by calling size() method on it.
Remember this could be different with the length of the array as the system does backup
ArrayList. Actually the backup array always has a larger length than the size of ArrayList so
that it can store more elements.
int size = myStringArrayList.size();
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 53
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
4- Checking Index of an Item in Java ArrayList
If ( myStringArrayList.contains( “Joey” )
index = myStringArrayList.indexOf("Joey”);
// location of Item object in List
5- How to retrieve an element from ArrayList in loop
Many times we need to traverse on Java ArrayList and perform some operations on each
retrieved item.
The following shows two ways of doing it using simple iteration methods.
for (int i = 0; i < myStringArrayList.size(); i++)
String item = myStringArrayList.get(i);
System.out.println("Item " + i + " : " + item);
}
OR, you can use “for each” loop as well
int i = 0;
for ( String item : myStringArrayList) {
System.out.println("Item " + (i++) + " : " + item);
}
// for each instanceof String, put it in object “item”.
6- How to search in ArrayList for an element?
There are multiple ways to do the search. Here, we will use :
-
contains() method of Java
Collections.binarySearch()
Reference: http://javarevisited.blogspot.sg/2014/03/binary-search-vs-containsperformance.html
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 54
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
7- How to check if ArrayList is Empty in Java
boolean result = myStringArrayList.isEmpty(); //isEmpty() will return true if List is empty
OR
if(myStringArrayList.size() == 0){
System.out.println("ArrayList is empty");
}
8- How to remove an element from ArrayList
myStringArrayList.remove(0);
// remove 1st occurrence of the specified indexed element.
myStringArrayList.remove(item); // remove 1st occurrence of item.
9- Copying data from one ArrayList to another ArrayList in Java
ArrayList <String> copyOfMyStringArrayList = new ArrayList<String>();
copyOfMyStringArrayList.addAll ( myStringArrayList );
10- How to replace an element at a particular index in ArrayList?
myStringArrayList.set(0,"Item2"); // will replace the first element with “Item2”
11- How to remove all elements from ArrayList?
myStringArrayList.clear( ); // remove all elements. Can reuse Java ArrayList after clearing it.
12- How to converting from ArrayList to Array
String[ ] strArray = myStringArrayList.toArray( new String[ myStringArrayList.size( ) ]);
For (String element : strArray) {
System.out.println(element);
}
The following sample
returns an array containing all of the elements in this list in proper
sequence
String[] strArray = new String[ myStringArrayList.size() ];
String[ ] copyArray = myStringArrayList.toArray( strArray );
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 55
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
13- How to converting from Array back to an ArrayList
Note that this creates a wrapper that makes the array look like a araylist. When you
change an element in the list, the element in the original array is also changed. Note that
the list is fixed size - if you try to add elements to the list, you'll get an exception.
String[ ] sample = { "One", "Two", "Three" };
List<String> newSampleList = Arrays.asList(sample);
OR
ArrayList myStringArrayList = Arrays.asList(new String[ ] {"One", "Two", "Three");
14- How to sort an ArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
public class sortSample {
static void prt(List<String> a, String s)
{
// NOTE: (List a, String s) will compile too, but not as robust
System.out.printf("%-40s ", s);
System.out.println(a);
}
public static void main(String[] args)
{
List<String> unsortedList = Arrays.asList("zaaa", "abc", "bcd", "ade", "zaab", "cde");
prt(unsortedList, "Arraylist not sorted:");
Collections.sort(unsortedList);
prt(unsortedList, "Arraylist in ascending order:");
Collections.sort(unsortedList, Collections.reverseOrder());
prt(unsortedList, "Arraylist in descending order:");
}
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 56
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
15- How to loop over ArrayList with Iterator
Sample Code segment:
Iterator<String> itr = myStringArrayList.iterator();
while ( itr.hasNext() ) {
System.out.printf ( "[%5s]" ,itr.next( ) );
}
System.out.println("=================");
// use iterator for traversing List and Set.
// List is immuutable, so it allows only traversing
ListIterator<String> listItr = myStringArrayList.listIterator();
while ( listItr.hasNext() ) {
System.out.print( "[ " + listItr.next() + " ]" );
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 57
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
16- How to sort ArrayList using Iterator
Sample Code Segment:
List<String> unsortList = new ArrayList<String>();
unsortList.add("CCC");
unsortList.add("BBB");
unsortList.add("AAA");
Iterator<String> itr3 = unsortList.iterator();
while ( itr3.hasNext() ) {
System.out.println( itr3.next() );
}
/* OR
for(String temp: unsortList){
System.out.println(temp);
}
*/
//sort the list
Collections.sort(unsortList);
//after sorted
System.out.println("ArrayList is sorted");
// another way to list out the content
for (int j=0; i< unsortList.size(); j++)
System.out.println( unsortList.get(j));
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 58
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
17- How to sort user-defined Class with ArrayList
Comparable Interface Class - contains only one method called compareTo.
Comparator interface Class - contains two methods, called compare and equals.
Sample to list in ascending order (called natural order in Java)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class SmartPhone implements Comparable <SmartPhone>, Comparator<SmartPhone> {
private String brand;
private String model;
private int price;
public SmartPhone() {
}
public SmartPhone(String brand, String model, int price) {
this.brand = brand; // note : have to use ""this", unless //your formal parameter spells differently
this.model = model;
this.price = price;
}
@Override
public int compareTo(SmartPhone sp) {
// user the default ascending order alphabetical sort
return this.brand.compareTo(sp.brand);
}
@Override
public String toString() {
return brand + "/ " + model + " cost “ + price + "\n";
}
public int compare(SmartPhone sp1, SmartPhone sp2) {
return ( sp1.price < sp2.price ) ? -1 :
(( sp1.price > sp2.price) ? 1 : 0 );
}
};
Sample continue next page…
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 59
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
public class ArrayListSortingExample {
public static void main(String... args) {
//creating objects for arraylist sorting example ------------------------SmartPhone google = new SmartPhone("Google", "Pixel",590);
SmartPhone samsung = new SmartPhone("Samsung", "Galaxy S7",670);
SmartPhone lg = new SmartPhone("LG", "HTC 10",500);
SmartPhone apple = new SmartPhone("Apple", "IPhone7",890);
//creating Arraylist for sorting example -----------------------ArrayList<SmartPhone> phones = new ArrayList<SmartPhone>();
//storing objects into ArrayList for sorting -----------------------phones.add(nokia);
phones.add(samsung);
phones.add(lg);
phones.add(apple);
System.out.println("Unsorted:\n");
System.out.println(phones);
//Sorting Arraylist in Java on natural order of object -----------------------Collections.sort(phones);
System.out.println("Sorted in Java Natural Order:\n");
System.out.println(phones);
//print sorted arraylist on natural order -----------------------// Sorting Arraylist in Java on custom order defined by Comparator
Collections.sort( phones, new SmartPhone() );
System.out.println("Custom sorted order:\n");
System.out.println(phones);
}
}
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 60
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
DAY 4&5 RECURSION AND BASICS IN SEARCH AND SORTING ALGORITHMS
Search & Sort
Sequential Search
Binary Search
Selection Sort
Insertion Sort
Merge Sort
Recursion
Let’s see how to do factorial
int fact(int n)
{
int result;
if(n==1)
return 1;
return ( fact(n-1) * n );
}
By why!? Discuss!
For more exercises – http://learn.stormingrobots.com.
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 61
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Sequential Search
Pre-condition: Given – e.g. int [ ] arr = { 19, 10, 5, 30, 10 }
Post-condition: return the index where the target element is first found. Otherwise, return
-1
Goal is to search the 1st occurrence.
Pseudo code:
For index from 0 to # of elements
If element == target
Return index
None found , return -1
Binary Search
Pre-condition: In order to use binary search, the list must be sorted first.
Post-condition: return the index where the target element is found. Otherwise, return -1
While left <= right
middle = (left + right) / 2
if ( target == element [ middle ] )
return middle
if ( target > element [ middle ] )
left = middle
else
right = middle
none found , return -1
# of iterations = log(N)
e.g. N = 1024 , # of iterations = 10
Big-O complexities
best case = O(1)
worst case = O(N2 )
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 62
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Sorting
Pre-condition: Given – e.g. int [ ] arr = { 19, 10, 5, 30, 10 }
Post-condition: sorted in ascending order
The following includes selection sort, insertion sort, quick sort, and merge sort
Selection Sort
Go thru the list. Swap each found element < target.
Pre-condition: Given – e.g. int [ ] arr = { 19, 10, 5, 30, 10 }
Post-condition: sorted in ascending order
N = # of elements
for index1 from 0 up to N-1
{ // compare element[index1 ] with
//
element[index1+1], [index1+2] …. [index +…] up to # of elements
min = index1;
for index2 from index1 +1 up to N-1
if ( element[index2] < element [ index ] )
min = index2;
// after the inner loop is complete, found the minimum one
swap that with element [ index1 ]
temp = element [index1]
element[index1] = element [ min ]
element[min] = temp
} // go back to get the next element
# of iterations = N * (N-1)
Big-O complexities
best case = O(N2 )
worst case = O(N2 )
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 63
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Insertion Sort
N = # of elem ents
for(index1=1;index1 up to N-1
{ key = a[index1];
i = 0; // go thru all elements before index1 until found a smaller value
while ( i < index1)
{
if element [index1]< element[i]
{
copy all elements from [ i ] to [index1-1] to
element [ i+1 ] to [ index1 ]
element[ i ] = key;
break
out
the
immediate
}
}
}
loop
Also, look at the implementation shown in the 2016 AP CS document. If this link does not work,
you should go to the AP board site to look for the latest syllabus document.
# of iterations <= N2
Big-O complexities
best case = O(N )
worst case = O(N2 )
Quick Sort
<… pseudo code … >
# of iterations <= N2
Big-O complexities
best case = O(n logN )
worst case = O(N2 )
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 64
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Merge Sort
Reference: www.khanacademy.org
# of iterations <= N2
Big-O complexities
best case = O(n logN )
worst case = O(N ) BUT! Memory consumption is high
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 65
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Day 5 –Practice! Practice!
Tasks to do:
1) Work on improving control structure
2) Work on improving understanding in basics of OOPs design pattern
3) Review Key terms
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 66
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
APPENDIX
Advanced Placement Computer Science Syllabus
https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap-computer-science-acourse-description.pdf
Classification Category
% of multiple-choice items
Programming fundamentals
55-75%
Data Structures
20-40%
Logic
5-15%
Algorithms/Problem Solving
25-45%
Object-Oriented Programming
5-15%
Recursion
5-15%
Software Engineering (such as
error checking, robustness,
efficiency.)
2-10%
Section 1 : multiple
Choices
40 Qs
75 minutes
50% of Exam
Score
Sectioin II: Free
Reapons
90 minutes
50% of Exam
2016 AP CS A Syllabus
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 67
Java Programming with Computational
Thinking / AP CS A
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
Engineering and Computational Thinking For Pre-College
908-595-1010
www.stormingrobots.com
P. 68
Java Programming with Computational
Thinking / AP CS A
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
Engineering and Computational Thinking For Pre-College
908-595-1010
www.stormingrobots.com
P. 69
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
Java Quick Reference
Before the exam, you should always get yourself familiar the format of the quick reference.
For further learning, you should always consult Java document such as
https://docs.oracle.com/javase/tutorial/java/index.html
•class java.lang.Object
• boolean equals(Object other)
• String toString()
class java.lang.Integer
• Integer(int value)
• int intValue()
• Integer.MIN_VALUE // minimum value represented by an int or Integer
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 70
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
• Integer.MAX_VALUE // maximum value represented by an int or Integer
class java.lang.Double
• Double(double value)
• double doubleValue()
class java.lang.String
• int length()
• String substring(int from, int to) // returns the substring beginning at from
// and ending at to-1
• String substring(int from) // returns substring(from, length())
• int indexOf(String str) // returns the index of the first occurrence of str;
// returns -1 if not found
• int compareTo(String other) // returns a value < 0 if this is less than other
// returns a value = 0 if this is equal to other
// returns a value > 0 if this is greater than other
class java.lang.Math
• static int abs(int x)
• static double abs(double x)
• static double pow(double base, double exponent)
• static double sqrt(double x)
• static double random() // returns a double in the range [0.0, 1.0)
interface java.util.List<E>
• int size()
• boolean add(E obj) // appends obj to end of list; returns true
• void add(int index, E obj) // inserts obj at position index (0 size) ,
// moving elements at position index and higher
// to the right (adds 1 to their indices) and adjusts size
£ £ index
• E get(int index)
• E set(int index, E obj) // replaces the element at position index with obj
// returns the element formerly at the specified position
• E remove(int index) // removes element from position index, moving elements
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 71
Java Programming with Computational
Thinking / AP CS A
Engineering and Computational Thinking For Pre-College
// at position index + 1 and higher to the left
// (subtracts 1 from their indices) and adjusts size
// returns the element formerly at the specified position
class java.util.ArrayList<E> implements java.util.List<E>
Answers to Questions in Day 2
1.
2.
3.
4.
5.
6.
7.
8.
9.
Real-world objects contain state and behavior.
A software object's state is stored in fields.
A software object's behavior is exposed through methods.
Hiding internal data from the outside world, and accessing it only through publicly exposed
methods is known as data encapsulation.
A blueprint for a software object is called a class.
Common behavior can be defined in a superclass and inherited into a subclass using the
extends keyword.
A collection of methods with no implementation is called an interface.
A namespace that organizes classes and interfaces by functionality is called a package.
The term API stands for Application Programming
Interface.\https://docs.oracle.com/javase/tutorial/java/index.html For further
learning, you should always consult Java document such as
https://docs.oracle.com/javase/tutorial/java/index.html
3322 Rt. 22 West, Suite 1503, Branchburg, NJ 08876
908-595-1010
www.stormingrobots.com
P. 72