Click here to Skip to main content
15,909,445 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why is default type for number in Java int? As in this example:

class TestClass {
    public static void main(String args[] ) throws Exception {
        A a = new A();
        a.test(5);
    }
}
class A{
    void test(short a){
        System.out.println("Short");
    }
    void test(int a){
        System.out.println("Integer");
    }
    void test(byte a){
        System.out.println("Byte");
    }
}
It prints Integer.. My question is "Why is default type for a number int in Java"?

What I have tried:

Default type for numerical value
Posted
Updated 20-Mar-18 23:52pm
v2

You are calling A.test() passing the integer i. That is not a default type but defined by your code:
Java
int i = sc.nextInt();


[EDIT]
Quote:
Sir I modified the code to pass 5 instead of int i.. I am getting Integer
5 is a numerical integer literal.
Yes, when there is no type hint in the literal, it is an int.
If it has an 'L' postfix, it is a long:
a.test(5L);

If the literal contains a period or an exponent, it is a double.
If it has an 'F' postfix, it is a float.

If you want to treat it as different type you can also use casting:
a.test((short)5);
[/EDIT]
 
Share this answer
 
v2
Comments
Akshit Gupta 21-Mar-18 5:52am    
Sir I modified the code to pass 5 instead of int i.. I am getting Integer
Jochen Arndt 21-Mar-18 6:04am    
See my updates answer.
However, editing a question by removing portions that are referenced by solutions is not good style. Others reading the question and answers later might not get that. It is better to let the initial code stay (e.g. by commenting) it and indicate newly added lines like I have done in my updated answer.
Um.
Here is a clue:
Java
int i = sc.nextInt();
...
a.test(i);
You specifically declare i as an integer, so pretty understandably, it treats it as an integer!
 
Share this answer
 
Comments
Akshit Gupta 21-Mar-18 5:52am    
Sir I modified the code to pass 5 instead of int i.. I am getting Integer
OriginalGriff 21-Mar-18 6:13am    
"int i = ..."
Declares "i" as an integer. Anything you put into an integer variable will be ... an integer!
Your code doesn't prove that.
You are passing an int to test overloads.
As matter of fact, Java is strongly typed: variables have not a default type, they do have their assigned type.
 
Share this answer
 
Comments
Akshit Gupta 21-Mar-18 5:52am    
Sir I modified the code to pass 5 instead of int i.. I am getting Integer
CPallini 21-Mar-18 8:38am    
5 is a literal.
See
https://en.wikibooks.org/wiki/Java_Programming/Literals

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900