Java+Daily+Notes


 * Day 1**

Book comments:
 * The book may seem silly but the authors rely heavily on recent brain research to design the silliness to aid your learning.
 * The end of the chapter exercises, according to the authors, are **mandatory**

Creating a program in Eclipse:
 * 1) File, New, __#|Java__ Project
 * 2) Name the project, click Finish
 * 3) Be sure the Package Explorer __#|window__ is open
 * 4) Expand the project you just created
 * 5) Right click on the src folder for the project
 * 6) Click New, Class
 * 7) Enter a package name to group your project files
 * 8) Name the class
 * 9) Check public static void main(String[] args)
 * 10) Click Finish

Notice that the name of your class file, e.g., test1.java must match the name of the class itself (in the code).

file: HelloWorld.java code format="java" public class HelloWorld {   public static void main(String[] args) {       System.out.println("Hello World");

} } code

The following file demonstrates the challenge of input as well as a simple if statement. Also notice the use of the import operator. When we use this operator we use some of java's built in libraries. The java.io package contains the two input classes we use: BufferedReader and InputStream. The asterisk(java.io.*) tells the compiler to look for these __#|classes in__ this package in general.

file: SimpleInput.java code format="java" import java.io.*;

public class SimpleInput {   public static void main(String[] args) {       int age = 18; // what do you need for adequate testing? 0, 21, < 21, >21

String line = null; int val = 0;

System.out.println("Enter an age to test"); try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); line = is.readLine; val = Integer.parseInt(line); } catch (NumberFormatException ex) { System.err.println("Not a valid number: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); }

System.out.println("I read this number: " + val);

if (val < 21) {           System.out.println("under age"); } else { System.out.println("Legal"); }   } } code


 * Day 2**

A **Class** provides a template to create an **object** or an **instance** of the class.

