Setup Guacamole Remote Desktop Gateway on Ubuntu with one script

How to replace RDP, SSH and TeamViewer with free open source web-based client-less remote desktop gateway.

 

I recently learned about Guacamole and found that the setup is quite easy. I had been looking for a way to access all of my virtual and physical machine desktops remotely but didn’t want to rely upon, or trust TeamViewer eternally. Guacamole is open source software that provides you a way to run a tomcat/apache/mysql server suite that sets up and connects remote desktop connections via a web browser very similar to Teamviewer. It allows you to connect to any number of different desktops from anywhere with just an html5 web browser, and a single open port on your firewall that logs you into a console that has access to all your desktops, without having to install or configure remote clients such as putty, RDP and VPN.

The installation documentation on the official site is comprehensive but I was able to set up the system fast thanks to Chase Wright’s post here.

First, you’ll want a standard Ubuntu server or virtual machine installed and running. I installed guacamole on Ubuntu Server 16.10 LTS.

Second, open an ssh connection to your server and run the following commands:

sudo su -
wget https://raw.githubusercontent.com/MysticRyuujin/guac-install/master/guac-install.sh
chmod +x guac-install.sh
./guac-install.sh

The installation will take a little while to download and install, and should only prompt you to provide a mysql database password.

For me, that was pretty much it for the initial setup. Next, I went to a different computer and connected to the guacamole gateway at the following default website:

http://serverIPaddress:8080/guacamole (replace serverIPaddress with your ubuntu server’s IP)

Login with the default guacamole username/password: guacadmin/guacadmin

The initial interface is a little sparse, but to create an RDP connection do the following:

  1. Create a new user first before you create a connection because, by default, it will launch a desktop session the next time you log in. If there’s a problem with the connection you may get stuck. This happened to me and I was stuck on the error:
    “Connection Error: An internal error with Guacamole server, and the connection has been terminated”

    It took a little digging but essentially the server console is up and running, but it is hidden by the black screen/pop-up and you can get back into the settings by going to the url: http://serverIPaddress:8080/guacamole/#/settings/sessions

  2. Create the user first by going to the menu in the upper right-hand corner and choose Settings:
  3.  
  4. Next, click the Users tab and then New User:
  5. Next, provide a username, password (x2), and give this new user all permissions and hit save at the bottom:
  6. With this new user created, you will now want to log in as this new user and change the guacadmin account password.
  7. Now we can create our first connection. Before you create your first RDP connection, be sure to test RDP account credentials from a different computer to ensure you can connect successfully.
  8. Click on the Connections tab and then New Connection. The only things I had to set up to get to my workstation RDP connection working were the following:
  9.  
  10. Hit Save at the bottom. There are many additional settings available but this should get you up and connected.
  11. Now we want to assign this connection to a user. Do that by going into the Users tab again, find the user you want to assign and the connection:
  12. Now go to a different computer from the one you want to connect to, go to http://serverIPaddress:8080/guacamole site, login as the user with the connection assigned to it and you should be greeted with the RDP console of the remote computer.
  13. To setup an ssh connection it’s even easier. Again, first create a new user with the same name as the ssh server you want to connect into (I named my user HN-DHCP01). Then create a new connection and name it the same as your server. Below are the guacamole ssh connection settings I used to connect to my DHCP01 server:
  14. Under the Authentication setting, provide a valid ssh user’s credentials on the server you’ll be connecting into.
  15. Hit save at the bottom. Go back into the User tab, then select the new user (HN-DHCP01 user) and assign the connection to the user at the bottom and hit save.
  16. Log out of guacamole, then log in as the new user (HN-DHCP01) this will instantly log you into an ssh session that you can see in the screenshot below runs right in the browser!
  17. Guacamole also supports Two-Factor Authentication as well as a multitude of additional setups and configurations. It’s wise to setup 2FA prior to opening any firewall ports into your local network from the internet, as well as make sure that you follow all security precautions and test everything thoroughly.  Enjoy your guacamole and let me know in the comments if I’ve missed anything.

 

Stanford CS106a Assignment 2, Problem 4 – Target – Part 1

