File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes grammar help: what is this structure? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "grammar help: what is this structure?" Watch "grammar help: what is this structure?" New topic
Author

grammar help: what is this structure?

Shawn Ma
Greenhorn

Joined: Feb 18, 2012
Posts: 16
I have the following example code, in which I don't understand the block in braces underlined. Can anyone explain to me the role of it(constructor? private method??..) and why this pair of weird braces? Is there any better way to write the code? also can you give me any comment of my code? (including the namings) Thanks!



The class Matrix is defined by me here:


Can I/should I change the Matrix() constructor underlined above to :


or

?

Can you give me any advice on writing better java code? design rules? coding habits?
Thanks!



Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3373
    
    9
The weird block of code is called an "initialization block". It works roughly the same way as a parameterless constructor, and is run after the super() call in the constructor, but before the rest of the constructor body. They are rarely useful, since you can do most of the stuff they do in a constructor instead.

As for your coding, I would suggest you to document your classes and methods using javadoc properly. They should say what a class models, what a method does, what values it expects and what it returns. You should also check at the start of a method whether the arguments are in agreement with the values that are allowed.

Comments that explain what a snippet of code does should rarely be necessary, the code should be self-explanatory. The use of descriptive variable names is very useful in this regard. Right now I can't tell from a glance what your methods createIdentityOpertor(), identitize() and identity() are supposed to do, and how they are different (although identity() seems to be an alias for createIdentityOpertor()... why?). P.S. shouldn't that read Operator instead of Opertor?

Why do you have a special matrixStack class? Why doesn't its name begin with a capital letter, as per convention? You could use a Deque<Matrix> instead. ArrayDeque and LinkedList already provide a full implementation.

Personally, I don't like using all-caps for constants. It makes my code look very angry. I like to use the same conventions for them as regular variables. But again, this is a personal choice for me.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7057
    
  16

Shawn Ma wrote:I have the following example code, in which I don't understand the block in braces underlined. Can anyone explain to me the role of it(constructor? private method??..)

It's called an initializer, and it's run at the time the object is created and before the constructor (but after any variables defined before the initializer are created) [Edit: beg pard. Stephan is absolutely right - after the super() but before the rest of the constructor].

What you'll see more often are static initializers, which is basically the same construct, except with the word static in front of the opening brace; and they're used for the same sort of thing as you have here: a variable that can't be initialized in a single statement (except that static initializers work with static variables).

Is there any better way to write the code?

Yes: put the code in the constructor. To be honest, I've never found a need for a non-static initializer; although I imagine it might be worth doing if you would otherwise have to repeat the code for a whole bunch of constructors (which doesn't appear to be the case here).

also can you give me any comment of my code? (including the namings)

Well, identitize is an odd name for a method, and I would also add Javadoc comments for your methods; but other than that, you seem to be sticking to the basic conventions and nothing leaps out at me.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here
Shawn Ma
Greenhorn

Joined: Feb 18, 2012
Posts: 16
Thank you, Stephan. It helps a lot, may I ask a few more questions?
It works roughly the same way as a parameterless constructor, and is run after the super() call in the constructor, but before the rest of the constructor body. They are rarely useful, since you can do most of the stuff they do in a constructor instead.

what is a super() call? and Is this a normal constructor way to rewrite the "initializer" code?:

But I am still not clear, why is this necessary to have such a "initializer"? hasn't "private Matrix[] stackMatrix = new Matrix[MATRIX_STACK_SIZE];" already allocated memory for each element of the array?

You should also check at the start of a method whether the arguments are in agreement with the values that are allowed.

Do you mean type check?

Right now I can't tell from a glance what your methods createIdentityOpertor(), identitize() and identity() are supposed to do, and how they are different (although identity() seems to be an alias for createIdentityOpertor()... why?). P.S. shouldn't that read Operator instead of Opertor?

Yes, I think everything can be done with a single method createIdentityOpertor(double[][] dst). The subtle difference is: createIdentityOpertor(double[][] dst) change the value of a given general array to make it an identity, identitize() change the value of the current object which is an array to make it an identity. The former is private, the latter is public.

Stephan van Hulst wrote: You could use a Deque<Matrix> instead. ArrayDeque and LinkedList already provide a full implementation.

I'm sorry but I don't know what are these? are you talking about generics? or some predefined classes? sorry I'm a total beginner.

Thank you again.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3373
    
    9
The first thing *every* constructor does, is call a constructor of its superclass. If you don't do this explicitly yourself, the compiler will insert a call to the parameterless superclass constructor itself. This call looks like: super(); and is the very first line of the constructor body.

When you have an instance variable of any reference type, including arrays, it will start out as null. When you assign a new array to it, you will have allocated memory to hold pointers to all its elements, and initially all these pointers are null. If you want every element to be non-null, you have to manually create a new element at every index.

