Review of CSCI 2911
- Contents
- Introduction to Computers and Java
- Java Fundamentals
- Files
- GUI Applications
- Arrays and the ArrayList Class
Introduction to Computers and Java
Java bytecode is cross-platform, meaning that it can run on various computer operating systems.
Java applications — stand-alone programs;
Java Applets — small applications that require the use of a Java enabled web browser.-
Computer Systems — Hardware:
- the central processing unit (CPU)
- main memory
- secondary storage devices, such as hard drive and CDROM
- input and output devices
-
Computer Systems — Software:
-
Operating Systems
- control system resources
- provide means of interaction with the computer
-
Application Software
- programs that make the computer useful to the users
- for example, word processors and games
-
Computer program is a set of instructions that enable the computer to solve a problem or perform a task. These instructions form an algorithm.
-
Common programming language elements
- Key words
- Operators
- Punctuation
- Programmer-defined identifiers
- Strict syntactic rules
-
Compiling a Java program
javac Program.javaRunning a Java program
java Program -
Software engineering
- Designing
- Writing
- Testing
- Debugging
- Documenting
- Modifying
- Maintaining
Object-Oriented Programming (OOP) is centered on creating objects rather than procedures — encapsulation.
Java Fundamentals
-
Parts of a Java Program
- Comments
- Class Header
- Curly Braces
- The
main
Method - Java Statements
-
Console Output
System.out.println("Hello World");
-
Java escape sequences
New Line \n
Carriage Return \r
Tab \t
Backslash \\
Double Quote \"
Single Quote \'
-
Variables and literals
int c = a + b + 12;
-
The
+
operator can be used for concatenation and addition.String s = "One " + 2 + " Three";
-
There are eight primitive data types
boolean
byte
char
short
int
long
float
double
-
Variable assignment and initialization
int answer = 42;
-
Arithmetic operators
+
-
*
/
%
-
Operator precedence and grouping with parenthesis
float n = (a + a) * (b + b) - c;
-
Combined assignment operators
x += 2; y %= 5;
-
The increment and decrement operators
number + 1 number++ number - 1 number--
-
Differences between prefix and postfix
number++ ++number number-- --number
-
Creating constants for program maintainability.
final int MAX_ALLOWANCE = 10000;
The
String
class from the Java standard library holds a series of characters.Primitive variables contain the value they have been assigned. Objects, however, are not stored in variables but referred by variables.
-
A variable can be assigned to a string literal.
String
objects are the only objects that can be crated in this way.String name = "Jade Cheng";
-
A variable can be created using the
new
keyword.String name = new String("Jade Cheng");
-
The
String
methods:text.charAt(4); text.length(); text.substring(2, 3); text.toLowerCase();
Variable scope refers to the part of a program that has access to this variable’s contents.
-
Commenting code
// a single line comment /* block comments */ /** * JavaDoc comments */
-
The
Scanner
class works withSystem.in
to read input from the keyboard.Scanner scanner = new Scanner(System.in);
-
A dialog box is a small graphical window that displays a message to the user or request input. They can be displayed using the
JOptionPane
class.JOptionPane.showMessageDialog(null, "Hello World"); String name = JOptionPane.showInputDialog("Enter your name.");
-
The
System.exit
method and the exit codeSystem.exit(0); System.exit(1);
-
The parse methods
byte aByte = Byte.parseByte("12"); int anInt = Integer.parseInt("12"); short aShort = Short.parseShort("12"); long aLong = Long.parseLong("12"); float aFloat = Float.parseFloat("12.12"); double aDouble = Double.parseDouble("12.12");
Decision Structures
The
if
statement decides whether or not a section of code executes.-
A boolean expression is any variable or calculation that results in a true or false condition.
if (x > y) ... while (x == y) ... return x != y;
-
Flags are
boolean
variable that monitor some condition in a program.boolean isFinished = false;
-
Characters are stored in memory using Unicode format and they are ordinal.
'a' < 'z' // true
The
if-else
statement adds the ability to conditionally execute code when theif
condition is false.-
Java provides two binary logical operators:
&&
and||
.A B A && B A || B true true true true true false false true false true false true false false false false Java also provides one unary logical operator:
!
.A !A true false false true Order of precedence,
!
has a higher order of precedence than&&
and||
. Relation operators like<
also have higher precedence than&&
and||
. Parenthesis can be used to force the precedence to be changed.-
Comparing
String
objects"apple".compareTo("orange"); // less than 0 "apple".compareToIgnoreCase("Apple"); // 0 "apple".equals("APPLE"); // false "apple".equalsIgnoreCase("APPLE"); // true
-
The conditional operator is a ternary (three operands) operator.
z = x > y ? 10 : 5
-
The
switch
statement allows us to use an ordinal value to determine how a program will branch. Theswitch
statement can evaluate an integer type or a character type.switch (itemId) { case 1: System.out.println("Item #1 is selected."); break; case 2: System.out.println("Item #2 is selected."); break; case 3: System.out.println("Item #3 is selected."); break; default: System.err.println("Invalid item ID."); break; }
-
The decimal format and
printf
methodpublic final class Program { public static void main(final String args[]) { final int dogs = 3; final int cats = 4; final double water = 2.546345; System.out.printf( "We have %d dogs, %d cats, and %.2f gallons of water.\n", dogs, cats, water); } }
Loops
-
Three different looping structures
while (i < 10) { ... } for (int i = 0; i < 10; i++) { ... } do { ... } while (i < 10);
-
Infinite loops
while (true) { ... } for (;;) { ... } do { ... } while (true);
-
Similar to nested
if-else
statements, nested loops are common.public final class Program { public static void main(final String args[]) { for (int i = 0; i < 10; i++) { int j = 0; while (j < 20) { System.out.println("j is: " + j); j += 2; } } } }
The
break
statement can be used to abnormally terminate a loop.The
continue
statement causes the currently executing iteration of a loop to terminate and the next iteration will begin.
Methods
-
Methods are commonly used to break a problem down into small manageable pieces.
- divide and conquer
- code reuse
A
void
method is one that simply perform a task and then terminates.-
A value-returning method not only performs a task, but also sends a value back to the code that called it.
System.out.println("Hello, World!"); int number = Integer.parseInt("23");
-
Method header and method body
public static void main(String[] args) { ... }
-
Method header contains
- method modifiers
- return type
- method name
- parentheses with variable declaration
A method executes when it is called.
The JavaDoc comments for a method begin with
/**
and end with*/
.Values sent into a method are called arguments, which must correspond to the variable declaration in the parentheses of the method declaration.
Arguments are passed by value. If a primitive parameter variable is changed inside a method, it has no affect on the original argument.
A variable holding the memory address of an object is called a reference variable.
-
The
@param
tag in documentation/** * Finds a thing in this instance. * * @param name The name of the thing to find in this instance. */ public void find(String name) { ... }
Local variables declared inside a method are not accessible rom outside of this method.
Defining and calling a value-returning method
-
The
@return
tag in documentation/** * Computes a value based on values of this instance. * * @return The value computed by this instance. */ public int compute() { ... }
Classes
-
Object-oriented programming is centered on creating objects rather than procedures.
- The persistent values of an object are called fields.
- Procedures associated with an object are called methods.
- Object-oriented programming combines data and behavior via encapsulation.
Data hiding protects data from corruption and hides details of how it is maintained.
Reuse of code promotes the development of larger software projects.
A class is a “blueprint” from which objects are created. An object is called an instance of a class.
-
Class objects normally have methods that perform useful operations on their data. Primitive variables can only store data and have no methods.
int len = myString.length();
Each object created is independent from each other.
-
Unified Modeling Language (UML) provides a set of standard diagrams for graphically depicting object-oriented systems.
Accessors: methods that retrieve the data of fields.
Mutators: methods that modify the data of fields.
-
Constructors: methods that are called when an object is created.
- Constructors have the same name as the class.
- Constructors have no return type.
- Constructors are typically public.
Constructor can be overloaded.
A method may have a local variable with the same name as an instance field. This is called shadowing. The local variable will hide the value of the instance field.
Classes in Java API are organized into packages. The
java.lang
package is automatically made available to any Java class.-
Example
class Person { private int height; public Person(final int height) { this.height = height; } public Person(final Person other) { this.height = other.getHeight(); } public int getHeight() { return this.height; } public void setHeight(final int height) { this.height = height; } public String toString() { return "A person with height " + this.height; } }
Files
Files can be opened for input or output.
Files should be closed prior to program termination.
In general, there are two types of files: binary and text.
-
Reading data from a file
FileReader
BufferedReader
Scanner
Example Code
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Program { public static void main(final String[] args) { try { File file = new File("myFile.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) System.out.println(scanner.nextLine()); } catch (FileNotFoundException e) { System.err.println("File not found."); } } }
-
Writing text to a file
PrintWriter
FileWriter
Example Code
import java.io.FileWriter; import java.io.IOException; public class Program { public static void main(final String[] args) { try { final FileWriter writer = new FileWriter("myFile.txt"); writer.write("I'm writing to the file."); writer.close(); System.out.println("Done."); } catch (final IOException e) { System.err.println("IO Exception"); } } }
-
The
Random
classnextDouble()
nextFloat()
nextInt()
nextInt(int n)
GUI Applications
A graphical User Interface (GUI) is a window or windows that provide interaction with the user.
GUIs generally accept input from the keyboard and mouse.
Some common GUI components are: buttons, labels, text fields, check boxes, radio buttons, combo boxes and sliders.
Java is equipped with a set of classes for drawing graphics and creating GUI components. These classes are part of the Abstract Windowing Toolkit (AWT).
Swing
was introduced with the release of Java 2. It is a library of classes that provide an improved alternative for creating GUI applications and applets.GUI environments are event-driven. GUI applications contain event listeners, which are objects that automatically execute one of their methods when specific events occur.
Handling action events can be done in various ways. For example, we can write even listener classes as private inner classes. We can also use anonymous classes.
Event listeners must implement an interface and be connected to a component.
Layout refers to the positioning and sizing of components. A layout manager is an object that controls the positions and sizes of components and makes adjustments when necessary.
-
Example
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.WindowConstants; /** * The class that contains the main entry point of the program. */ public final class Program { /** * The main entry point of the program. * * @param args The command-line arguments (ignored). */ public static void main(final String[] args) { // Create the window, center it on the screen, and display it. final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } /** * A window that displays a text area, a text field, and a button. When the * button is pressed, the contents of the text field are appended to the * contents of the text area and then cleared. */ final class MainWindow extends JFrame { /** A serialization version ID. */ private static final long serialVersionUID = -726678164482368106L; /** * Initializes a new instance of the MainWindow class. */ public MainWindow() { super("Jade's Window"); // Set the size for this window, and use a flow layout manager to // automatically control the bounds of the components; automatically // dispose resources for this instance when it is closed by the user. this.setSize(300, 300); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // Create the components for the window, and add them to this instance. final JTextArea textarea = new JTextArea(""); final JTextField field = new JTextField(20); final JButton button = new JButton("Show"); this.add(button); this.add(field); this.add(textarea); // When the button is pressed, append the text from the text field to // the text of the text area. button.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { textarea.append(field.getText() + "\n"); field.setText(""); } }); } }
Arrays and the ArrayList
Class
-
Arrays allow us to create a collection of like values that are indexed.
int[] ints; int[] ints = { 1, 2, 3, 4, 5, 6 }; int[] ints = new int[6];
-
Arrays can store any type of data but only one type of data at a time.
float[] floats = new float[6]; char[] chars = new char[6]; double[] doubles = new double[6];
-
An array is accessed by the reference name and a subscript that identifies which element in the array to access
numbers[1] = 10; int num = numbers[1];
Array indexes start at zero and continue to array length subtract one.
-
Arrays are not limited to primitive data.
String[] names = { "Bill", "Susan", "Steven", "Jean" };
Examples of sorting and searching algorithms: selection sort and binary search
-
A Java program can receive arguments from the operating system command-line.
public static void main(String[] args) { ... }
-
Similar to an array, an
ArrayList
allows object storage. Unlike an array, anArrayList
automatically expands when a new item is added and shrinks when items are removed.ArrayList<String> names = new ArrayList<String>(); names.add("Jade Cheng"); names.add(0, "Jade Cheng"); String aName = names.get(0); names.remove(0);