The problem is as follows:
Create a figure that is simply three GOval objects, two red and one white, drawn in the correct
order. The outer circle should have a radius of one inch (72 pixels), the white circle
has a radius of 0.65 inches, and the inner red circle has a radius of 0.3 inches. The
figure should be centered in the window of a GraphicsProgram subclass.

Here is my first part of the solution to the problem. The output is correct, however, the guide states I should use constants. I will re-write the program later in Part 2 once I have learned how to use constants. But for now here is the solution to the problem and the output below.


/*
* File: Target.java
* Name: Jason Coltrin
* Section Leader: n/a
* -----------------
* This file is the starter file for the Target problem.
* This figure is simply three GOval objects, two red and one white, drawn in the correct
* order. The outer circle should have a radius of one inch (72 pixels), the white circle
* has a radius of 0.65 inches, and the inner red circle has a radius of 0.3 inches. The
* figure should be centered in the window of a GraphicsProgram subclass.
*/

import acm.graphics.*;
import acm.program.*;

import java.awt.*;

public class Target extends GraphicsProgram {
public void run() {
drawLargeRedOval();
drawWhiteOval();
drawSmallRedOval();
}

// precondition: a canvas of 200pixels across and 200pixels top to bottom,
// the center is 100x100 pixels.
// postcondition is a red filled circle with 1 inch radius with 72pixels has
// a center of 36
// 100 - 36 = 64,64 is where the left and bottom of the rectangle in which
// the oval is located should be placed

public void drawLargeRedOval() {
GOval myOval = new GOval(64, 64, 72, 72);
myOval.setFilled(true);
myOval.setColor(Color.RED);
myOval.setFillColor(Color.RED);
add(myOval);

}

// precondition: a 200x200pxl canvas with a 72pxl red circle centered at
// 100x100
// postcondition: another white circle added on top of the red circle. .65
// of 72 = 46.8 - half of 46.8 = 23.4
// 100 - 23.4 = 76.6, is where the left and bottom of the GOval rectangle is
// set.
public void drawWhiteOval() {
GOval myOval = new GOval(76.6, 76.6, 46.8, 46.8);
myOval.setFilled(true);
myOval.setColor(Color.WHITE);
myOval.setFillColor(Color.WHITE);
add(myOval);
}

// precondition: a 200x200pxl canvas with a 46.8 white circle on top of a
// red 72pxl circle with a center of 100x100
// post condition: another red circle added on top of the white circle. .3
// of 72 = 21.6 - half of 21.6 = 10.8
// 100 - 10.8 = 89.2, is where the left and bottom of the small re oval is
// set.
public void drawSmallRedOval() {
GOval myOval = new GOval(89.2, 89.2, 21.6, 21.6);
myOval.setFilled(true);
myOval.setColor(Color.RED);
myOval.setFillColor(Color.RED);
add(myOval);
}
}

Target

Condition that I will work on in part 2:
Do you make appropriate use of constants? Several of the programs you’ll write – especially
the graphics programs – will require values that will not be immediately evident from context.
When appropriate, introduce constants into your program to make the program more
customizable and easier to read.

Here is the code that contains the constants. So for example, the boss wants to make the logo bigger, replacing the value of the constants is easier:


import acm.graphics.*;
import acm.program.*;

import java.awt.*;

