Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2006

Tip: Looking for answers? Try searching our database.

alias

Thread view: 
NickName - 18 Dec 2006 20:57 GMT
Hi,

I may be jumping guns here.  I mean I'm totally new to java and yet, I
feel the need to do something like this for typing much less,

o = System.out.println; // problem, what data type for var of o here?
undefined.
or
alias o = System.out.println; // alias is supposed to be a special
command or the sort?

then, I do something like this

for (int i=0; i < 5; i++) {
switch(i)
case 0:
case 2:
case 4:
    o(i + " is an even number"); // instead of System.out.println(i +
" is an even number");
    break;
case 1:
case 3:
case 5:
    o(i + " is an odd number"); // instead of System.out.println(i + "
is an odd number");
    break;
default:
    o(i + " is neither an odd nor even number");
    // instead of System.out.println(i + " is neither an odd nor even
number");
}

Doable?  How?  TIA.
Flo 'Irian' Schaetz - 18 Dec 2006 21:16 GMT
And thus, NickName spoke...

> I may be jumping guns here.  I mean I'm totally new to java and yet, I
> feel the need to do something like this for typing much less,

If you want to make your code unreadable, there are more easy ways to go...

> o = System.out.println; // problem, what data type for var of o here?
> undefined.
> or
> alias o = System.out.println; // alias is supposed to be a special
> command or the sort?

Doesn't exist - afaik. You could, of course, simply write...

public void o(String message) {
    System.out.println(message);
}

> then, I do something like this
>
> for (int i=0; i < 5; i++) {
>  switch(i)

Strange way to ask for...

i % 2 == 0

or

i & 1 == 0

Flo
NickName - 18 Dec 2006 22:05 GMT
> And thus, NickName spoke...
>
[quoted text clipped - 14 lines]
>     System.out.println(message);
> }

Thank you.  That's exactly what I'm looking for.  And with a little
twist, I changed it to

// alias, creating short hand for some commonly used command, DL
   public static void o(String msg) {
       System.out.println(msg);
   }

// added static because the caller uses static

Now, since we are at it and talking about readibility (pls note, I add
comments for short hands), a new one regarding a file's date time
stamp, the method of lastModified() seem to be the aggregation of
million seconds something as in

File myfile = new File(thisFile.txt);
long fileDate = myfile.lastModified();

What method to display date/time like mm/dd/yyyy or mm--dd--yyyy?
Sorry I did not go the trouble of digging it via language reference doc

TIA.

>[...]

> Flo
Hendrik Maryns - 19 Dec 2006 08:41 GMT
NickName schreef:
>> And thus, NickName spoke...
>>
[quoted text clipped - 22 lines]
>
> // added static because the caller uses static

An even easier way, still keeping things readable, is to use a proper
IDE, such as Eclipse, then just type syso + Ctrl + Space and you get the
whole System.out.println(|);, with the cursor at the |.

> Now, since we are at it and talking about readibility (pls note, I add
> comments for short hands), a new one regarding a file's date time
[quoted text clipped - 6 lines]
> What method to display date/time like mm/dd/yyyy or mm--dd--yyyy?
> Sorry I did not go the trouble of digging it via language reference doc

Have a look at Formatter:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html

There are also convenience methods in the outputstreams:
System.out.format(...)

H.
Signature

Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

NickName - 19 Dec 2006 20:03 GMT
>> [ ... ]
> >
[quoted text clipped - 15 lines]
> Ask smart questions, get good answers:
> http://www.catb.org/~esr/faqs/smart-questions.html

Thanks, got it.
Christopher Benson-Manica - 18 Dec 2006 22:10 GMT
> I may be jumping guns here.  I mean I'm totally new to java and yet, I
> feel the need to do something like this for typing much less,

> o = System.out.println; // problem, what data type for var of o here?

In other languages, o might be a function pointer, but in Java you're
out of luck.  The best you could do, saving yourself a little bit of
typing, would be something like

final PrintStream o = System.out;
o.println( "Hello, world!" );

although it really isn't worth the effort.  The alternative, using
reflection to get the println Method from System.out, will save you
neither typing nor brain CPU cycles.

> alias o = System.out.println; // alias is supposed to be a special
> command or the sort?

You might be thinking of shells and shell scripts; no such thing
exists in Java.

Signature

C. Benson Manica           | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com      | don't, I need to know.  Flames welcome.

John Ersatznom - 18 Dec 2006 22:32 GMT
>>I may be jumping guns here.  I mean I'm totally new to java and yet, I
>>feel the need to do something like this for typing much less,
[quoted text clipped - 11 lines]
> reflection to get the println Method from System.out, will save you
> neither typing nor brain CPU cycles.

