Go Back   Java Programming Forums > Learning Java > Java Code Snippets and Tutorials


Reply
 
LinkBack Thread Tools Display Modes
  #11 (permalink)  
Old 07-10-2009, 04:04 AM
helloworld922's Avatar
Super Moderator
 

Join Date: Jun 2009
Posts: 1,215
Thanks: 5
Thanked 258 Times in 234 Posts
helloworld922 will become famous soon enoughhelloworld922 will become famous soon enoughhelloworld922 will become famous soon enough
Default Re: General CS concepts

Variables and Objects

Variables and objects are basically things you can hold (err, that the computer can hold in memory). They store some sort of data that represents something. We'll start by focusing on variables.

Variables have 5 properties: data, name, type, scope, and lifetime.

Variables can be thought of as buckets. Each bucket can hold something (an object). Importantly, variables can only hold 1 item in their bucket at any one time, but that item can be changed (unless the variable is final). The item that bucket is holding is the data/value of that variable.

A variable's name is pretty self explanatory. Imagine you have a big black marker, and you wrote on the variable a name. Then, anytime someone needed that bucket (whether to put something in or take something out), they'd get the bucket labeled with that name.

A variable's type is what kind of things that variable can hold. If you had a bucket for milking cows for example, you wouldn't want to use it to change the oil in you engine.

A variable's scope is anywhere the variable can be used. Say you had a bucket on a farm in Kansas. You can use that bucket anywhere on that farm in Kansas. However, if you decide you want to milk cows in Nebraska but happen to forget your bucket, you wouldn't be able to use that bucket. However, when you come back to your farm in Kansas, you can use that bucket again.

The last characteristic of variables is lifetime. Lifetime is when the bucket physically exists. If one day you decide you want to set off dynamite in your bucket, it will cease to exist, and can't be used again.

So enough with the analogies, let's discuss variables in Java. Java variables can have any standard name that you can give to anything else:

must start with any unicode character so long as it isn't a defined operator or a digit, and anything after that can be any unicode character that isn't a defined operator. (Thanks Json Maybe I should actually learn something about Java before trying to help others). Quotes (single or double), brackets/braces/parenthesis, reserved Java keywords, and whitespaces are also dis-allowed.

Java Code
//valid variable names:
Hello
i
_
$
p_3
Á
While any of these are valid variable names, there is a convention that is is followed in Java:

Try to find descriptive variable names. They should describe what it is that variable is for. Names like "sum", "index", and "average" are fairly common. Bad names would be "_", "$#@", etc.

It's important to note that Java is case sensitive. so the variable "Hello" would be different from the variable "hello". Conventionally, variables start with a single lower-case word, then subsequent words would have their first character capitalized. It's also fairly common to find variable names with subsequent words separated by underscores. In the latter case, all the letters are lower case.

Java Code
public int averageHeight;
public int average_height;
public int index;
The type of a variable defines what that variable can hold. All variables in Java must be declared with their type and their name:

Java Code
int someInt; // type int, name someInt
double x; // type int, name x
If you want a variable to be constant, or final, use the final keyword:
Java Code
final double pi = 3.141592;
final variables MUST have a value set to them right away, and that value cannot change for the lifetime of that variable.

There are two main data types in Java: primitive, and objects. Objects will be discussed later. The primitive Java data types are: byte, char, short, int, long, float, double, and boolean. Note: sometimes String is considered a primitive data type because of the way the JVM handles strings, but String here will be considered objects because it will be easier to understand them as objects (and also because they technically are objects).

Primitive variables are those that hold their value directly. Object variables are those that contain a reference to an object. Object variables will be discussed later.

Scope is a bit tricky to explain. I will find a good way to explain this and post it later. For now, here are some examples.

ex:

method scope
Java Code
public static void main(String[] args)
{
     int x = 0;
     doIt();
// point 1
}

public static void doIt()
{
     int y = 1;
// point 2
}
Here, on our original sheet (main method), the variable x is in scope and is available for use anywhere in main. When doIt is called, x goes out of scope because we got out a scratch sheet to do work for the doIt method. On that new sheet, we have y in scope. When doIt ends, y goes out of scope (actually, it disappears completely in this case) and is not available to the original main method.

Curly bracket scope
Java Code
int a=0, b=1;
if (true)
{
     int c = 3;
// point 1
}
// point 2
Here, at point 1, we still have everything available from the original scope, in addition to anything available in our current scope denoted by the curly braces. At point 2, the inner curly-brace stuff goes out of scope, and we only have a and b available.