public class Target extends GraphicsProgram {

final static double firstOvalxUpLeft = 64;
final static double firstOvalyUpLeft = 64;

final static double firstOvalHeight = 72;
final static double firstOvalWidth = 72;

final static double secondOvalxUpLeft = 76.6;
final static double secondOvalyUpLeft = 76.6;

final static double secondOvalHeight = 46.8;
final static double secondOvalWidth = 46.8;

final static double thirdOvalxUpLeft = 89.2;
final static double thirdOvalyUpLeft = 89.2;

final static double thirdOvalHeight = 21.6;
final static double thirdOvalWidth = 21.6;

public void run() {
drawLargeRedOval();
drawWhiteOval();
drawSmallRedOval();
}

// precondition: a canvas of 200pixels across and 200pixels top to bottom,
// the center is 100x100 pixels.
// postcondition is a red filled circle with 1 inch radius with 72pixels has
// a center of 36
// 100 - 36 = 64,64 is where the left and bottom of the rectangle in which
// the oval is located should be placed

public void drawLargeRedOval() {
GOval myOval = new GOval(firstOvalxUpLeft, firstOvalyUpLeft,
firstOvalHeight, firstOvalWidth);
myOval.setFilled(true);
myOval.setColor(Color.RED);
myOval.setFillColor(Color.RED);
add(myOval);

}

// precondition: a 200x200pxl canvas with a 72pxl red circle centered at
// 100x100
// postcondition: another white circle added on top of the red circle. .65
// of 72 = 46.8 - half of 46.8 = 23.4
// 100 - 23.4 = 76.6, is where the left and bottom of the GOval rectangle is
// set.
public void drawWhiteOval() {
GOval myOval = new GOval(secondOvalxUpLeft, secondOvalyUpLeft,
secondOvalHeight, secondOvalWidth);
myOval.setFilled(true);
myOval.setColor(Color.WHITE);
myOval.setFillColor(Color.WHITE);
add(myOval);
}

// precondition: a 200x200pxl canvas with a 46.8 white circle on top of a
// red 72pxl circle with a center of 100x100
// post condition: another red circle added on top of the white circle. .3
// of 72 = 21.6 - half of 21.6 = 10.8
// 100 - 10.8 = 89.2, is where the left and bottom of the small re oval is
// set.
public void drawSmallRedOval() {
GOval myOval = new GOval(thirdOvalxUpLeft, thirdOvalyUpLeft,
thirdOvalHeight, thirdOvalWidth);
myOval.setFilled(true);
myOval.setColor(Color.RED);
myOval.setFillColor(Color.RED);
add(myOval);
}
}

Stanford cs106a, Assignment 2; Problem 3. – FindRange – Part 2

After re-reading the instructions for these sets of problems, I found that I should replace multiple statements of code used for one action with a method().
Additionally, the best practice is comment your preconditions and post conditions before every method in your program.
This practice helps in writing the code without getting off track.
It took a little while to learn that if I initialize an “Int” variable in the class before my methods, and if I use “Int” with the same variable again inside the method, then I am re-declaring the variable as a local variable, and the class variable will not retain it’s values throughout the different methods. If you want a variable’s values to be available to that variable throughout your methods, only declare the type one time in the class.

A few “firsts” for me in this app was 1. The use of the break; command to exit a loop. and 2. The use of if(){} else {if{}} and 3. Methods() to replace multiple statements.

So here is the much-cleaned up and easier to read/use (and working) solution to Problem 3:


/*
* File: FindRange.java
* Name: Jason Coltrin
* Section Leader: n/a
* --------------------
* This file is the starter file for the FindRange problem.
* write a ConsoleProgram that reads in a list of integers, one per line, until a sentinel value of 0
* is entered. When the sentinel is read, your program should display the smallest and largest values
* in the list.
* The program should handle the following special cases:
* • If the user enters only one value before the sentinel, the program should report
* that value as both the largest and smallest.
* • If the user enters the sentinel on the very first input line, then no values have been
* entered, and your program should display a message to that effect.
*/

import acm.program.*;

