this is may be the dumbest question ever asked in stack overflow but this is bothering me lot...
public class shorte
{
public static void main(String []args)
{
short e = 56; // no need for explicit cast
System.out.println(e);
start(56); // why does int literal here needs explicit cast ...
}
static void start(short e)
{
System.out.println(e);
}
}
while creating normal short variable from an int literal in function didn't ask for any explicit cast , but why does passing int literal to short variable (parameter passing) needs an explicit cast......??
and again
i now it is not recommended to ask two unrelated questions in single post but this too trivial to ask in yet another post..
**scope of 'for' counter variable **
public class forloop
{
public static void main(String []args)
{
int a =12;
for(int a =12;a<14;++a) // no showdowing of variable ,give compile-time error
{
System.out.println(a);
}
}
}
so i tried it with normal blocks
a=12
{
a=13; even this doesn't compile
}
does that mean, blocks don't have their own scope...
A short
literal can be automatically constructed from an int
literal in Java. This is the case of
short e=50;
But calling a function and passing parameters is different. Because of the possibility of overloading, the function call should exactly match the function prototype. Imagine an overloaded function with an int
parameter for one version and a short
parameter for another.
As for the second question, in most languages, you usually cannot hide an identifier declared in an outer scope by the same identifier in an inner scope. I have two exceptions in my head:
1- A global variable can be hidden by a local variable (in C++ for example, as Java does not have global variables).
2- A class data member can be hidden by a local variable.
In both cases, the language offers a resolution operator (:: for 1- and this
for 2- ).
Just from the technical point of view (not speculating about the reasons ;-)): It's in the specification
a)
5.2 Assignment Conversion
[...]
In addition, if the expression is a constant expression ( §15.28 ) of type byte , short , char , or int :
• A narrowing primitive conversion may be used if the type of the variable is byte , short , or char , and the value of the constant expression is representable in the type of the variable.
b)
6.4 Shadowing and Obscuring
[...]
It is a compile-time error if the name of a local variable v is redeclared as a local variable of the directly enclosing method, constructor, or initializer block within the scope of v ; or as an exception parameter of a catch clause in a try statement of the directly enclosing method, constructor or initializer block within the scope of v ; or as a resource in a try -with-resources statement of the directly enclosing method, constructor or initializer block within the scope of v .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With