Can I have macros in Java source files

Viewed 80377

In my program I'm reading integers form console many times. Every time, I need to type this line.

new Scanner(System.in).nextInt(); 

I'm used to C/C++ and I'm wondering if I can define something like

#define READINT Scanner(System.in).nextInt(); 

and then, in every place in my java program I can read form console as

int a = new READINT;

But I read form books Java does not support macros.

Someone please explain me why is it so, and can I do this in any other way.

9 Answers

Macros are text-level pre-processing tools that can be badly abused if not carefully designed. Example:

#define MULTIPLY( a, b ) ( a * b )

MULTIPLE(1+2,3+4) will have the result of (1+2*3+4)

Another example

#define SQUARE( a ) ((a) * (a))

int x = 5;
SQUARE(x++);

will increment x twice. ((x++) * (x++))

I think that Java language designers did not buy it for these reasons, because it is meant to be simple.

Related