public class FindRange extends ConsoleProgram {

int num1; // declare num1 as int
int num2; // declare num2 as int
int getNum = 1; // declare getNum as int and give initial value of 1. Later,
// if getNum = 0, then it will break the getuntilzero loop
int highNum; // declare the largest number as int
int lowNum; // declare the lowest number as int

public void run() {

// Print game description
println("This program finds the largest and smallest numbers.");

/*
* Precondition is high/low variables are initialized as int.Post
* condition is if getNum1 = 0 then message "Please try again.". If
* number is not = 0, set both highNum and lowNum to getNum1
*/
getNum1();

/*
* Precondition is highNum == lowNum. Get a new number, num2, and if
* num2 = 0 then print "Highest: highNum" and "Lowest: lowNum" and end
* the method/program. If num2 is not = 0 determine if num2 is greater
* than highNum or less than lowNum. If num2 > highNum, highNum is now
* equal to num2. If num2 < lowNum, then lowNum is now equal num2. If * num2 is equal to highNum and num2 is equal to lowNum, then getNum2 * again. Postcondition is num2 is now set to set to either lowNum or * highNum. lowNum is the lower number. highNum is the higher number. * lowNum is not equal to highNum. */ getNum2(); /* * Precondition is lowNum is not equal to highNum. get a new number * getNum. while getNum is not equal to 0, if getNum < lowNum, then * lowNum is now equal to getNum. if getNum is higher than highNum, then * highNum is now equal to highNum. get a new number again. if getNum is * equal to zero, display the highest and lowest numbers and end the * method/program Postcondition is largest and smallest numbers are * displayed. */ getUntilZero(); } public void getNum1() { num1 = readInt("?:"); if (num1 == 0) { println("Please try again without 0."); getNum1(); } highNum = num1; lowNum = num1; } public void getNum2() { if ((highNum != 0) && (lowNum != 0)) { num2 = readInt("?:"); if (num2 == 0) { println("Biggest number:" + highNum); println("Smallest number:" + lowNum); getUntilZero(); } else { if (num2 > highNum) {
highNum = num2;

} else {
if (num2 < lowNum) { lowNum = num2; } else { if ((num2 == highNum) && (num2 == lowNum)) getNum2(); } } } } } public void getUntilZero() { while ((getNum != 0) && (highNum != lowNum)) { getNum = readInt("?:"); if (getNum == 0) { displayHighLow(); endApp(); break; } else { if (getNum < lowNum) { lowNum = getNum; } else { if (getNum > highNum)
highNum = getNum;
}
}
}
}

// precondition is sentinel has been entered
// postcondition is smallest and largest numbers are displayed
private void displayHighLow() {
println("Smallest:" + lowNum);
println("Largest:" + highNum);
}

// :-)
private void endApp() {
println("Thanks for playing");

}
}

And here is the output:
Working

Stanford cs106a, Assignment 2; Problem 3. – FindRange – Part 1

The instructions are to write a ConsoleProgram that reads in a list of integers, one per line, until a sentinel
value of 0 is entered. When the sentinel is read, your program should display the smallest and largest values in the
list, as illustrated in this sample run:
SampleFindRange

The program should handle the following special cases:
• If the user enters only one value before the sentinel, the program should report
that value as both the largest and smallest.
• If the user enters the sentinel on the very first input line, then no values have been
entered, and your program should display a message to that effect.

I found that programming this assignment got me familiar with using the debugger. I place breakpoints along the lines of code I want to watch. I start the program in debugging mode and then hit the resume (F8) button to run the program until the next break-point, error, or endless loop :-p. I can then watch as variables are assigned values, and at what point a “while” iteration loops. I can see if certain conditions are met and if so, what happens next.

Also, I found that it’s not over til it’s over and the project is not complete until the program has been tested extensively. Just when you think it’s complete and you run a test one more time, the program doesn’t behave as expected. This is just the case below. The program is mostly complete except for when multiple values are supplied; the program loses track of which number is the lowest. But for today I’m happy with the progress I made.

Besides the debugger I learned about the “break;” command, ‘and’ (&&) and ‘or’ (||) operators, and appropriate use of methods(). Although I did not create a method in this program, I understand I can take code that has been repeated somewhere, turn it into a method, and clean up the code in general.

Here’s where I am so far. First the code, then the condition cases fulfillment, a successful run, and then the last problematic condition that still needs to be resolved.


/*
* File: FindRange.java
* Name: Jason Coltrin
* Section Leader: n/a
* --------------------
* This file is the starter file for the FindRange problem.
* write a ConsoleProgram that reads in a list of integers, one per line, until a sentinel value of 0
* is entered. When the sentinel is read, your program should display the smallest and largest values
* in the list.
* The program should handle the following special cases:
* • If the user enters only one value before the sentinel, the program should report
* that value as both the largest and smallest.
* • If the user enters the sentinel on the very first input line, then no values have been
* entered, and your program should display a message to that effect.
*/

import acm.program.*;

