Posted in Uncategorized

Java Post #2 Learn the Java Language 《《o(≧◇≦)o》》

⌒(≧ x ≦)⌒

Values vs. Variables vs. Types
  • 3 is an integer value. 
  • x might be an integer variable, meaning it can hold any integer value, for example 3. 
  • Both 3 and x are of type integer. 
  • We often say things like “x is 3”, but “is” is misleading — really, x “holds” 3.
If y is another integer variable, you can’t have x hold y. x can only hold an integer value, such as the value of y. An assignment statement like x=y says that x’s value should become what y’s value is.
Some people call variables “lvalues”, where the “L” at the front of “lvalue” means that it is something that can appear on the Left hand side of an assignment. Whether you find this confusing or clarifying is up to you.
“Automatic” variables are those that are part of some code to execute. This name comes from how their storage space (on the stack) is automatically created and deleted when the routine is entered and exited. 
The only other kind of variable (besides automatic) in Java is an instance (or class) variable. These terms have to do with scope, not with type.

Types

Java has the following types:
    9     [name of class or interface]          any object which is a kind of that class or interface
    10   [array type]                                 any object which is a kind of that
The first eight types listed above (i.e. all but the last two) are called the primitive types, since they are not defined in terms of anything else — they are just sequences of bits that computer cpus are ready to deal with. You are probably already familiar with types like these, so I won’t waste any more words trying to explain them!
Anything that is not a primitive type is a reference type. A reference type is a class, interface, or array type. A variable of any reference type may be set to null, meaning that it doesn’t hold anything. (If you are familiar with pointers you will recognize that reference types are pointers to objects…If not well, whoops the cats outta the bag…)
The last two types in the table mean that you can use a class or interface name just like you would use a primitive type. This is pretty neat. 
Every class is effectively a type. So if myDog is a variable of type Dog, then any kind of Dog may be assigned to the variable myDog. As another example, if a variable is of type Object, you can assign any object at all to it.
Dog bigDog = new Dog(); 
bigDog.fetch(); // This calls the fetch() routine defined in class Dog 
Object anObject = bigDog; // This assignment is ok, since Dog is a kind of Object 
anObject.fetch(); // This is a compile-time error, since fetch() is not defined for Objects 
((Dog)anObject).fetch(); // This will work, but if anObject does not contain a  kind of Dog when this statement is executed at  run-time, then this will generate a ClassCastException
Even classes themselves are objects, of the class Class, so their type is Class. You don’t normally have to deal with this, but it is reassuring to know that absolutely everything beyond the primitive types is an object of some class!
There are heaps of “built-in” classes (in the standard libraries), plus of course all the classes you create. So there are as many types as you want!
*sigh…

Arrays

The last entry in the table above is for array types. They are represented by having any of the previous types followed by some number of []’s, one for each dimension of the array. 
So Dog[] is an array of Dog’s, and int[][][] is a 3D array of ints. Array types are classes like any other class, and arrays are objects like any other object. For example, an array has an instance variable length that says how big the array is. So if mat is a variable of type int[][], then mat.length tells how many int[] rows it has, and mat[3].length gives the length of the third row. The size of a dimension is not a part of the type. Such sizes are aspects of the values that get assigned.
int[][] mat; // mat === null (mat, as an object, defaults to null) 
mat = new int[2][2]; // mat === {{0,0}, {0,0}} 
mat = new int[3][]; // mat === {null, null, null} 
mat[0] = new int[4]; // mat === {{0,0,0,0}, null, null} 
mat[1] = new int[3]; // mat === {{0,0,0,0}, {0,0,0}, null} 
mat[2] = new int[2]; // mat === {{0,0,0,0}, {0,0,0}, {0,0}} 
mat[0][2] = 7; // mat === {{0,0,7,0}, {0,0,0}, {0,0}} 
mat[3][2] = 4; // throws IndexOutOfBoundsException
//Jargon for today: This array definition above is called Jagged Array 
//To be more specific an array with irregular number of elements in a row are called Jagged Array
If you have an array of type Dog[], then each member of the array can be any kind of Dog.
Dog[] dogList = new Dog[5]; // dogList holds {null, null, null, null, null}
new Dog[5] creates space to hold 5 dogs — it creates 5 variables of type Dog. These variables are each initialized to null until you assign something else to them.
The source code can contain an explicitly typed-out array, but for some reason only in an initializer:
int[][] mat = {{2,3},{4,5}}; // this is ok 

