I have this exercise:
public class Test2 {
public static void main (String [] args){
int index=1;
getArray()[index=2]++; //why???
}
public static int[] getArray() {
return null;
}
}
In my opinion, to call the static method getArray it is necessary to write:
getArray(); ... without the index!
I considered this code with a compiler error.
Can you explain me why getArray() [index =2]++; compiles without errors?
Let's go step by step:
the method is supposed to return an array of int (public static int[])
that array gets then accessed at index 2 (whateverArray [index=2])
finally, the result of that access (an int value) can be incremented (whateverArray[2]++)
and yes, a minor thing, you can assign a variable and use that as array index in the same statement, too
Thus this is all legal syntax. Of course, at runtime, you end up with a nullpointer exception.
The compiler could know that the method returns null, but standard javac does not care about such subtle details (for method results). And any decent IDE will tell you immediately that this code will break when executed.
Related
The following code:
public static void main(String[] args) {
int first = 1;
int second = 2;
sum(first,second);
System.out.println(sum);
}
public static int sum(int a, int b){
int sum = a+b;
return sum;
}}
will return error and I need to write
int x = sum(first,second);
System.out.println(sum);
and define that method as integer x and print x.
But for array,
public static ArrayList<String> removeLast(ArrayList<String> list) {
//code
return list;
}
public static void main(String[] args) {
//code
removeLast(persons);
System.out.println(persons);
}
will print the returned value of array without defining as another array as the was with the previous one.
I am sorry if the question has already been asked as I couldn't find it. And I am just learning Java.
Arrays are passed by (value of) reference, therefore, any change that happens to the array inside the method, will actually change the array passed in to it. On the other hand ints are passed by value. Change an int inside a method, and it won't change the int passed into the method.
For this reason, the return statement in your array method is completely unnecessary. Your code will still change the array, even if you omit the return statement.
But there's another misconception that needs to be pointed out: when you sum two ints, you are creating a new value in memory, which exists as long as the method is executed. When the sum method is done, the sum int doesn't exist anymore. To retain its value, you need to return it from within the method, and assign it to a variable where you call the code.
Because Java is pass by value, but the value of reference types (including arrays) is a reference to the Object (in this case, a List). You might use a variadic function and (in Java 8+) an IntStream to implement it like
public static int sum(int... arr) {
return IntStream.of(arr).sum();
}
Then you can call sum with as many (or few) int arguments as you like.
Will print the returned value of array without defining as another
array as the was with the previous one ?
Whatever #yeedle mentioned above is correct, but one point to add as below:
ArrayList class (actual type of persons object) has overridden the toString() method such that it
could print the array details when you invoke
System.out.println(persons);.
You need to know that for your objects (created for your custom
classes like Product, Employee, etc..), you need to override
toString() method (inherited from java.lang.Object) to print the
values like how you wanted, otherwise simply using
System.out.println(object); will print the hashcode of the
object (like #HA5431 etc..).
You can look here and here
So I was writing a Minecraft Forge mod, in eclipse, and I came around an eclipse warning that was very confusing. Though I have developed for a lot know, I do not know what the following text means.
The argument of type Block[][] should explicitly be cast to Object[][] for the invocation of the varargs method fooMethod(Object[]...) from type FooClass. It could alternatively be cast to Object[] for a varargs invocation
My Java Code:
fooMethod:
public static void registerBlock(Object[]...blocks){
for (Object[] b : blocks){
Block block = (Block) b[2];
Integer[] bb = {(int) b[0], (int) b[1]};
blocksID.put(bb, (Block) block); //Block ID
unlocalName.put(block.getUnlocalizedName(), bb);//Unlocal Name
localName.put(block.getLocalizedName(), bb); //Local Name
}
fooMethodWithWarning:
this.registerBlock(blocks);
If someone could very kindly dumb it down a little Itsy bit.
It's because what you're doing is ambiguous. It is unclear whether you're trying to do this:
// Calls the vararg method with multiple arguments
// (the arrays in blocks).
registerBlock((Object[][]) blocks);
or this:
// Calls the vararg method with a single argument (the blocks object)
registerBlock((Object[]) blocks);
Doing it the first way, when you iterate over the argument in the method each element will be an element from the 2d array. So each element will be a 1 dimensional array and there will be the same number of elements as their were in the 2d array.
Doing it the 2nd way, regardless of how many arrays were in the original array, when you iterate over the parameter in the method you will get one element and it will be the original 2d array.
To understand this, you (unfortunately) need to know how Java internally implements them.
The method signature, internally, becomes:
public static void registerBlock(Object[][] blocks)
(See JLS 15.12.4.2)
You can invoke a varargs method in two ways, either by passing all arguments as an array, or by passing them one-by-one as separate parameters. If you only provide one argument, the compiler needs to decide whether you are intending to pass only one argument as a variable argument list, or whether you are passing all your arguments as an array (with potentially many arguments).
The problem is exacerbated by the fact that an Object[] itself can is also an Object, so an Object[][] can be assigned to Object[] can be assigned to Object.
If you cast your array as Object[][] as the compiler suggests, it thinks that you are passing all varargs in one array (potentially many). If you cast it to Object[], it thinks you are passing a single vararg argument.
In this confusing case, I would advise not to use varargs - they are syntactic sugar anyway and in this case they provide more confusion than that they add convenience.
To to that, just declare your method as:
public static void registerBlock(Block[][] blocks)
From what you write in a comment on the answer above, this should fix your problem (since you are passing in a Block[][] argument to the method invocation)
... but ...
You may have a bigger problem - this will cause an exception at runtime because registerBlock is not expecting a two-dimensional array of Blocks (which you say you are passing in)
Instead, it expects the inner array to contain two Integers and then one Block.
That's not a good object-oriented style and it is the root cause of your problems.
You need to wrap these two integers and the Block into a class:
public class BlockRegistration {
private int x;
private int y ;
private Block block;
// [...]
public Block getBlock() { return block; }
public int getX() { return x; }
public int getY() { return y; }
}
and then your method becomes:
public static void registerBlock(BlockRegistration... blocks) {
for (BlockRegistration b : blocks) {
Block block = b.getBlock();
Integer[] bb = { b.x, b.y };
blocksID.put(bb, block); // Block ID
unlocalName.put(block.getUnlocalizedName(), bb);// Unlocal Name
localName.put(block.getLocalizedName(), bb); // Local Name
}
}
Check this line
for (Object[] b : blocks){
blocks should be 2 dimensional object array.
public class test
{
public static void main(String[] args)
{
int x = 5;
int y = 10;
multiply(x,y);
}
public static void multiply(int x, int y)
{
int z = x*y;
System.out.println(z);
}
}
I am new to programming and I am confused on a few things.
Why is it correct to use void? I thought void is used in order to specify that nothing will be returned but, the multiply method returns z.
Do all programs require that you have exactly "public static void main(String[] args)"? What exactly is the purpose of the main method and what do the parameters "String[] args" mean? Would the program work if the main method was removed?
Thank You!
First, the multiply method does not return anything; it prints the product, but does not return any value.
public static void multiply(int x, int y)
{
int z = x*y;
System.out.println(z); //may look like a return, but actually is a side-effect of the function.
} //there is no return inside this block
Secondly, public static void main provides an entry point into your program. Without it, you cannot run your program. Refer to the Java documentation for more information on the usage of public static void main.
The String[] args here means that it captures the command line arguments and stores it as an array of strings (refer to the same link posted above, in the same section). This array is called args inside your main method (or whatever else you call it. Oracle cites argv as an alternate name)
System.out.print tells the program to print something to the console, while return is the result of the method. For example, if you added print all over your method to debug (a common practice), you are printing things while the program runs, but this does not affect what the program returns, or the result of the program.
Imagine a math problem - every step of the way you are "print"ing your work out onto the paper, but the result - the "answer" - is what you ultimately return.
When a method does not return anything, you specify its return type as "void". Your multiply method is not returning anything. Its last line is a print statement, which simply prints the value of its arguments on the standard output. If the method ended with the line "return z", then you would not be able to compile the program with the "void" return type. You would need to change the method signature to public static int multiply(int x, int y).
All Java programs do require the public static void main(String[] args) if they are to be executable. It is the starting point of any runnable Java program. Here's what it means:
a. public - the main method is callable from any class. main should always be public because it is the method called by the operating system.
b. static - the main method should be static, which means the operating system need not form an object of the class it belongs to. It can call it without making an object.
c. void - the main method does not return anything (although it may throw an Exception which is caught by the operating system)
d. String[] args - when you run the program, you can pass arguments from the command line. For example, if your program is called Run, you can execute the command java Run 3 4. In that case, the arguments would be passed to the program Run in the form of an array of Strings. You would have "3" in args[0] and "4" in args[1].
That said, you could have a Java program without a main, which will not be runnable.
I hope that helps.
Why is it correct to use void? I thought void is used in order to specify that nothing will be returned but, the multiply method returns z.
No
multiply method does not return z. However, you are correct, void is in fact used to specify that nothing will be returned.
Do all programs require that you have exactly "public static void main(String[] args)"? What exactly is the purpose of the main method and what do the parameters "String[] args" mean? Would the program work if the main method was removed?
yes, all programs must have a main function that looks like public static void main(String[] args).
Like others said, the multiply method does NOT return anything. The other answers explained why that is.
However it would also be helpful to mention that when you use void that method can not return anything. In contrast, if you set your method to return anything (not to void) you are required to return that type of value.
For example:
public static void main(String[] args){
int a;
a = returnInt();
}//End Method
public static int returnInt(){
int z = 5;
return z;
}//End Method
The main method does not return anything, which is why we use void. The returnInt method returns an integer. The integer that the method returns is z. In the main method where a = returnInt(); that sets the value of a to the value returned from returnInt(), in this case, a would equal 5.
Tried to keep it simple, hope it makes sense.
public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.
static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
void means that the method has no return value. If the method returned an int you would write int instead of void.
The combination of all three of these is most commonly seen on the main method which most tutorials will include.
credits to Mark Bayres
The multiply() method in your example does not return the value of z to the calling method, rather it outputs the value of z (e.g., prints it to the screen).
As you said, the void type keyword means that the method will not return a value. Methods like this are intended to "just do something". In the case of main(), the method will not return a value, because there is no calling method to return it to -- that's where your program begins.
OK, technically, that last comment is not accurate; it actually is possible to have your main return a value to the operating system or process that launched the program, but it isn't always necessary to do so -- especially for simpler console-based programs like those you'll write when you're just getting started! :)
Void class is an uninstantiable class that hold a reference to the Class object representing the primitive Java type void.
and The Main method is the method in which execution to any java program begins.
A main method declaration looks like this
public static void main(String args[]){
}
The method is public because it be accessible to the JVM to begin execution of the program.
It is Static because it be available for execution without an object instance. you may know that you need an object instance to invoke any method. So you cannot begin execution of a class without its object if the main method was not static.
It returns only a void because, once the main method execution is over, the program terminates. So there can be no data that can be returned by the Main method
The last parameter is String args[]. This is used to signify that the user may opt to enter parameters to the java program at command line. We can use both String[] args or String args[]. The Java compiler would accept both forms.
Why is it correct to use void? I thought void is used in order to
specify that nothing will be returned but, the multiply method returns
z.
Your multiply method is correct to have void since it is returning nothing, it is just printing to the console.
Returning something means gives out a result to the programm for further computation.
For example your methode with return of the result would look like this:
public static int multiply(int x, int y)
{
int z = x*y; //multipling x and y
System.out.println(z); //printing the restult to the console
return z; //returning the result to the programm
}
this "new" method can be used like this for example:
public static void main(String[] args)
{
int x = 5;
int y = 10;
int result = multiply(x,y); //storing the returnen value of multiply in result
int a = result + 2; //adding 2 to the result and storing it in a
System.out.println(a); //printing a to the console
}
Output:
50
52
Do all programs require that you have exactly "public static void
main(String[] args)"? What exactly is the purpose of the main method
and what do the parameters "String[] args" mean? Would the program
work if the main method was removed?
This mehtod seves a the etry point for your programm. This meas the first thing that is executet of your programm is this mehtod, removing it would make the programm unrunneable.
String[] args stands for the commandline arguments you can give to you programm befor starting over the OS (OS = Windows for example)
The exact purpose of all of the words is very well explained in the other answers here.
So i can pass nulls into functions in java. I can also overload functions in java. But consider the following
public static void main(String ... args){
doStuff(null);
}
public static void doStuff(String s){
solveWorldHunger();
}
public static void doStuff(Integer i){
nukeCanada();
}
public static void nukeCanada(){
System.out.println("NO!");
}
public static void solveWorldHunger(){
System.out.println("YAY!");
}
The previous program will always print out YAY no matter what the order of the sorce code...
Can anyone shed some light onto why the jvm consitently decides to run the solveWorldHunger function over the nukeCanada function`?
It's quite clear to the compiler that you can't store null in a primitive int. So, it decides to go with the method which has String as argument.
However, when you change your 2nd method to take Integer as argument, then you will get compiler error. Because both of them are eligible to be invoked with null argument. So, there will be ambiguity.
So, try changing your 2nd method: -
public static void doStuff(String s){
solveWorldHunger();
}
public static void doStuff(Integer i){ // Integer instead of `int`
nukeCanada();
}
And invoke it on null. You will see the compiler error.
So, in that case, you can invoke the appropriate method using typecasting like this: -
doStuff((Integer)null); // Calls Integer version
doStuff((String)null); // Calls String version
Also, note that, if you have your 2nd method take a parameter that is a super type of String, like Object, then there would be no ambiguity, because compiler will now choose the most specific one, i.e., String argument.
So, ambiguity only occurs, when you have two methods with types that are not in the same inheritance hierarchy.
Only your doStuff(String) method can take a NULL argument... the primitive int can never be null. If you had a second method overload that passed an object, you would no longer be able to pass null as a parameter for that method.
I'm doing a task for a course in Java programming and I'm not sure how the following thing is working? The method below takes the value from an array and a integer. The integer should be added to the array and then be used outside the method in other methods and so on, but how could this work when the method has no return for the new content of the array? There is a void in the method? Have I missed something? Preciate some help? Is there something about pointers?
public static void makeTransaction(int[] trans, int amount);
Arrays in Java are objects. If you modify the trans array inside the method, the changes will be reflected outside of it1. Eg:
public static void modify(int[] arr)
{
arr[0] = 10;
}
public static void main(...)
{
int x = {1, 2, 3};
System.out.println(x[0]); // prints 1
modify(x);
System.out.println(x[0]); // now it prints 10
}
Note that native arrays can't be dynamically resized in Java. You will have to use something like ArrayList if you need to do that. Alternatively you can change the return type to int[] and return a new array with the new element "appended" to the old array:
public static int[] makeTransaction(int[] trans, int amount)
{
int[] new_trans = Arrays.copyOf(trans, trans.length + 1);
new_trans[trans.length] = amount;
return new_trans;
}
1 It is also worth noting that as objects, array references are passed by value, so the following code has no effect whatsoever outside of the method:
public void no_change(int[] arr)
{
arr = new int[arr.length];
}
You can't add anything to an array. Java arrays have a fixed length. So indeed, what you want to do is impossible. You might make the method return an int[] array, but it would be a whole new array, containing all the elements of the initial one + the amount passed as argument.
If you want to add something to an array-like structure, use an ArrayList<Integer>.
Do you have to keep the method signature as is?
Also, can you be a bit more specific. When you say "the integer should be added to the array", are you referring to the amount argument? If so, then how is that amount added? Do we place it somewhere in the array or is it placed at the end, thus extending the array's length?
As far as pointers go, Java's pointers are implicit, so if you don't have a strong enough knowledge of the language, then it might not be so clear to you. Anyways, I believe that Java methods usually will pass objects by reference, and primitives by value. But, even that isn't entirely true. If you were to assign your object argument to new object, when the method terminates, the variable that you passed to the method is the same after the method executed as it was before. But, if you were to change the argument's member attributes, then when the method terminated those attributes values will be the same as they were inside of the method.
Anyways, back to your question, I believe that will work because an array is an object. So, if you were to do the following:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
}
// static int i;
/**
* #param args
*/
public static void main(String[] args)
{
int[] trans = {0,1,3};
makeTransaction(trans, 10);
for(int i = 0; i<trans.length; i++)
{
System.out.println(trans[i]);
}
}
The output of the array will be:
10
1
3
But, watch this. What if I decided to implement makeTransaction like so:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
trans = new int[3];
}
What do you think that the output will be? Will it be set to all zero's or will be the same as it was before? The answer is that the output will be the same as it was before. This ties in to what I was saying earlier.
I might've assigned that pointer to a new object in memory, but your copy of the pointer inside of the main method remains the same. It still points to the same place in memory as it did before. When the makeTransaction method terminates, the new int[3] object that I created inside of it is available for garbage collection. The original array remains intact. So, when people say that Java passes objects by reference, it's really more like passing objects' references by value.