Something similar does sometimes come up where you want to "wrap"
something like System.out.println. For example, you want to log certain
events, but the exact nature of the logging should be irrelevant to
whatever does the logging and should be changeable in a single place.
Then you do this:

public interface Logger {
    public void log (String message);
}

//Somewhere else
public class StdoutLogger implements Logger {
    public void log (String message) {
        System.out.println(message);
    }
}

//Somewhere else again
public static void main (String[] args) {
    Logger logger = new StdoutLogger();
    ...
    someobject.doSomething(logger, other_args);
    ...
}

//Somewhere else again
public void doSomething (Logger logger, other_args) {
    ...
    logger.log("Foo");
     ...
    catch (IOException e) {
        logger.log("Oops! I/O error");
        logger.log(e.toString());
        <some sort of recovery>
    }
    ...
}

Later on you might want to use some other Logger. You can make an
AggregatingLogger: (assumes Tiger)

public class AggregatingLogger implements Logger {
    private List<Logger> members;
    public AggregatingLogger () {
        members = new LinkedList<Logger>();
    }
    public void add (Logger logger) {
        members.add(logger);
    }
    public void log (String message) {
        for (Logger logger : members) {
            logger.log(message);
        }
    }
}

Just be careful not to add an aggregating logger to itself, OK? :)
NickName - 19 Dec 2006 19:46 GMT
> >>I may be jumping guns here.  I mean I'm totally new to java and yet, I
> >>feel the need to do something like this for typing much less,
[quoted text clipped - 69 lines]
>
> Just be careful not to add an aggregating logger to itself, OK? :)

Interesting, thanks.
Daniel Pitts - 18 Dec 2006 22:34 GMT
> Hi,
>
[quoted text clipped - 30 lines]
>
> Doable?  How?  TIA.

import static java.lang.System.*;
public class OddsAndEvens {
  public static final int MAX_COUNT = 5;
  public static boolean isEven(int number) {
     return (number & 1) == 0;
  }
  public static void main(String[] args) {
     for (int i = 0; i < MAX_COUNT; ++i) {
       out.println(i + " is an " + (isEven(i) ? "even" : "odd") + "
number");
     }
  }
}
Probably the shortest way to write this and still have it readable.

the "import static.java.lang.System.*" line tells the compiler to
borrow all of the static declarations in the java.lang.System class
(including the "out" object).

It is always a good idea to find meaningful names for your classes, and
for any constant (other than "obvious" values, such as 1, or 0.)

It's also not a bad idea to break out short methods (such as the
isEven) that describe the intent of even the simplest piece of "logic".

Now, having said all that, System.out.println is common enough that if
you need to use it a lot, there isn't much wrong with copy-paste.
Also, if you are using a good IDE (and you should try to), you will
have a lot of auto-complete tools.  For example, in IntelliJ IDEA, I
would type "sout" press *ctrl-J* and press *enter*, and I would get
System.out.println(""), with my cursor between the quotes.

There are a lot of other typing helpers within all sorts of IDE's.

In short, don't worry about typing too much. Usually the problem is
with people typing too little, and making the code unreadble, and
therefore impossible to maintain.
NickName - 19 Dec 2006 20:02 GMT
> OP [...]

> import static java.lang.System.*;
> public class OddsAndEvens {
[quoted text clipped - 10 lines]
> }
> Probably the shortest way to write this and still have it readable.

Very nice and thanks for introducing the System package here.  More
questions,
For the LINE of
public static final int MAX_COUNT = 5;
why not simply int MAX_COUNT = 5;
? // since it's it's already at the top level of the OddsAndEvens
class.

Please elaborate on the "(number & 1) == 0", though the & symbol is
supposed to mean something like Evaluation AND (binary).  TIA.

> the "import static.java.lang.System.*" line tells the compiler to
> borrow all of the static declarations in the java.lang.System class
[quoted text clipped - 18 lines]
> with people typing too little, and making the code unreadble, and
> therefore impossible to maintain.
Daniel Pitts - 20 Dec 2006 00:25 GMT
> > OP [...]
>
[quoted text clipped - 20 lines]
> ? // since it's it's already at the top level of the OddsAndEvens
> class.

int MAX_COUNT = 5; woudl create a new integer for every object create
in OddsAndEvens.  In this particular case, that doesn't matter much,
but if you have a constant value that is the same accross 10000
objects, it can start to add up.

the "static" keyword tells the compiler that the memory and value is
associated with the class, not individual instances of the class.  The
"final" keyword tells the compiler to not let anyone accidently change
the value of this constant. It also allows the compiler to optimize.

