Himanshu Saxena
Himanshu Saxena

Reputation: 5

multiple constructors in java

class Objectsmultiplecnstrctrs {

    public static void main(String args[]){

        ObjectsForMultipleConstructors engg2=new ObjectsForMultipleConstructors(1);
        ObjectsForMultipleConstructors engg3=new ObjectsForMultipleConstructors(1,2);
        ObjectsForMultipleConstructors engg=new ObjectsForMultipleConstructors(1,2,3);

    }
}

// secondary class


public class ObjectsForMultipleConstructors {
    private int hour;
    private int minute;
    private int second;


    public ObjectsForMultipleConstructors(int h){
        this.hour=h;
        System.out.printf("give one ",+hour);

    }

    public ObjectsForMultipleConstructors(int h,int m){
        System.out.printf("goddamn ",+m);
    }

    public ObjectsForMultipleConstructors(int h,int m,int s){
        System.out.println("guess");

    }
}

OUTPUT is give one goddamn guess

Now the thing is i have declared int hour =h and value of h I assigned in the arguments in the main class,so im expecting the value of h which i defined to be displayed next to the text (System.out.printf("goddamn ",+m);) ,,but its doing what i want it to do ,where im missing

Upvotes: 1

Views: 187

Answers (4)

masay
masay

Reputation: 933

Why you use comma System.out.printf("give one ",+hour); ?

it must be System.out.printf("give one " + hour);

the description of printf usage is :

A convenience method to write a formatted string to this output stream using the specified format string and arguments. An invocation of this method of the form out.printf(format, args) behaves in exactly the same way as the invocation out.format(format, args) Parameters: format A format string as described in Format string syntax args Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification. The behaviour on a null argument depends on the conversion.

Upvotes: 3

Chandra Sekhar
Chandra Sekhar

Reputation: 19492

I think its because you have not used %d access specifier in the method printf

Upvotes: 0

rsp
rsp

Reputation: 23373

In order to format and print arguments to printf() you need to specify them in the pattern string, like:

System.out.printf("give one %d ", hour);

Upvotes: 1

Chetter Hummin
Chetter Hummin

Reputation: 6817

You need to have a format specifier as well in a printf statement

System.out.printf("give one %d ",hour);

Upvotes: 0

Related Questions