0

I want to create my own custom function in Java which work exactly same like the printf in C.

Like

printf("My name is %c, my age is %d", "B", 23);

Which will print My name is B, my age is 23

or

 printf("No of items %d", 2);

which will print No of items 2.

Pshemo
  • 122,468
  • 25
  • 185
  • 269

6 Answers6

3

There are multiple such methods in Java.

String.format(String, Object...)

Returns a formatted string using the specified format string and arguments.

and

System.out can use PrintStream.printf(String, Object...)

and

The Formatter syntax applies to both of the above

For example,

String fmt = "i = %d%n";
int iv = 101;
System.out.print(String.format(fmt, iv));
System.out.printf(fmt, iv);
Formatter out = new Formatter(System.out);
out.format(fmt, iv);
out.flush();

Outputs

i = 101
i = 101
i = 101

tl;dr from your Question

Use "%s" for a String and System.out.printf like

System.out.printf("My name is %s,my age is %d%n", "B", 23);
System.out.printf("No of items %d%n", 2);

Output is (as requested)

My name is B,my age is 23
No of items 2
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You can go for System.out.printf(). it acts same like as printf function in c.

Vishnuvardhan
  • 5,081
  • 1
  • 17
  • 33
0

you can code this way.. please share the feedback, as I tried some happy cases only.

public class Test1 {

 public static void main(String[] args) {
    printf("My name is %s ,my age is %d","B",23);
 }

 public static void printf(final String in, final Object... args) {
    System.out.println(String.format(in, args));
 }
}

Output : My name is B ,my age is 23

manoj
  • 3,391
  • 2
  • 20
  • 30
0

We can use

System.out.print("My name is "+"B"+",my age is " +23);

or

System.out.print("No of items "+2);
Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59
0
    String name = "B";
    int age = 23;
    System.out.printf("My name is %s, My age is %d", name,age);
    System.out.println();
    System.out.printf("No of items %d", 2);

Output:

My name is B, My age is 23
No of items 2
Coding Bad
  • 252
  • 1
  • 4
  • 12
0

create function like function(String line,Object ...args)