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.

8
  • 9
    search in the javadocs for: String.format() also check this: System.out.format() Commented Jul 27, 2015 at 5:10
  • You can also create a custom made method for that... Commented Jul 27, 2015 at 5:11
  • 6
    You can use System.out.printf Commented Jul 27, 2015 at 5:11
  • System.out.printf? Commented Jul 27, 2015 at 5:11
  • see format method doc docs.oracle.com/javase/tutorial/java/data/numberformat.html Commented Jul 27, 2015 at 5:11

6 Answers 6

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

We can use

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

or

System.out.print("No of items "+2);

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.