How should I declare main()
method in Java?
Like this:
public static void main(String[] args)
{
System.out.println(\"foo\");
}
>
Lets understand the difference via example and its Super easy
mymethod(String... str)
vs
mymethod(String []str)
Method getid take int type array.
So if we call the getId method we need to pass array.
To pass array we can create anonymous array or just simply first create an array and pass like i done this in below example.
class test
{
public void getid(int []i)
{
for(int value:i)
{
System.out.println(value);
}
}
public static void main(String []arg)
{
int []data = {1,2,3,4,5}
new test().getid(data);
}
}
Now below we Using triple dot -> mymethod(int... i)
now the method still need the array but the difference is now we can pass direct value to that method and "..." automatically convert it to the array
look example below
class test
{
public void getid(int ...i)
{
for(int value:i)
{
System.out.println(value);
}
}
public static void main(String []arg)
{
new test().getid(1,2,3,4);
}
}
Advantage of using "..." instead of " [ ] "
1) Its save memory :-
in example one using mymethod(int [ ] )
When we create an array in main method " Data[] "they create new object and get there space in memory
as well as when we create method and define there argument like :-
getid(int []) -> this will create another object in a memory so we have 2 object in a memory which is same to each other
2) You can pass nothing while using "... "
In example two you can pass nothing while calling "getid" method and they will work without giving any error which is very helpful to make program more stable for example
.
.
.
public static void main(String []arg)
{
new test().getid();
}
.
.
.
But if we call "getid" method and didn't pass any argument while using "[ ] " then it will show the error at compile time