user5049335
user5049335

Reputation:

Function in Java similar to printf from C

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.

Upvotes: 0

Views: 1979

Answers (6)

user5146771
user5146771

Reputation:

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

Upvotes: 0

Coding Bad
Coding Bad

Reputation: 262

    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

Upvotes: 0

manoj
manoj

Reputation: 3761

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

Upvotes: 0

Mohit Kanwar
Mohit Kanwar

Reputation: 3050

We can use

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

or

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

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

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

Upvotes: 4

Vishnuvardhan
Vishnuvardhan

Reputation: 5107

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

Upvotes: 1

Related Questions