By checking arguments I mean that sometimes your parameters have constraints, and you have to see if your arguments are valid. For instance, let's say you have a class that needs to store a non-null value in an instance variable, and you have a setter method. If you don't check in the setter method that the argument passed is non-null, then things may go wrong later. Here's an example:
If the constructor didn't check if the engine was null, then the program might crash if we try to drive the car. Now, you could wonder why this is any better, because the program now crashes when you create the car. It's better because the program will crash at the root of the problem, not later, when it's harder to figure out what went wrong.

I suggested a Deque<Matrix>, because you can perform stack operations on it. Deque is a generic interface in the collections framework, much like List and Set. ArrayDeque and LinkedList implement the Deque interface, so you can do stuff like this:
Shawn Ma
Greenhorn

Joined: Feb 18, 2012
Posts: 16
Thank you Winston for the explanation of initializer, however I still do not quite understand.

Winston Gutkowski wrote:
What you'll see more often are static initializers, which is basically the same construct, except with the word static in front of the opening brace; and they're used for the same sort of thing as you have here: a variable that can't be initialized in a single statement (except that static initializers work with static variables).



Yes: put the code in the constructor. To be honest, I've never found a need for a non-static initializer; although I imagine it might be worth doing if you would otherwise have to repeat the code for a whole bunch of constructors (which doesn't appear to be the case here).


my understanding is:
Instance variables always exist and starts from a constructor, so (not static)initializer can always be replaced by a constructor.
Static(class) variables can exist without a constructor, so the initialization may not be realized by a constructor. When it can't be put on one line, we need an initializer block. Because it's static variable, the initializer is called "static initializer".
From the oracle websiteswebpage, it says "There is an alternative to static blocks — you can write a private static method". Now I don't quite understand the "private static method":
1. "static": why is it static? is it that method using only static variables are defined as static method, because the method can be called without creating an instance of the class?
2. "private": private means not accessible from outside of the defining class. so static variable initialization should be prohibited from outside of the defining class?

On the same oracle page, when compared this alternative with that for non-static initializers: "protected final method", I don't understand why one is "private" not "protected", not "final", and the other is?
Sorry this is not quite related to my original question, but I still want to take this chance to learn the basics.


Well, identitize is an odd name for a method.

I want to use this method to change the value of the data field to make it an identity, what is a normal name would you give it?(Sorry for the silly question:p)

Thanks again.

Shawn Ma
Greenhorn

Joined: Feb 18, 2012
Posts: 16


When you have an instance variable of any reference type, including arrays, it will start out as null. When you assign a new array to it, you will have allocated memory to hold pointers to all its elements, and initially all these pointers are null. If you want every element to be non-null, you have to manually create a new element at every index.


so without further initialization, the following two statements have the same effect?

private Matrix[] stackMatrix = new Matrix[MATRIX_STACK_SIZE];

private int[] stackMatrix = new int[MATRIX_STACK_SIZE];


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36498
    
  16
Shawn Ma wrote: . . . my understanding is:
Instance variables always exist and starts from a constructor, . . .
No, that is mistaken. The instance fields are implicitly initialised to 0, false, or null when the class is initialised. Then the instance initialisers are called, then the constructors. So those variables exist before the constructor. The full details are in the Java Language Specification.
I agree with Winston that you ought to use a constructor, rather than an instance initialiser. You should use static initialisers only for static fields; they are useful because they are only called when the class is loaded, before any instances are created.

There is one instance when a constructor does not implicitly or explicitly call super(...);: that is when the first line of the constructor reads this(...);
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3373
    
    9
Shawn Ma wrote:my understanding is:
Instance variables always exist and starts from a constructor, so (not static)initializer can always be replaced by a constructor.
Static(class) variables can exist without a constructor, so the initialization may not be realized by a constructor. When it can't be put on one line, we need an initializer block. Because it's static variable, the initializer is called "static initializer".

Yes sir.

From the oracle websiteswebpage, it says "There is an alternative to static blocks — you can write a private static method". Now I don't quite understand the "private static method":
1. "static": why is it static? is it that method using only static variables are defined as static method, because the method can be called without creating an instance of the class?

As a matter of fact, it *has* to be static, because the method is called during the class loading process before you can create an instance. The method also doesn't work with variables, it just returns a value which is assigned to a static variable.

2. "private": private means not accessible from outside of the defining class. so static variable initialization should be prohibited from outside of the defining class?

Preferably, yes.

Here's what it should look like:
Personally I prefer static initializer blocks though.

On the same oracle page, when compared this alternative with that for non-static initializers: "protected final method", I don't understand why one is "private" not "protected", not "final", and the other is?
Sorry this is not quite related to my original question, but I still want to take this chance to learn the basics.

I don't know why the article says that. But why would you do this in the first place if you can just use constructors/initializers. I don't like initializing members from methods.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36498
    
  16
Shawn Ma wrote: . . .