mat = {{6,7},{8,9}}; // but this won’t compile!
For some reason, the run-time names of array classes are different from how you specify them in the source code — an array of ints is int[] in the source code but “I” at run time. I can’t imagine why this is.
A Very Subtle Point: 
If you have a variable dogList of type Dog[], then you can also assign dogList to be an array of type SeeingEyeDog[] assuming SeeingEyeDog is a kind of Dog. 
But then you need to be careful that you won’t be hit by the following potential run-time problem: 
If you say dogList[3] = stupidDog (which looks fine to the compiler as long as stupidDog is a kind of Dog), an ArrayStoreException can be thrown, since an array of type SeeingEyeDog[] cannot contain stupidDog if stupidDog is not a kind of SeeingEyeDog.

Initialization

Objects are always initialized to null unless they are explicitly initialized otherwise. 
Primitive-type variables fall into two categories: Automatic ones must be initialized before use. Instance (or class) ones are automatically initialized to 0 or false.
If an automatic variable is not initialized before it is used, that is a compile-time error. Here’s how the compiler decides whether something is initialized:

Change all values (except for boolean constant expressions) to “blah”.  Then, see if you can still tell that the variable must necessarily have been assigned, considering just the possible flows of control (including boolean-switched evaluation like &&||?:).  Also, consider try statements to be capable of immediately throwing any exception.

int b;                       |         |  int b; 
while (3>5) {                |         |  while (false) { 
  b = 3;                     |         |    b = blah; 
}                            |         |  } 
foo(b);                      |         |  blah(b); // b not initialized 
                             |         | 
int c;                       |         |  int c; 
if (flag)                    |         |  if (blah) 
  c = 14;                    |         |    c = blah; 
else                         |         |  else 
  c = 17;                    |         |    c = blah; 
foo(c);                      |         |  blah(c); // c is initialized 
                             |         | 
int d;                       |         |  int d; 
if (flag)                    |         |  if (blah) 
  d = 20;                    |         |    d = blah; 
if (!flag)                   |         |  if (blah) 
  d = 30;                    | becomes |    d = blah; 
foo(d);                      |         |  blah(d); // d not initialized! 
                             |         | 
int e;                       |         |  int e; 
if (flag || !flag)           |         |  if (blah || blah) 
  e = 5;                     |         |    e = blah; 
if (flag && !flag)           |         |  if (blah && blah) 
  foo(e);                    |         |    blah(e); // e not initialized! 
                             |         | 
boolean f;                   |         |  boolean f; 
if (flag && (f=true))        |         |  if (blah && (f=true)) 
  foo(f);                    |         |    blah(f); // f is initialized 
                             |         | 
boolean g;                   |         |  boolean g; 
if (flag || (g=true))        |         |  if (blah || (g=true)) 
  foo(g);                    |         |    blah(g); // g not initialized 
                             |         | 
int t;                       |         |  int t; 
try {                        |         |  try { 
  t = 5;                     |         |    t = blah; 
  foo(t);                    |         |    blah(t); // t is initialized 
  throw(new MyException());  |         |    throw(blah); 
} catch (MyException e) {    |         |  } catch (blah) { 
  foo(t);                    |         |    blah(t); // t not initialized! 
}                            |         |  } 

Classes

For convenience, there are classes corresponding to each of the primitive types. 

For example, the Integer class has a constructor to make an integer from a string, and an intValue() method that returns an int:
if (getParameter(“side”) != null)
     side = (new Integer(getParameter(“side”))).intValue();
Strings are totally objects, members of the class String. They are not arrays of characters like in C. If the source code contains “hello”, it will be compiled as a String object.
int theLen = “A String”.length();
The + operator concatenates strings, promoting first if necessary. 
x = “a” + 4 + “c” 
is compiled to the equivalent of: 
x = new StringBuffer().append(“a”).append(4).append(“c”).toString() 
I don’t know whether “value = “+3+4 is supposed to result in “value = 34” or “value = 7”. 
(Note that in Java, the “just try it and see” method can lead to big trouble: Perhaps the Java specification does not specify the answer… in which case you will ofc find some answer when you try it and see on your computer, but then when you write code based on what you learned, your code won’t work on other people’s computers, which have different Java implementations….*sigh…So much for being Platform Independent…) 
You can’t mess with the contents of a String. If you want to, use a StringBuffer instead.

Variable Scope

A variable’s scope is from its declaration to the end of the block it is declared in.