> Please elaborate on the "(number & 1) == 0", though the & symbol is
> supposed to mean something like Evaluation AND (binary).  TIA.

In binary, if a number is a multiple of two, then its lowest
signifigant bit is 0, otherwise the bit is one.
We can use that knowledge to help us determine the "evenness" of a
number.  Since an even number is a number which contains two as a
factor, we can test the lowest bit to tell us where a number is odd or
even.
1 is the bitmask for the lowest bit.  n & 1 will return the value of
the lowest bit.
for example:
n | BIN  |n&1|
0 | 0000 | 0 | even
1 | 0001 | 1 | odd
2 | 0010 | 0 | even
3 | 0011 | 1 | odd
4 | 0100 | 0 | even

Hope this helps.
- Daniel.
NickName - 20 Dec 2006 17:20 GMT
> > > OP [...]
> > > }
[quoted text clipped - 38 lines]
> Hope this helps.
> - Daniel.

Your explanation is perfect.  Thank you.
Ian Wilson - 19 Dec 2006 10:48 GMT
<wants to write o(text) instead of System.out.println(text)>

> for (int i=0; i < 5; i++) {
>  switch(i)
[quoted text clipped - 11 lines]
>      o(i + " is neither an odd nor even number");
> }

1) Separate the message from the IO function.

String m;
for (int i=0; i < 5; i++) {
 switch(i) {
 case 0:
 case 2:
 case 4: m = " is an even number"; break;
 case 1:
 case 3:
 case 5: m = " is an odd number";  break;
 default: m = " is neither an odd nor even number";
 }
 System.out.println(i+m)
}

2) Use a less clumsy test and fix the out-by-one error.

System.out.println("whatever you want to say about 0");
for (int i=1; i < 6; i++) {
  if (i%2 == 0) {
     System.out.println(i+" is even");
  } else {
     System.out.println(i+" is odd");
  }
}
NickName - 19 Dec 2006 20:11 GMT
[ ...]

> 1) Separate the message from the IO function.
>
[quoted text clipped - 11 lines]
>   System.out.println(i+m)
> }

Beautiful and glad to learn about the "String m" usage, thanks.

> 2) Use a less clumsy test and fix the out-by-one error.
>
[quoted text clipped - 6 lines]
>    }
> }

Ok, so, the i%2 == 0 is a formula to see if i is divisable by 2?
Similar ones?  TIA.
Ian Wilson - 20 Dec 2006 10:19 GMT
>> 2) Use a less clumsy test and fix the out-by-one error.
>>
>> System.out.println("whatever you want to say about 0");
>> for (int i=1; i < 6; i++) {

Most people[1] regard 0 as even. If you are one of them, you could
replace the above two lines with:
    for (int i=0; i < 6; i++) {

>>    if (i%2 == 0) {
>>       System.out.println(i+" is even");
[quoted text clipped - 4 lines]
>
> Ok, so, the i%2 == 0 is a formula to see if i is divisable by 2?

Yes.

The value of `a%b` is the remainder after integer division of a by b. I
recall Patricia Shanahan saying that the Java remainder operator (`%`)
is almost the same as the usual modulo operator but there is some subtle
distinction which I forget. (P.S. my recollection may be inaccurate, it
often is :-)

http://en.wikipedia.org/wiki/Modulo_operation

> Similar ones?

I'm too new to Java to have a list of "interesting" operators handy :-)
I find O'Reilly's "Learning Java" helpful.

Just reading this newsgroup regularly is an excellent way of discovering
better ways to do things in Java.

[1] Roulette table operators don't.
Patricia Shanahan - 20 Dec 2006 13:55 GMT
...
> The value of `a%b` is the remainder after integer division of a by b. I
> recall Patricia Shanahan saying that the Java remainder operator (`%`)
> is almost the same as the usual modulo operator but there is some subtle
> distinction which I forget. (P.S. my recollection may be inaccurate, it
> often is :-)
...

The difference is in the extension to negative numbers.

One of the examples in the JLS is

(-5)%3 produces -2

This is correct for remainder, because it maintains consistency with
division. I would expect (N mod 3) to be represented by an integer in
the range 0 through 2 for any integer N.

Patricia
NickName - 20 Dec 2006 17:24 GMT
> ...
> > The value of `a%b` is the remainder after integer division of a by b. I
[quoted text clipped - 15 lines]
>
> Patricia

Thank you.
NickName - 20 Dec 2006 17:21 GMT
> >> 2) Use a less clumsy test and fix the out-by-one error.
> >>
[quoted text clipped - 33 lines]
>
> [1] Roulette table operators don't.

Great.  Thank you.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.