public class FindRange extends ConsoleProgram {

public void run() {

println("This program finds the largest and smallest numbers.");

int getNum = readInt("?:"); // gets initial input from user
int sentinel = getNum; // sets first input to value sentinel
int highNum = 0;
int lowNum = 0;
highNum = getNum; // allow the first input highNum to be set as the
// largest number

if ((getNum == 0) && (highNum == 0)) { // check for first input zero
// constraint
println("No values have been entered. Please start over.");

} else { // if not 0, set getNum to be equal to highNum
if (getNum > highNum) {
highNum = getNum;
}
getNum = readInt("?:"); // ask for the 2nd getNum
if (getNum < highNum) { lowNum = getNum; // assign new getNum to lowNum if less than // highNum } if (getNum == 0) { // if second getNum is equal to 0, meet // constraint to set high/low to same number println("Smallest:" + highNum); println("Largest:" + highNum); lowNum = highNum; } } while ((sentinel != 0) && (lowNum != highNum)) { getNum = readInt("?:"); if (getNum == 0) { println("Smallest:" + lowNum); println("Largest:" + highNum); break; } if (getNum > highNum) {
highNum = getNum;

} else {

if (getNum < highNum) { lowNum = getNum; } } } } }
Condition 1 met:
NoValuesException
Condition 2 met:
OneNumberException
Success!...
success
But wait, not so fast...
BugDoh

Stanford cs106a Assignment 2, Problem 2 – Hailstone sequence

Here is my answer to the hailstone sequence problem. The problem is as follows:

Pick some positive integer and call it n.
If n is even, divide it by two.
If n is odd, multiply it by three and add one.
Continue this process until n is equal to one.

The numbers go up and down, but eventually—at least for all numbers that have ever been tried—comes down to end in 1. In some respects, this process is reminiscent of the formation of hailstones, which get carried upward by the winds over and over again before they finally descend to the ground. Because of this analogy, this sequence of numbers is usually called the Hailstone sequence, although it goes by many other names as well.


/*
* File: Hailstone.java
* Name: Jason Coltrin
* Section Leader: n/a
* --------------------
*This file is the starter file for the Hailstone problem.
*Pick some positive integer and call it n. If n is even,
*divide it by two. If n is odd, multiply it by three and
*add one. Continue this process until n is equal to one.
*/

import acm.program.*; //needed to run ConsoleProgram

public class Hailstone extends ConsoleProgram {
public void run() {

int n = readInt("Enter a number:"); // get user's number
int evenNum; // define even number as integer
int oddNum; // define odd number as integer
int halfNum; // define Hailstone step1 if number is even as integer
int tripleOne; // define Hailstone step1 if number is odd as integer 3n+1
int count = 0; // define steps it takes to get to 1 as count and initialize at 0

if (n == 1) {
println("Please enter a number larger than 1.");
}

while (n != 1) { // run if/else statement until n is not equal to 1

if ((n % 2) == 0) {
evenNum = n;
halfNum = (evenNum / 2);
println(evenNum + " is even, so I take half: " + halfNum);
n = halfNum;

} else {
oddNum = n;
tripleOne = ((3 * n) + 1);
println(oddNum + " is odd, so I make 3n+1: " + tripleOne);
n = tripleOne;

}
count++; //increment counter 1 for every while loop
}

println("You've reached the number 1, I'm stopping.");
println("The process took " + count + " steps to reach 1.");
}
}

This problem makes use of a while/if/else loop, and increment a counter. I thought I would have to use a For loop and a Boolean to increment the counter, but once I initialized the count variable at 0, it just took a little work to place the count++ in the correct location.

Here is what the output looks like:
HailstoneConsole

Stanford cs106a Assignment 2, Problem 1 – PythagoreanTheorem

Below is my answer for Problem 1, Assignment 2:

The question asks,
By using the Pythagorean Theorem, calculate the value of c, in relation to input provided by the user for the values of a, and b. Write a ConsoleProgram that accepts values for a and b as doubles (you can
assume that a and b will be positive) and then calculates the solution of c as a
double.

My solution is as follows:

/*
* File: PythagoreanTheorem.java
* Name: Jason Coltrin
* Section Leader: n/a
* -----------------------------
* This file is the starter file for the PythagoreanTheorem problem.
*/

import acm.program.*; //imports classes needed to run ConsoleProgram