The declaration need not be at the beginning of a block: 
for (int i = 1; i < 10; i++) 
But you can’t declare after a comma, so you can’t do: 
for (int i = 1, byte j = 10; i < 10; i++, j–) // WON'T COMPILE! 
What’s really going on in that example? The first “int” means that everything up to the next ; is a declaration. But the next ; also delineates the next part of the for. So the whole first part must be an int declaration. 
But even the following is no good: 

int i; 
for (i = 1, byte j = 10; i < 10; i++, j–) // WON'T COMPILE! 
If it’s so hard to declare in for loops, I don’t see why it’s allowed at all. *sigh…
Here’s the answer: Java has a hack that lets the initialization of a for loop (but no other weird place) be an initializer. This means that it starts with a type, and then as many variables as you want of that one type, each initialized if you wish. So you can do: 
for (int i = 1, j = 10; i < 10; i++, j–) // compiles ok
Note that if you declare a variable inside a loop, then it is undefined for the part of the loop prior to its declaration, and its initialization, if any, will be performed for every pass of the loop.

Operators

Java basically has all the same operators as C, but + can concatenate strings, and >>> shifts right filling with zero (not the sign bit). 
Floating point values as well as integer values can be incremented and decremented with ++ and –. 
For boolean values, & and && are the same except that && won’t evaluate its second argument if the first argument was false. Or’ing is similar. 
Floating point operations never produce exceptions (they can produce NaN though), and integer operations only generate an ArithmeticException upon /0 or %0. 
A boolean can’t be cast to or from anything else. 
Casts between different integer types either drop bits (to shrink) or extend the sign bit (to grow). 
Casts involving floating point numbers always result in the representable value closest to the original value, except: If the final type is less than 32 bits, first it converts to a 32-bit integer, and then it chops off bits. In particular, very large (or infinite) positive values become -1 and large negative values become 0! 
If NaN is cast to an integer, it becomes 0.

Control Flow

Very simple. Same as C. Hope you know C! Kinda like Python maybe…?

There are only a couple of differences: exceptions, labeled break/continue, and no goto.
Labeled Break and Continue 
A block or statement can have a label, say foo:{some code}. Then, if, inside the labeled part, a break foo; is encountered, the labeled section will immediately be exited. If a continue foo; is encountered, the labeled part (which must be a for, do, or while statement) will immediately be continued. 
Method Declaration
[accessSpecifier] [static] [abstract] [final] [native] [synchronized] returnType methodName ([paramlist]) [throws exceptionsList]
  • static means the method is a class method — it may be invoked by ClassName.methodName as well as instance.methodName (there is no difference — use whichever is handier). 
  • A static method therefore cannot use instance variables, or this, since there may not even be any instance in existence!
  • abstract means the method has no code — a subclass must override (redefine) the method, supplying code. In this case, the declaration is followed by a semicolon instead of code.
  • final is the opposite of abstract — it means that subclasses are not allowed to override the method.
  • native means the the code for the method is written in some language other than java. We will not discuss this sort of weirdness here…
  • The return type may be a type, or void. If the return type is void, then no value is returned. No return statement is needed, and if there is one (for example to return from a point other than the end of the function’s code), it must omit the value. (It may not even specify a “void” value, e.g. return voidFunction(3,5); is not allowed.)

Variable Declaration

Instance variables are declared in a class definition like this:
[accessSpecifier] [static] [final] [transient] [volatile] type varName [= init];
  • static means the variable is a class variable — there is only one copy of this variable, no matter how many instances exist. Instances do not have their own copy of this variable — they all share the one unique copy. 
  • The variable may be referenced as ClassName.varName as well as instance.varName (there is no difference — use whichever is handier).
  • final means that the value of the variable, specified by the init at the end of the declaration, will never change. This means the compiler can treat it as a constant, rather than creating storage for it, and perhaps make other optimizations as well.
  • transient means that the variable should not be considered part of the object when the object is being archived. What does this mean? Who knows. Current versions of Java all ignore this anyway!
  • volatile means that the variable can be changed asynchronously, and the compiler should specifically avoid optimizations that assume the variable’s value to be, say, the same as what it was the last time you looked.
  • The init is executed when a new instance is created (or when the class is created, if static), prior to the execution of the constructor.

Access Specifiers

Access specifiers are to help make code modular and reusable, by clearly specifying the scope of a class, class variable, or method. 
Small programs can ignore them for the most part, but packages should use them carefully.
There are four scope levels that can be specified:
private | package | protected | public