private Matrix[] stackMatrix = new Matrix[MATRIX_STACK_SIZE];

private int[] stackMatrix = new int[MATRIX_STACK_SIZE];
No, of course they don’t. You have two sorts of array there; the array of primitives is implicitly filled with 0s, and the Object[] with nulls.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3373
    
    9
Shawn Ma wrote:so without further initialization, the following two statements have the same effect?

private Matrix[] stackMatrix = new Matrix[MATRIX_STACK_SIZE];

private int[] stackMatrix = new int[MATRIX_STACK_SIZE]
;


Sorry, no. A new instance of a primitive array will have all its elements initialized as 0 or false. A new instance of a reference array will have all its elements initialized as null.

[edit]

Hah, it looks like I'm slow again.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60053
    
  65

Stephan van Hulst wrote:Personally, I don't like using all-caps for constants. It makes my code look very angry. I like to use the same conventions for them as regular variables. But again, this is a personal choice for me.

I find it odd that you admonish the poster for not using proper conventions for class naming, and then suggest violating the conventions for constant names. I'd recommend following the conventions, even if it makes for "angry" constant names.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Shawn Ma
Greenhorn

Joined: Feb 18, 2012
Posts: 16
yeah, i realized my example is not what I meant to give, I wanted to give an example of two arrays having different reference types, but both are of objects types. such as:


private Matrix[] stackMatrix = new Matrix[MATRIX_STACK_SIZE];

private double[4][] stackMatrix = new double[4][MATRIX_STACK_SIZE];

Is this valid?

Campbell Ritchie wrote:
Shawn Ma wrote: . . .

private Matrix[] stackMatrix = new Matrix[MATRIX_STACK_SIZE];

private int[] stackMatrix = new int[MATRIX_STACK_SIZE];
No, of course they don’t. You have two sorts of array there; the array of primitives is implicitly filled with 0s, and the Object[] with nulls.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3373
    
    9
Bear Bibeault wrote:I find it odd that you admonish the poster for not using proper conventions for class naming, and then suggest violating the conventions for constant names. I'd recommend following the conventions, even if it makes for "angry" constant names.

I agree with you, but in my mind all-caps constants don't seem to be that conventional since I got used to the JavaRanch style guide.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60053
    
  65

Much as I love the Ranch, I'd urge adherence to industry standards over proprietary standards that differ.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3373
    
    9
Hah, I don't know if you intended that as the jab I think; but you make a good point.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2969
    
    9
Hmmm... I was never much of a fan of the Cattle Drive standards, even now that they've been cleaned up a bit. But the rule with constant identifiers always made sense to me; it was basically the one part I liked. No need to get all shouty over a constant, right?

And to me it was always a bit ambiguous what Sun meant by "constant" anyway - a compile-time constant? That's well-defined. But what about a final reference to an immutable object, other than String? Definitely not a compile-time constant, but maybe a constant nonetheless. And what about a final reference to a mutable object? Not a "constant" in my mind, certainly, but some people think it is. And nowadays you also see all caps for enum values - often, but not always. Which are usually immutable, but not always. And does it make a difference if you're talking about a constant member variable vs a local variable? Sun never made this stuff very clear.

Ultimately, knowing that something is a "constant", or not, usually does not fundamentally change my understanding of what code does, the way knowing it's a class or field or method would. Usually it's just one more bit of data about a thing, which we could encode in the name, if we want to get all Hungarian about our names. But it's rarely if ever the most important attribute of that thing. So I just don't see why it matters.

That said, I do usually follow the most common usage conventions that I see on these issues (inconsistent as they are). But this one just doesn't seem that important to me.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18127
    
    8

Mike Simmons wrote:And nowadays you also see all caps for enum values - often, but not always. Which are usually immutable, but not always.


Well, they did say we should stop using those "magic numbers" and start using enums instead, so it isn't surprising to see enum names in all-caps just like the old magic numbers used to be. But I haven't gone back to see if they updated the code standards to mention enums -- anybody know if they did?
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2969
    
    9
You're right that enums fill the "magic number" role, and to the extent that consistency with legacy C/C++ code is a design goal of Java, it makes sense to capitalize the value names. Sun and Oracle haven't updated the code conventions document since 1999, so there's no mention of enums there. Oracle appears to have dropped the old "Naming Conventions" section from the latest JLS, as well - and that never mentioned enums either. However all modern examples I can find discussing enums (in the APIs, Java Tutorial, JLS examples, and Effective Java) seem to use all caps for enum names. So that seems to be the de facto standard.

I seem to recall that back when enums came out, there were some published examples that did not follow that convention. But those seem to have been replaced, or at least outnumbered.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: grammar help: what is this structure?
 
Similar Threads
Learning Project 2
Just wanted to share my code SudokuSolver !
June Newsletter Puzzle
copying arrarys into a different class with methods
Multidimensional ArrayList