- Students: Major, # of credit hours, GPA
- Car: Model, Liscense plate.
- Example: your car, you as a student.
- Methods are actions.
- Strings use double quotes, chars use single quotes Ex: ‘a’
- Keyword this, used to refer to specific instance of a class.
- Opening and closing ‘{” is refered to as a statement block
- Block comment * .... * and line comment //
- A constructor sets up an object for usage.
- Default constructer
- Initialization constructer
- get/set or acessor methods for every private property
- two string method
- print info method
- Default constructor initialized an instances properties to default values.
- Constructor must be named the same as the class
- Intitialization constructor gives user defined parameters to initialize an instance with properties with those inputed values.
- boolean - true or false
- char - single character
- double - allows you to store a decimal
- String - allows you to store a literal string
- Using the keyword this refers to the classes properties
- Get and set methods let you modify the properties of an instance of an object.
- In set methods you should use the type void in the signature of the method because you do not wish to return anything.
- System.out.println(); - prints the contained data and adds a newline at the end.
- System.out.print(); - Does the same as above but without a newline.
Syntax and Logical (or semantic)
- compiler helps solve syntax errors.
- Debugger helps with logical errors.
- Analysing the problem and designing a solution.
- Backslash (escape char sequence: ‘/’) says take whatever is next and treat it in a special fashion.
- \n = newline
- \ = backslash
- " = double quote
- =, +, -, *, /, %
- += is a = a + b
- -= is a = a - b
- *= is a = a * b
- /= is a = a / b
- %= is a = a % b
- we use the + for both int/double addition and appending Strings.
- Parentheses allow us to set precedence.
- System.out.println(“number + value = ” + (3 + 5)); => number + value = 8
- Higher order operators take precedence.
- System.out.println(“number * value = ” + 3 * 5); => number * value = 15
- Integer division produces truncated values NOT ROUNDED
- int/int = int
- double/double = double
- double/int = double
- int/double = double
- 3542 % 17 = 6
- x % 17 - max returned it 16, min is 0
- 0 % 5 = 0
- 1 % 5 = 1
- 2 % 5 = 2
- 3 % 5 = 3
- 4 % 5 = 4
- 5 % 5 = 0
- 6 % 5 = 1
- cyclic
+4 = positive 4 -4 = negative 4
- a = 1
- a++ => 2 => a = a + 1
- a– => 0 => a = a - 1
- ++ is the only time you modify the value of a variable without an equal sign.
a = 2; a++; // a = 3 ++a; // a = 4 a = a + 1 // a = 5 a + % // a = 10
a = 2; b = a++ * 2 // b = 2 * 2 => 4; a = 3; a = 2; b = ++a * 2 // a = 3; b = 3 * 2 => 6;
Precedence: *, /, % +, - +=, -=, etc. // shortcut ops
b = a - 3 * 4 % 2; // Precedence is b = (a - ((3*4) % 2));
int a = 2; int b = 4; int c = 5; int d = 7; System.out.println(“result? ” + (a * b % c / d)); => result? 0
d = a++ + c * –b - 3 // ++ and – will match first d = (a++) + c * (–b) - 3 //use ‘a’ first then increment it. Increment b first then use it. d = (((a++) + (c * (–b))) - 3); => d = 14, a = 3, b = 3, c = 5
a += b => a = 5 // Everything to the right of the equal sign is evaluated first. a *= d - c => 45
// Perform assignment a = 405 b = 5
// is a equal to 405? a == 405 => true
// is a not equal to 405 a != 405 => false
<, >, <=, >=
YOU CANNOT COMPARE STRINGS IN THIS FASHION.
boolean b1 = true;
boolean b2 = false;
b1 == b2 > false
b1 =
true => true // Uneccesarry step
b1 = !b2 => b1 = true
!b2 => true
b2 => false
boolean b1 = true; boolean b2 = false; // ‘&&’ = logical and // ‘||’ = logical or
// Both must be true to return truex b2 && b1 => false !b2 && b1 => true
// Either can be true to return true b2 || b1 => true
b1 && b2 || true => true b1 && (b2 || true) => true b2 && (b1 || true) => false
A | B | A&&B |
---|---|---|
T | T | T |
T | F | F |
F | T | F |
F | F | F |
System.out.println("a\tb\ta&&b\nT\tT\tT\nT\tF\tF\nF\tT\tF\nF\tF\tF\n");
#+s
A | B | C | (A && B) | !(B or C) | A && !(B or C) |
---|---|---|---|---|---|
T | T | T | T | F | F |
T | T | F | T | F | F |
T | F | T | F | F | F |
T | F | F | F | T | T |
F | T | T | F | F | F |
F | T | F | F | F | F |
F | F | T | F | F | F |
F | F | F | F | T | F |
Two variable = 2^2 combinations or 4 Three variable = 2^3 combinations or 8 Four variables = 2^4 combinations or 16
- signature (public void method1() or public class School(int students))
- local variable = a variable local to a method.
- The scoper of the variables declared in a methods signature are only for that method.
- Leave off public
- Name the classes a different name to avoid conflict
- You can name the file whatever you would like
- Give comments about the logic behind what the code does not what it does.
- char, boolean, and int are primative types and have default values in
Java.
- Be explicit and init variables with a value. Don’t rely on default assignment.
Logical Data Type
Type | Range | Size | Variable | Declaration |
---|---|---|---|---|
boolean | true, false | N/A | loop | boolean loop; |
Numerical Data Type
Type | Range | Size | Variable | Declaration |
---|---|---|---|---|
byte | -128 to 127 | 8 bits | bits_8 | byte bits_8; |
short | -32,768 to 32,767 | 16 bits | TALL | short TALL; |
int | -2 billion to 2 billion | 32 bits | sum | int sum; |
long | -9 quintillion to 9 quintillion (huge) | 64 bits | mile | long mile; |
float | -3.4 e^+/-38 to 3.4 e^+/-38 | 32 bits | pi | float pi; |
double | -1.7 e^+/-308 to 1.7^+/-308 | 64 bits | stuff | double Stuff; |
Char Data Type
Type | Range | Size | Variable | Declaration |
---|---|---|---|---|
char | Single (Unicode) Characters | 16 bits | letter | char letter; |
- casting temporarily makes a variable look like something different.
return (double) (points/maxPoints) * 100;
char a = 'a';
a // => 'a' (char)
char B = 'b';
b // => Error: cannot find symbol- variable b
B // 'B' char
(int) a // => 97 (int)
(int) b // => 66 (int)
a - B // => 31 (int)
'a' - 'A' // 32 (int)
'a' - 32
(char) a - 32 // 65 (int)
(char) (a - 32) // 'A' (char)
// Ranges
boolean b = true;
b = a >= 65 && a <=90 // => false
b = a >= 'A' && a <='Z' // => false
- Truncate means don’t round.
- Widening is when we assign a smaller bit size value to a larger bit size variable byte 11100100 -> int 00000000 00000000 00000000 11100100
- All if statements are disconnected.
- else if ties statements to a single if and must have a logical flow.
- ctrl + arrow left right skips between tokens.
- You can nest if statements within eachoter.
class User {
public UserOperations userOperations;
public User() {
userOperations = new UserOperations();
}
public void menu() {
System.out.println("1. Integer Calculation?");
System.out.println("2. Print Info");
System.out.println("3. Perform Calcuation");
// ...
System.out.print("Enter a number: ");
// if the method readInt existed
int number = readInt();
if (number == 1) {
userOperations.printDescription();
// if the method readBoolean existed
boolean integerCalculation = readBoolean();
userOperations.setIntegerCalculation(integerCalculation);
}
else if (number == 2) {
userOperations.printInfo();
}
else if (number == 3) {
if (userOperations.getIntegerCalculation()) {
int leftOperand = 0, rightOperand = 0, result = 0;
// if the method readInteger existed
leftOperand = readInteger();
rightOperand = readInteger();
result = userOperations.divide(leftOperand, rightOperand);
}
else {
double leftOperand = 0, rightOperand = 0, result = 0;
// if the method readInteger existed
leftOperand = readDouble();
rightOperand = readDouble();
result = userOperations.divide(leftOperand, rightOperand);
}
}
}
}
- Use the new keyword
- Encapsulating
- We are encapsulating
class Mortgage {
private int amount;
private double interestRate;
private int numberOfYears;
// methods can be found in Mortage.java
}
class Address {
private String street;
private int zipCode;
//...
}
class Name {
private String firstName;
private String middleName;
//...
}
class Borrower {
private Address address;
private Mortage mortgage;
private Name name;
public Borrower() {
address = new Address();
mortage = new Mortgage();
name = new Name();
}
public Borrower(Address address, Mortage mortage, Name name) {
this.address = address;
this.mortage = mortage;
this.name = name;
}
public Address getAddress() {
return address;
}
//get/set methods here
public String toString() {
String data = address.toString() +
mortage.toString() +
name.toString();
return data;
}
}
public boolean testToSeeIfMortagesAreEqual (Mortage m1, Mortage m2) {
if ( m1.getAmount() == m2.getAmount() &&
m1.getInterestRate() == m2.getInterestRate() &&
m1.getNumberOfYears() == m2.getNumberOfYears() ) {
return true;
}
else {
return false;
}
}
Some Psuedocode
class ThreeDRectangle {
int length, width, height;
// ...
public int volume() {
return length * width * height;
}
}
public boolean isCube(ThreeDRectangle rectangle) {
if ( rectangle.getLength() == rectangle.getWidth() &&
rectangle.getLength() == rectangle.getHeight() ) {
return true;
}
else {
return false;
}
}
boolean b isCube(new ThreeDRectangle());
// or
ThreeDRectangle r1 = new ThreeDRectangle();
b = isCube(r1);
public int compare rectangleVolume(ThreeDRectangle r2, ThreeDRectangle r3) {
return r2.volume() - r3.volume();
}
switch (int) {
case value1: // the statements to execute if literal
// value1 is equivalent
// optionally a break can be listed
case value2: // the statements to execute if literal
// value2 is equivalent
// optionally a break can be listed
// ...
case valueN: // the statements to execute if literal
// valueN is equivalent
// optionally a break can be listed
default: // the default statements to execute if
// none of the literal values matched
}
switch (number) {
case 0: System.out.println("zero");
break;
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;
case 3: System.out.println("three");
break;
case 4: System.out.println("four");
break;
case 5: System.out.println("five");
break;
case 6: System.out.println("six");
break;
case 7: System.out.println("seven");
break;
case 8: System.out.println("eight");
break;
case 9: System.out.println("nine");
break;
default: System.out.println("Not 0 through 9");
}
- Goes through cases procedurally. Then uses break to get out of the switch statement.
switch(grade) {
case 'A': System.out.println("Exellent");
break;
case 'B': System.out.println("Good");
break;
case 'C': System.out.println("Average");
break;
case 'D': System.out.println("Below Average");
break;
case 'E': System.out.println("Failed");
break;
default: System.out.println("Invalid");
}
- Switch statements are only used for single values rather than a range of values like an if statement.
switch(grade) {
case 'A': // Falls to next line
case 'B': // Falls to next line
case 'C': System.out.println("PASS");
break;
case 'D': // Falls to next line
case 'F': System.out.println("FAIL");
break;
default: System.out.println("Invalid");
}
// Menus are great for switch statements
char letter = 'y';
switch (letter) {
case 'y':
System.out.println("Yes");
break;
case 'y':
System.out.println("Yes");
break;
case 'N':
case 'n':
System.out.println("No");
break;
default:
System.out.println("Enter y or n");
}
// Let's try it with grades
int score = 85;
switch(score) {
case 100:
case 99:
//...
case 90:
System.out.println("A");
case 80:
//...
}
Grades don’t work so well, unless we do something clever. We need to isolate the tens position
int score = 85;
switch (score / 10) {
case 10:
case 9:
System.out.println("A");
break;
case 8:
System.out.println("B");
break;
case 7:
System.out.println("C");
break;
case 6:
System.out.println("D");
break;
default: System.out.println("F");
}
- The shitty precursor to the superior for loop.
- Structure of a while loop:
while (expression) {
// the statement to execute each time the loop iterates included
// is a specific statement which increments the loop variable
}
- While sequence
- Be dilligent about how many times a loop executes
int i = 0;
while (i < stop) {
System.out.println("i = " + i);
i++;
}
int i = 345
while (i > 0) {
System.out.println(i % 10);
int temp;
temp = temp + (i % 10);
i = i / 10;
}
import java.util.ArrayList;
import java.util.Scanner;
public class Paragraph {
private ArrayList<String> sentences;
public Paragraph() {
sentences = new ArrayList<String>();
}
public void addSentence(String sentence) {
sentences.add(sentence);
}
public void addTerminalInputSentence() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = scanner.nextLine();
addSentence(data);
}
public String toString() {
String data = "";
// get each sentance and add them to sentance one at a time.
for (String sentence : sentences) {
data = data + sentence + "\n";
}
return data;
}
public int numberOfSentences() {
return sentences.size();
}
}
// Exercise: Create any of the standard list of methods
// not included within the solution to Paragraph
// Exercise: examine the class Scanner and practice using
// it's different methods
// Exercise: create the insert process, to insert into the
// middle of the list create the update/replace
// process
- classes such as Integer and Character that allow us to use methods on variables of type int and char as if they were Objects.
// Example for BlueJ's codepad, not a compilable class
import java.util.ArrayList;
ArrayList<Integer> list;
list // <object reference> (ArrayList<Integer>)
list.size() // 0 (int)
list.add(new Integer(10)) // true (boolean)
Integer num;
num // null
num = list.get(0); // <object reference> (Integer)
list.size() // 1 (int)
list.clear();
list.size() // 0 (int)
int i = 1234;
while (i > 0) {num = new Integer(i % 10); list.add(num); i = i / 10 }
list.size() // 4 (int)
num = list.get(0) // <object reference> (Integer)
num.toString() // "4" (String)
int j = 0;
while (j < list.size()) {num = list.get(j); System.out.println(j + " : " + num.toString()); j++;
Last while prints: 0 : 4 1 : 3 2 : 2 3 : 1
lets continue…
while (j > 0) {num =list.get(j - 1); System.out.println(j + " : " + num.toString()); j--;}
Note that you can’t just scan in a char so this example is shit.
import java.util.Scanner
public class Menu {
private int x;
public Menu() {
x = 0;
}
public void method (int a) {
System.out.println("method: " + a);
}
public void method(char a) {
System.out.println("method: " + a);
}
public void method(double a) {
System.out.println("method: " + a);
}
public void menu() {
Scanner scanner = new Scanner(System.in);
System.out.println("1. Method(int)");
System.out.println("2. Method(char)");
System.out.println("3. Method(double)");
System.out.println("2. Quit");
System.out.print("Enter a selection: ");
int selection = scanner.nextInt();
switch(selection) {
case 1: int value1;
System.out.println("Enter the int: ");
value1 = scanner.nextInt();
method(value1);
break;
case 2: char value2;
}
}
Circle |
---|
radius |
methods |
Circle c1 = new Circle(3.0);
Circle c2 = new Circle(4,0);
- & is used for location in memory
C1
Circle |
---|
Radius = 3.0 |
IN MEMORY &348
C2
Circle |
---|
Radius = 4.0 |
IN MEMORY &459
c1 = c2;
ArrayList<Circle> circles = new ArrayList<Circle>();
circles.add(c1);
circles.add(new Circle(50));
Circle |
---|
Radius = 50 |
IN MEMORY &622
ArrayList<Circle>
0 | &459 |
1 | &622 |
ArrayList in Memory &655
import java.util.Scanner;
public class Example
{
public Example() {}
public int method() {
int number = 0;
int sum = 0;
Scanner sc = new Scanner(System.in);
while (number <= 0) {
System.out.print("Enter an int: ");
number = sc.nextInt();
sum = sum + number;
}
return sum;
}
}
In the example above negative number would still be added.
import java.util.Scanner;
public class Example
{
public Example() {}
public int method() {
int number = 0;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter an int: ");
number = sc.nextInt();
while (number <= 0) {
sum = sum + number;
System.out.print("Enter an int: ");
number = sc.nextInt();
}
return sum;
}
}
This one above would not add the negative number
import java.util.Scanner;
public class Example
{
public Example() {}
public int method() {
int number = 0;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter an int: ");
number = sc.nextInt();
while (number <= 0) {
sum = sum + number;
System.out.print("Enter an int: ");
number = sc.nextInt();
}
return sum;
}
public String method(String str) {
String data = new String();
System.out.println(data.compareTo());
// String data = new String("");
// System.out.println(data.compareTo("test"));
//
// will print 4 because it contains 4 more characters than
// the empty data string.
int i = 0;
while (i < str.length) {
System.out.println(str.charAt(i++));
}
// Reverses characters
for(i = str.length() - 1; i >= 0; i--) {
data = data + str.charAt(i);
}
return data;
}
}
- A String is just a sequence of characters.
- ArrayLists are defined by size.
- Strings are defined by length.
- Everything in Java is an object.
- I feel like I’m using Ruby’s ugly ass older brother.
public static void main(String[] args) {
}
class Example {
public static void main (String[] args) {
int i = 0;
for(; i < 25; i++) {
if (i % 5 == 0) {
System.out.println();
}
else {
System.out.print("*");
}
}
}
}
class Example2 {
}
class Example3 {
}
String s1 = new String("test");
String s2 = new String("abc");
// checks if two strings refer to the same place in memory
s1 == s2;
// checks if the values of two strings are equal
s1.equals(s2);
As we have created Java solutions this semester, we have examined how to go about identifying the elements contained (methods and properties) within each class. In order for our decisions to be accurate, we first must have understood the classes being created. An example is the class Circle. In order to create an accurate class representation, we first must understand the problem. Consider how our understanding of the following items assists in constructing the class:
- A circle has a radius
- The radius is half the size of the diameter
- The area of a circle is pi * radius squared.
- Consider how you would add identification of the circle’s circumference and what information would be needed to assist you in determining additions to the class circle.
As we create this analysis, appropriate identifications to make are:
- What are the inputs we need?
- What are the outputs we need to create?
- What are the constraints we will work with?
- What are the relationships our solution (or class) have with other solutions (or classes)?
- Have we made any assumptions?
Once we have analyzed the problem, we begin to framework the problem into a Java solution. Doing so requires the analysis, otherwise we will create a solution without any planning. This leads to a poorly designed solution. Our design will identify things such as:
- The types of all variables
- The names of classes, properties, and methods
- Which classes contain which properties and methods
- What methods will return
- What methods will receive
- How many times a loop will iterate
public Example {
public static void main(String[] args) {
int row, col;
for (row = 0; row < 5; row++) {
for (col = 0, col < 5, col++) {
System.out.println("* ");
}
System.out.println();
}
// Multiplication Table
for (row = 0; row < 5; row++) {
for (col = 0; col < 5; col++) {
System.out.print( (row * col) + " ");
}
System.out.println();
}
}
}