A class’s code can always access member variables of objects of that class — but if the variable is private, then nothing else can see it, even within the package. 
  • A package variable (the default — there’s no need to explicitly specify this) is visible only within the package. 
  • A protected variable is also visible to subclasses outside the package, but only for objects of those subclasses. (why???) 
  • And finally, a public variable is accessible by code anywhere.
Are these compile-time or run-time restrictions? Run-time! That is, at run time you can ask what methods a class implements, and so on.

“Static” variables or methods are class variables and methods. 


  • What does a public method mean for a non-public class? 
    • For example, interface methods must be public. But why, if the interface isn’t public? 
    • An abstract method may only appear in an abstract class. 
    • You can’t have an abstract static method. 
    • All methods in a final class are automatically final. The same is true for private methods. 
    • If a method is static and has no type or name, then it is init code for the class. 
    • Why can’t a constructor be synchronized (or anything else)?

    Interfaces And Abstract classes

    1. Abstract classes are meant to be inherited from… and when one class inherits from another it means that there is a strong relationship between the 2 classes. For instance, if we have an abstract base class called “Canine”, any deriving class should be an animal that belongs to the Canine family (like a Dog or a Wolf). The reason we use the word “should” is because it is up to the Java developer to ensure that relationship is maintained.

    With an interface on the other hand, the relationship between the interface itself and the class implementing the interface is not necessarily strong. For example, if we have a class called “House”, that class could also implement an interface called “AirConditioning”. Having air conditioning not really an essential part of a House (although some may argue that point), and the relationship is not as strong as, say, the relationship between a “TownHouse” class and the “House” class or the relationship between an “Apartment” class that derives from a “House” class.

    Because a TownHouse is a type of House, that relationship is very strong, and would be more appropriately defined through inheritance instead of interfaces.

    So, we can summarize this first point by saying that an abstract class would be more appropriate when there is a strong relationship between the abstract class and the classes that will derive from it. Again, this is because an abstract class is very closely linked to inheritance, which implies a strong relationship. But, with interfaces there need not be a strong relationship between the interface and the classes that implement the interface.

    2. Java does not allow multiple inheritance..like I had mentioned earlier. In Java, a class can only derive from one class, whether it’s abstract or not. However, a class can implement multiple interfaces – which could be considered as an alternative to for multiple inheritance. So, one major difference is that a Java class can inherit from only one abstract class, but can implement multiple interfaces.

    3. An abstract class may provide some methods with definitions – so an abstract class can have non-abstract methods with actual implementation details. An abstract class can also have constructors and instance variables as well. An interface, however, can not provide any method definitions – it can only provide method headings. Any class that implements the interface is responsible for providing the method definition/implementation.

    Class Declaration

    [public] [abstract | final] class ClassName [extends SuperClassName] [implements InterfaceName1 [,InterfaceName2]…] { 
         in any order: 
         instance vars (class vars marked by “static”) 

         (these can shadow inherited vars! “super.” may help, or may not…) 

         instance methods (class methods marked by “static”) 

         (same goes here) 

         static {init code that gets executed when class is loaded

    • If you don’t specify a superclass, “Object” is assumed. 
    • Public classes must appear in a file with the same name as the class. Why?

    Constructors

    A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
    Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object.
    All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

    Packages

    Libraries (collections of functions) are called “packages” in Java.
    After you understand the syntax and semantics of the Java language, the main thing you will spend time learning about is the large set of classes that are a standard part of Java. You will learn about classes that enable you to get input, produce output, and do countless other things. These classes are supplied as packages.
    You can create a package like this:
         package graphics; // applies to this whole file
         interface Draggable { 
              . . . 
         }

         class Circle { 
              . . . 
         }

         class Rectangle { 
              . . . 
         }
    All files containing the package graphics line will be considered to be in your graphics package.  That line must be the first one in the file!!!  If you don’t specify a package, you are in the “default package”, which is always imported.
    Remember that only public methods and interfaces are visible outside the package.
    You can import by: 
         import graphics.Circle; 
    or 
         import graphics.*;

    If the same class is in two packages you have imported, you can specify which class you intend by prepending the package name to the class name: 
         graphics.Circle


    .
    .
    .

    In case you feel that this is utter gibberish and wanna be redirected to a better place to improve your skills… Feel free to try this site… I studied from there… Its a little confusing but manageable…


    φ(*⌒▽⌒)ノ

    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s