file: Account.java code format="java" public class class Account{ private double balance; public Account{ //construct a "basic" Account balance = 5; }       public Account(double amount){ //overload constructor balance = amount; }       public double getBalance{ //getter for balance, returns the balance by VALUE return balance; }       public void deposit(double amount){ balance += amount; //same as balance = balance + amount }       public boolean withdraw(double amount){ boolean result = false; if(balance >= amount){ //make sure of no overdraft balance -= amount; result = true; }           return result; //return the result of the transaction }

public static void main(String[] args){ Account   bobsAccount = new Account;        //java type - lower case, classes - upper case System.out.println("Bobs current balance is: " + bobsAccount.getBalance); //append the strings together with '+'

double depositAmount = 100; bobsAccount.deposit(depositAmount);   //pass the VALUE: 100 System.out.println("New balance is "+ bobsAccount.getBalance);

if(bobsAccount.withdraw(100)){ System.out.println("Success"); }else{ System.out.println("Not enough $$$"); }

Account sallysAccount = new Account(500);   //example of overLOADING a method } } code


 * Day 3**

An abstract class cannot be initialized like a normal class, it can only be extended. Once extended all abstract method in the abstract class must be overridden in the child class, unless the child class is also an abstract class. file: AbstractAccount.java code format="java" public abstract class AbstractAccount{ public String name; //needs to be public to inherit public String address; public String socialSecurityNumber; public double balance;

public abstract boolean open(String name, String address, String socialSecurityNumber, double balance); public abstract boolean close(String socialSecurityNumber); } code __#|Now__ that we have an abstract class lets extend it. file: BankAccount.java code format="java" public class BankAccount extends AbstractAccount{ public boolean open(String name, String address, String socialSecurityNumber, double balance){ this.name = name; this.address = address; this.socialSecurityNumber = socialSecurityNumber; this.balance = balance; return true; }   public boolean close(String ssn){ if(ssn.equals(socialSecurityNumber)) return true; else return false; }   public String toString{ //override the built in method return name + " " + address + " " + socialSecurityNumber; } } code Now lets extend the class we just made file: SavingsAccount.java code format="java" public class SavingsAccount extends BankAccount{ public static double minimumBalance = 5; //inferring this number doens't change, make it static public double interestRate = 0;

protected boolean checkBalance(double amount){ if(amount < minimumBalance) return false; else return true; }   public boolean open(String name, String address, String socialSecurityNumber, double balance) { //overriding the open method if(checkBalance(balance)){ return super.open(name, address, socialSecurityNumber, balance); //call the method in the parent class }else{ return false; }   } } code Finally lets test it. file: Main.java code format="java" public class Main{ public static void main(String[] args){ BankAccount bobsAccount = new BankAccount; bobsAccount.open("Bob", "123 Derp str.", "555-55-5555", 100); System.out.println(bobsAccount.toString);

SavingsAccount sallysAccount = new SavingsAccount; if(!sallysAccount.open("Sally", "555 Forest", "444-44-4444", 4)){ System.out.println("Closing account"); sallysAccount.close("444-44-4444"); sallysAccount = null; //dereference the value }else{ System.out.println(sallysAccount.toString); }   } } code


 * Day 4**

To introduce ArrayLists, lets just change the main of yesterdays code slightly. You will also notice in this example that we have assigned a SavingsAccount object to a BankAccount type. This can be done with child classes only. You cannot assign a parent class to a child class value. file: Main.java code format="java" import java.util.ArrayList;

public class Main{ public static void main(String[] args){ ArrayList bank = new ArrayList; //create our arraylist with the generic 'BankAccount'

BankAccount bobsAccount = new BankAccount; bobsAccount.open("Bob", "123 Derp str.", "555-55-5555", 100); bank.add(bobsAccount); //add the account to the bank

SavingsAccount sallysAccount = new SavingsAccount; if(!sallysAccount.open("Sally", "555 Forest", "444-44-4444", 34)){ System.out.println("Closing account"); sallysAccount.close("444-44-4444"); sallysAccount = null; //dereference the value }else{ bank.add(sallysAccount); //since savingsAccount extends BankAccount it can be added to the list }

for(BankAccount b: bank){ //special for loop to loop through the list System.out.println(b.toString); }   } } code

file: DateTest.java code format="java" import java.util.Date;
 * Helpful date code:**

public class DateTest{ public static void main(String[] args){ Date dateCreated = new Date; System.out.println("Date is: " + dateCreated); } } code


 * Day 5**

Installing Window builder:

 * Get your version type. This can be found by:
 * Help -> About Eclipse -> version:
 * Copy the link of your specified version of eclipse:
 * 4.2 Juno: http://download.eclipse.org/windowbuilder/WB/release/R201209281200/4.2/
 * 3.8 Juno:http://download.eclipse.org/windowbuilder/WB/release/R201206261200/3.8/
 * 3.7 Indigo:http://download.eclipse.org/windowbuilder/WB/release/R201206261200/3.7/
 * 3.6 Helios: http://download.eclipse.org/windowbuilder/WB/release/R201206261200/3.6/
 * 3.5 Galileo:http://download.eclipse.org/windowbuilder/WB/release/R201206261200/3.5/
 * In Eclipse go to: Help -> Install New Software...
 * Paste the link into the 'work with' text field.
 * Make sure everything is selected.
 * Next.
 * Accept the license agreement.
 * Finish.
 * Restart Eclipse.
 * Done!

Creating an Applet

 * Create a new Project normally.
 * File -> New -> Java Project -> Name it -> Finish.
 * Now we need to notice a new button Window Builder has added to the tool bar.
 * All the way to the left you will see 'New' then 'create new visual class'.
 * Click 'create new visual class' -> Swing -> JApplet -> Name the class -> Finish.
 * Now notice the new buttons at the bottom of our text editor labeled: 'source' and 'design'
 * Click 'design'
 * You are now in the window builder interface.

Adding a button

 * Have the window builder interface open
 * Select JButton from the component tab of the Palette.
 * Place it on you applet at the desired location. (don't drag it)
 * Play with the other elements.
 * You can change the layout of a container through the properties panel.
 * Play with the properties

Creating an action

 * Select an element with an event, such as a button or slider
 * In the properties panel
 * Next to the word properties is a button called 'show events'
 * This will show all of the possible events your element can have.
 * For the basic event:
 * Action -> performed Action -> double-click
 * This should bring you to your source code where you can set what the action does.


 * Day 6**

DoubleBuffering:
There are a lot of nice examples online that do this but most don't use a canvas, which is fine, it doesn't really matter. A few examples I found: This one uses a listeners to update the screen: [|here.] This one uses a thread like I tried to make Thursday: [|here.] If you want to __#|download__ all of the code necessary to run this applet in Eclipse, you will need the following .java files: SimpleCircle, MovingCircle, and DoubleBufferBounce. All of these files and more can be found at: [|Java Source Files]

I also had a sort of template that I use when I build an applet based game. This one gets the pixel array from a bufferedImage and writes directly to it, allowing quicker fps.


 * Day 7**

Exception Handling is a way to catch input errors or nullPointerExceptions without your program crashing entirely. code Scanner in;

String line; int val = 0; try{ //initialize our try block //this block will contain your code that can possibly throw an exception. in = new Scanner(System.in); //This throws IOException System.out.println("Enter a number greater than 0"); line = in.next; //This also throws IOException

val = Integer.parseInt(line); //this throws the NumberFormatException

if(val <= 0){ throw IllegalArgumentException("Input must be greater than 0"); //throw our own Exception } }catch (NumberFormatException e) { System.err.println("Not a valid number: " + line); }catch (IOException e) { e.printStackTrace; //prints information about the source. }catch (IllegalArgumentException e){ //catches our custom exception System.err.println("Input must be greater than 0"); }finally{ //the finally block always executes, use it as cleanup if(in != null){ System.out.println("Closing input."); input.close; }else{ System.out.println("No input to close."); } } code


 * Day 8**

Threading is a way to accomplish multiple tasks at the same time. code format="java" public class Main implement Runnable{ //implementing the runnable interface making this class threadable public String name; public Main(String name){ this.name = name; }

@Override public run{ //this function from runnable interface try{ for(int x = 0; x<0; x++){ System.out.println(name + ": " + x); Thread.sleep(500); //wait for half a second }       }catch(InterruptedException e){} //the sleep method throws this exception

System.out.println("Finished " + name); }

public static void main(String[] args){ Thread thread0, thread1; thread0 = new Thread(new Main("Tyler")); thread1 = new Thread(new Main("John"));

//start the threads thread0.start; thread1.start; System.out.println("Finished main"); } } code

After you run this you will notice that the two threads output near simultaneously.


 * Day 9**

File IO: Anything involving an external file or directory in java uses the File class.

Output
To write to a file in java you need to use a buffer such as the FileWriter class.

code format="java" import java.io.File; import java.io.BufferedWriter; import java.io.FileWriter;

public class Main{ public static void main(String[] args) throws Exception{ //these classes throw exceptions File myFile = new File("output.txt"); //this will read from the projects root directory BufferedWriter out = new BufferedWriter(new FileWriter(myFile)); out.write("Hello, file output."); out.close; } } code

Input
Just like for console input, this is where Java has options. You can go with streams or buffers, or maybe something I haven't heard of, either way you get the same result. I like to use the Scanner class it gets the job done, but some say its too slow, if this is you then go with a buffer.

code format="java" import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.util.Scanner;

public class Main{ public static void main(String[] args) throws Exception{ //don't forget these classes throw exceptions File myFile = new File("input.txt"); //scanner input Scanner in = new Scanner(myFile); int x = in.nextInt; in.close;

//buffered input BufferedReader bfIn = new BufferedReader(new FileReader(myFile)); String line = bfIn.readLine; bfIn.close; } } code

Object File IO: You can also output entire object from java using the Serializable interface. [|Buffered Reader code examples]

code format="java" import java.io.*;

public class Main{ //the student class is static because it is referenced in main(a static method) static class Student implements Serializable{ //implements serializable String name; float gpa; String id; public Student(String name, String id, float gpa){ this.name = name; this.id = id; this.gpa = gpa; }       @Override public String toString{ //override the toString method StringBuffer sb = new StringBuffer(""); sb.append(" Name: "); sb.append(name); sb.append(" id: "); sb.append(id); sb.append(" gpa "); sb.append(gpa); return sb.toString; }   }

public static void main(String[] args){ Student myStudent = new Student("Tyler", "55555", 4.0f);

try{ File myFile = new File("output.txt"); myFile.createNewFile;

//writing ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(myFile)); oos.writeObject(myStudent); //write our object oos.close;

//reading ObjectInputStream ois = new ObjectInputStream(new FileInputStream(myFile)); Student read = (Student)ois.readObject; ois.close;

//output results to console System.out.println(ois.toString); }catch(Exception e){ e.printStackTrace; }   } }

code


 * Day 10**

The Eclipse Debugger is extremely useful. Setting break points: Opening the Perspective: To run the debugger simply press the debug button next to the run button to run your program in debug mode. From the debug perspective you can see various threads running, variable values, change the value of almost every variable, call functions on command, and hotswap code while your application is running.
 * Breakpoints can be set by selecting a line in the editor and right clicking the left side of the editor
 * OR by selecting a line and holding down the breakpoint shortcut key: Ctrl + Shift + B
 * Note that breakpoints can only be set on lines with code in it.
 * The perspective often opens when you run your program in debug mode.
 * It can also be opened by:
 * From the toolbar -> Window -> Open Perspective -> Debug
 * There is also a button on the toolbar to the far right that opens the debug perspective
 * The perspective contains the following windows normally
 * Debug
 * Breakpoints
 * Watch Values(x= Variables)
 * Outline
 * Any missing windows can be opened from the toolbar -> Window -> Show View -> your window

Changing the value of a variable: HotSwap: Executing methods and code: More on the debugger [|here.]
 * Set a break point someplace in your program
 * Start your app in debug mode
 * Go into the Variables window
 * Any value that is currently in scope should be visible and changed to your liking.
 * Run your application in debug mode
 * Make sure the area you're editing is outside of where your breakpoint is
 * The code you change should not be in main
 * To be able to see your changes, make your app call the method repeatedly
 * Note: you don't need a breakpoint to hotswap code
 * You can force any code to execute while your code is running or suspended from a breakpoints by highlighting the code -> right click -> execute
 * OR highlight -> Ctrl -> U
 * options:
 * The code must be complete, full brackets, no missing variables, the editor will let you know
 * You can even type code into your application, highlight it and then execute it