-7

In C i used to use #define p printf

to help me code easily rather than typing printf every time

let me give an example to understand better

p("hello world");

it does the job of

printf("hello world");

There is a way in java to do this I went through it long back Its not a duplicate question as they answered there is no way Iam sure of there is a way to do this using ENUM

How can I implement this in java

SmashCode
  • 741
  • 1
  • 8
  • 14
  • 5
    Don't. `printf` is much verbose, or, for that matter, `System.out.print.` – Sourav Ghosh Feb 16 '16 at 13:18
  • 3
    See http://stackoverflow.com/questions/6525059/can-i-have-macros-in-java-source-files – Adi Levin Feb 16 '16 at 13:20
  • 1
    Your use of the preprocessor is effectively redefining the language. While it *might* be OK for you, your maintenance programmer will have a hard time following code. Remember the compiler can understand any (valid) program in less then a second no matter how badly it's written. The real skill in programming is writing your program in a way that a maintenance programmer can understand it, particularly as that might be you in 6 months time – Stormcloud Feb 16 '16 at 16:23

4 Answers4

8

You need to use a method in a helper class.

e.g.

enum Helper {;

    static void p(String fmt, String... args) { System.out.printf(fmt, args); }
    static void p(Number n) { System.out.print(n); }
}

so you can call

import static mypackage.Helper.p;

p("hello world");

There is no scanf though you can use a Scanner to do something similar.

Most of the useful things you can do with macros, you can do with simple Java syntax. In term the JIT will optimise the code at runtime to get the same performance benefits.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
5

Simple answer: you don't. Java doesn't have that kind of text substitution.

Actually, you shouldn't be making those types of substitutions in C, either. A #define like that is a recipe for trouble.

dbush
  • 205,898
  • 23
  • 218
  • 273
3

For the love of god. Don't do this. You'll have a lot of unexpected behavior in your code.

However you could learn some shortcuts like typing "syso" + Return (in Eclipse) or "sout" +Return (in Netbeans). Does not shorten your code, but it's faster.

0

There is no similar macro available in Java. You could write your own methods that delegate to System.out.ṕrintln and the likes, but it would probably be unnecessary work for very little gains.

Think of it this way, typing out those words will make your fingers nimbler.

Kayaman
  • 72,141
  • 5
  • 83
  • 121