Lifetime in Java is when the variable actually exists. It's probably even more confusing than scope, and a lot of people get it confused with scope. Because of Java's garbage collector, the lifetime of any variable is from when it's first instantiated to when all references to it are gone. Ex:

Java Code
public static void doIt()
{
     String a = "hello";
     doNothing();
}

public static void doNothing()
{
     String b = "goodbye";
}
When someone calls the doIt method, the string a will be created (and it's lifetime has started). It is also in scope because it's in the little curly brackets of the doIt method. However, when the doNothing is called, a goes out of scope, but there is still a reference to it (due to the implementation of recursion, I won't discuss the details here). The string b is then created and is in the scope of the doNothing method. The doNothing method then returns, and b goes out of scope, and is also destroyed because there are no more references to it, thus ending its lifetime. The String a comes back in scope, and because there is nothing left to do int the doIt method, it too immediately goes out of scope and is destroyed.

Hopefully this makes sense, this is probably the most confusing part about computer science (memory management/keeping track of variables).

Here are some questions about variables and objects:

1. For each of the lettered comments, describe which variables are in scope and which are out of scope. Also, give the lifetime of all the variables (when are the created, and when are they destroyed).

Java Code
public static void main(String[] args)
{
     for (int i = 0; i < 5; i++)
     {
          System.out.println("Determining stats...");     // a
          doIt(i);
          // c
     }
     System.out.println("Done");     // b
}

public static void doIt(int number)
{
     if (i % 2 == 0)
     {
          System.out.println(i + " is even"); // d
     }
     else
     {
          System.out.println(i + " is odd"); // e
     }
}
2. What is the output of this program?

Java Code
public static void main(String[] args)
{
     int i = 1;
     int j = 2;
     System.out.println(myFunc(i,j));
}

public static int myFunc(int j, int i)
{
     if (i > j)
     {
          return j;
     }
     else
     {
          return i;
     }
}
3. Describe in your own words the 4 defining features of a variable: name, value, scope, and lifetime.

Answers are to come sometime



__________________
ASCII a question .. Get an ANSI

Please surround your code with [highlight=Java]code goes here[/highlight].

Last edited by helloworld922; 18-10-2009 at 03:23 PM.
Reply With Quote
The Following User Says Thank You to helloworld922 For This Useful Post:
Json (07-10-2009)
Sponsored Links
Java Training from DevelopIntelligence
  #12 (permalink)  
Old 07-10-2009, 08:02 AM
Json's Avatar
Super Moderator
 

Join Date: Jul 2009
Location: Manchester, United Kingdom
Posts: 1,157
Thanks: 54
Thanked 136 Times in 132 Posts
Json will become famous soon enoughJson will become famous soon enoughJson will become famous soon enough

I'm feeling Happy
Default Re: General CS concepts

To clarify some points above I here have two classes which will look really stupid.

Both of them are valid syntax and they show that you can use certain symbols as variable names as well as class names. It also shows you that you can create a final instance member without setting it straight away, but you HAVE to set it in the constructor or in an instance block but like above, you can only set it ONCE.

Now for the freaky stuff.

CAUTION: This is not best practise, DO NOT do this when programming

Java Code
public class _ {

    public int _ = 0;

    public final int __;

    public _() {
        this._++;
        this.__ = 5;
    }

    public static void main(final String... arguments) {
        final _ _ = new _();
        System.out.println("_ = " + _._);
    }
}

Java Code
public class $ {

    public final int £;

    public int $ = 0;

    public $() {
        this.$++;
        this.£ = 5;
    }

    public static void main(String... arguments) {
        final $ $ = new $();
        System.out.println("$ = " + $.$);
    }
}
And also the conclusion to the post above this one is that all Java developers are farmers

Happy coding! Enjoy!

// Json
Reply With Quote
  #13 (permalink)  
Old 01-11-2009, 04:39 PM
helloworld922's Avatar
Super Moderator
 

Join Date: Jun 2009
Posts: 1,215
Thanks: 5
Thanked 258 Times in 234 Posts
helloworld922 will become famous soon enoughhelloworld922 will become famous soon enoughhelloworld922 will become famous soon enough
Default Re: General CS concepts

Exceptions

Exceptions are special things that interrupt normal program flow. They're used to create robust methods that follow their contracts exactly. Here's a small example:

Java Code
// * note: this code won't compile as-is, but will demonstrate our purposes here
public int doOperation(int a, int b, char operator)
{
     if (operator == '+')
     {
          return a+b;
     }
     else if (operator == '-')
     {
          return a-b;
     }
     else if (operator == '*')
     {
          return a*b;
     }
     else if (operator == '/')
     {
          return a/b;
     }
}
What happens if the operator given isn't +,-,*, or / ? What if they input doOperation(1,3,'@') (perfectly legal to the compiler)? Should you return 0? -1? Both of these values are valid return arguments, so there is no way for the calling method to distinguish between a valid output and one that's used to denote an error.

The answer is to use exceptions. Exceptions are thrown, and then must be caught. There are two types of exceptions: unchecked, or checked. The difference is who has to catch the exception. Unchecked exceptions don't have to be caught, and checked ones do. Note: the JVM will end up catching all exceptions that get passed to it, but this is quite nasty and means your program is completely terminated.

To throw an exception:

Java Code
throw new Exception();
Generally, it's best not to just throw an exception, but actually inherit from the Exception class.
Note: the Exception class is a checked exception, so it must be caught. If you want an unchecked exception, inherit from the RuntimeException class.

So how do you catch an exception? The answer is with try/catch blocks.

Java Code
try
{
    // code
}
catch(Exception e)
{
     // stuff to do if an Exception is caught
}
This format will catch all exceptions (even RuntimeExceptions, which inherit from Exception). If you only want to catch a certain branch of exceptions:

Java Code
try
{
     // code
}
catch(NullPointerException e)
{
    // stuff to do if a NullPointerException is caught
}
Here, the catch block will catch NullPointerException's, and all children classes of NullPointerException.

So what if you don't want your method to catch the exception, but throw it up to the caller? For unchecked exceptions, you don't have to do anything, but for checked exceptions you have to declare in the method header that your method will throw certain types of exceptions

Java Code
// note: InvalidOperatorException isn't a default Java Exception, but here pretend it extends the Exception class.
//There is class called UnsupportedOperationException, but to demonstrate our purposes, I chose not to use it here
public int doOperation(int a, int b, char operator) throws InvalidOperatorException
{
    ...
}
Here, the doOperation declaration has a checked exception, but there's also another unchecked exception that could be thrown: the ArithmeticException, which could be thrown if the user tries to divide by 0. Note that it doesn't have to be declared that the doOperation method throws this exception, but declaring that it does doesn't force the caller to catch it.

Java Code
// will do the exact same thing as the above code
public int doOperation(int a, int b, char operator) throws InvalidOperatorException, ArithmeticException
{
   ...
}
The last section here (yes, finally got around to finishing it!) is about information you should include in your inherited exception class. For the most part, the Exception class will handle almost all of your needs. However, you may reach a time you will want to pass extra information back for debugging purposes such as the values of certain variables. Note that I haven't really had to do this, but it may become necessary when you start to work on larger Java projects. Doing this is exactly the same as it is for any other class, because Exception is a regular class that just happens to have the property of Throwable, as well as some other nice properties like getting the stack trace, but for all intensive purposes, there's nothing special about it beyond this.
__________________
ASCII a question .. Get an ANSI

Please surround your code with [highlight=Java]code goes here[/highlight].

Last edited by helloworld922; 13-01-2010 at 01:21 AM.
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On




100 most searched terms
Search Cloud
2 dimensional arraylist java 2d arraylist java actionlistener actionlistener in java addactionlistener addactionlistener java convert double to integer java double format java double to integer in java double to integer java drag en drop programmeren java eclipse shortcut keys exception in thread "awt-eventqueue-0" java.lang.outofmemoryerror: java heap space exception in thread "main" java.lang.nullpointerexception exception in thread "main" java.lang.outofmemoryerror: java heap space format double in java format double java get mouse position java java 2d arraylist java actionlistener java double format java double formatting java double to int java double to integer java format double java forum java forums java get mouse position java list to map java mouse position java programming forum java programming forums java programming practice problems java send keystrokes to another application java two dimensional arraylist java.io.ioexception: premature eof java.lang.classformaterror: truncated class file java.lang.outofmemoryerror: java heap space java.util.arraylist jbutton action jbutton actionlistener jtextarea font jtextfield font size jxl.read.biff.biffexception: unable to recognize ole stream programming mutators and generics smack api two dimensional arraylist two dimensional arraylist java unable to sendviapost to url what is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

All times are GMT. The time now is 02:03 AM.
Powered by vBulletin® Copyright ©2000-2009, Jelsoft Enterprises Ltd.