public class PythagoreanTheorem extends ConsoleProgram {
public void run() {
println("Enter values to compute the Pythagorean Theorem!");

// sets user input of a: to n1 as double
double n1 = readDouble("Enter value of a: ");

// sets user input of b: to n2 as double
double n2 = readDouble("Enter value of b: ");

// order of calculation calculates in parentheses first, then + second,
// and sets value of sqr root to variable c.
double c = Math.sqrt((n1 * n1) + (n2 * n2));

// Prints the answer after "C ="
println("c = " + c);
}
}

The output looks like below:
A2-P1

“For” loop examples

A few for loop examples:

    • General form: 

for (init; condition; step) {
statements
}

  • init done once at start of the loop
  • condition (can be a boolean) checked before every iteration through the loop – we execute the statements if they are true.
  • step every time through loop after statements
  • example:

for (int i = 0; i < 5; i++) { println(i); }

The result here of course would be the counting up to 5, starting at 0, and the output would be 0, 1, 2, 3, 4

  • Another example of counting down:

for (int i = 6; i > 0; i -= 2) {

println(i);

}

This will cause 2 to be subtracted from i with each pass through the loop and will not print out 0 because 0 is not > 0:

6

4

2

Here is an enhanced "for" loop in Java introduced in Java 5:

public class Test {

public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for (String name: names) {
System.out.print(name);
System.out.print(",");
}
}
}

Here your output will look like:
10,20,30,40,50,
James,Larry,Tom,Lacy

The "break" keyword will end the loop if a condition is met, for example:

for(int x : numbers ) {
if( x == 30 ) {
break;
}

As such the following output:
10,20

The continue keyword will continue the loop and for example, skipping thirty something like this:

if( x == 30 ) {
continue;
}

and the following output:
10,20,40,50

kudos to Stanford University & http://www.tutorialspoint.com/

 

 

 

Eclipse IDE Tips and Tricks

I wish I had know about these a couple weeks ago, but anyway here are a few tips and tricks I found for using the Eclipse IDE with Java:

// Eclipse tips and tricks
1. Quickly add main method by typing “main” followed by ctrl+space and then enter
2. Quickly format your source code by typing ctrl+shift+f or right click->source->Format
3. Type sysout then ctrl+space, then enter, to generate System.out.println();
4. F11 runs your application in debug mode – if no breakpoints, it will run normally
5. Hit ctrl+shift+o for organize imports. This will give you list of possible imports and then
add or the import to/from the top of the source file.
6. Type syserr and then ctrl+space to quickly type out System.err.println();.
7. to rename a variable, select the variable, right click, choose refactor -> rename, and all
of the instances where that variable name has been used will be changed.
8. You can rename a class as well by right-clicking on the .java file in the Package Explorer
pane, then -> refactor -> Rename.
9. When you highlight a line or block of code and push Ctrl + Alt together,
and the down arrow, it clones the line or block. (You may have to disable your intel
graphics card drivers or your screen will flip.)
10. Use Ctrl+Shift+/ to comment blocks of code and Ctrl + Shift + to uncomment them again.
11. If you want to find all the places a variable is used, right-click on the variable, choose
references -> workspace (or project, hierarchy). This will find all of the variables of
that name even in other classes/java files.
12. In order to find where a variable is declared, click on it, then press F3. This also works
for finding where other classes are declared in other files.
13. To remove/delete whole lines, click anywhere in the line and hit Ctrl+d.
14. Many methods, objects, arrays, etc will autocomplete. For example an array, type the
letter “A” then ctrl+space.
15. For new private fields, you can generate Getters and Setters automatically by right clicking
->Source ->Generate Getters & Setters. The same works for creating Constructors with the
correct parameters.
16. If you want to override methods in a superclass, right click -> source -> Override/Implement
methods…

I’m sure these will help me develop a little faster. Just formatting and adjusting my brackets to make things prettier has taken up a lot of time. Not to mention finding where variables are declared. I’m not familiar with what Getters & Setters or Overriding methods are used for at this time but apparently they are just busy work that is unnecessary to write out every time.

Object Reference and Arrays

The standard eight primitive variable types are:

boolean char byte short int long float double

a mnemonic to remember this is:

Be careful!

Bears

Shouldn’t

Ingest

Large

Furry

Dogs

I think I’m beginning to understand object references in Java as well as arrays. Object references use a dot where you use the thing before the dot to get to the thing after the dot. For example:

myCat.meow();

means use (the object referenced by) “myCat” to invoke the “meow()” method.

In order to 1. declare an object, 2. create an object,  and 3. assign the object there are 3 steps:

1st, declare a reference variable:

Cat myCat   — the reference variable is named myCat, and the variable is forever of the type Cat.

2nd, create an object

new Cat();   — tells the java virtual machine to allocate space for a new Cat object on the heap

3rd, link the object and the reference

Cat myCat = new Cat();   — Assigns the new Cat object to the reference variable myCat

As references are modified throughout an application, it may turn out that an object that used to refer to one object no longer refers to that object and now refers to another object. But that does not mean that the object reference has disappeared, nor the object that it originally referred to. However, abandoned objects that are left on the heap are fodder for the garbage collector. Also references can point to Null which means for example, the reference myCat could point to Null, and it just sits there. References aren’t collected as garbage because later a different object could still be assigned to it.

Arrays themselves are always objects, and can be declared just like object references to hold primitives or other object references.

Here’s an example of how to create an array of cats:

1. Declare a Cat array variable (the brackets are what defines Cat as an array)

Cat[] pets;

Cat[] is the type of the array, and pets is the variable. ( this is where I get confused)…

2. Create a new Cat array with a length of 6, and assign it to the previously-declared Cat[] variable pets

pets = new Cat[6];

3. The objects are still missing so let’s create new Cat objects and assign them to the array elements.

pets[0] = new Cat();

pets[1] = new Cat();

pets[2] = new Cat();

So now pets[0, 1, 2] refer to a Cat() object, however, the other 3 pets do not refer to anything until we declare that, in fact, pets[3, 4, 5] = either a new cat object, or a different existing object, or null (a reference variable that is not referencing any object has a value of null).

Take for example two different ways of creating 10 contact objects:

Contact[] ca = new Contact[10];

while (x < 10) {

ca[x] = new Contact();

x = x + 1;

}

_________________________________

Contact refc;

while ( x < 10 ) {

refc = new Contact();

x = x + 1;

}

In this second method of creating 10 contact objects, only the last of the Contact objects that was created will be accessible. With each trip through the loop, an assignment of a new object to the one reference variable was made. All the other previously referenced objects were abandoned on the heap – unreachable. The second method of creating the array of 10 contact objects is pretty useless.

 

 

Stanford’s CS106a Programming Methodology Courses

I’ve been studying the free Standford CS106a lectures for some time now on YouTube – Playlist Here – and have been following along with the assignments. The first assignments revolve around manipulating a java-based robot application named Karel. Karel can only perform a limited amount of movements like move, turn left, pick beeper, and put beeper. The assignment I’ve been working on involves moving Karel around a number of different worlds and place beepers in a checker pattern. However, if trying to move through a wall, Karel can be blocked. Other errors like these pop up and make my life suck. During the programming of the checkerboard application, I utilized and became familiar with the following:

  1. Program structure
  2. Top-down programming/decomposition/subproblems
  3. Conditional statements (if) (if/else)
  4. Iterative Statements (for/while)
  5. Method definition – private void name () { … }
  6. Recursion – having a method call itself
  7. Using import to include definitions from libraries

Programming with Java is all about primitives, camelcase, fence posts, and calling methods on objects! Programming is quite methodical and step-by-step in the first stages of an application. Thinking about what are my most simple, primitive moves and actions first, and then building on those is the start. Then once the most simple steps have been defined, I start to create methods that are more universal, and writing statements that are sub-methods of the top level methods. When programming top-down it’s fun because I am beginning to rely on the skills I’ve learned to trust that I can write later what I’d defined as a method.

Anyway, getting to where Karel ends in the video linked below has been a pretty mind-wracking endeavor. I’ve pretty much started over with the code three times but I can finally see the light at the end of the tunnel. One of the most difficult obstacles is writing the code so that it will run the same in all of the different “worlds” (8×8) (8×1) (1×8) etc. Also another thing about programming I’ve found is that by relying on my own skills and knowledge I have found I can arrive at a solution faster than searching online and there are many different ways of accomplishing the same task.

2013-07-13 16.09.29