Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

  • 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.

    //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.

    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:

    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:
    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
    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
    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:

    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).

    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?

    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
    This article was originally published in forum thread: General CS concepts started by helloworld922 View original post