I was around Wikipedia reading about a programming language called 'D', it is the first time I read about it.
It was curious to me that the syntax looks very similar to Java.
But most interesting was when I saw their main method uses char[][].
I opened up Eclipse and I tried this:
public static void main(char [][] args){
}
I was surprised when I saw it compiled with no syntax errors, but I did not understand why.
Can someone explain to me why this call to the main method can compile in Java?
As what you have written is valid Java syntax (static void method with name main and as argument a two dimensional char array) it will compile. The problem however is, that this main method will not work as entry point to a Java program, as this has to have the signature:public static void main(String[] args).
dcn, is correct it is a valid method named main. But can't be used to start a Java app.
To expand further, there is some flexibility in the signature:
You can use any variable name, not just args:
public static void main(String[] whateverNameYouWant) {
}
The variable must be an array of Strings, but you can declare that in any valid Java syntax, like so:
public static void main(String args[]) {
}
As, Michael Krussel, points out, you can also use varargs:
public static void main(String... args) {
}
Related
This question already has answers here:
What is a class literal in Java?
(10 answers)
Closed 5 years ago.
To illustrate the contrast. Look at the following java snippet:
public class Janerio {
public static void main(String[] args) {
new Janerio().enemy();
}
public static void enemy() {
System.out.println("Launch an attack");
}
}
The above code works very fine and seems to be yes as answer to this question as the output turns to be as follows.
Launch an attack
But at the very next moment when I run the following snippet
public class Janerio {
public static void main(String[] args) {
System.out.println(new Janerio().class);
}
}
I get the compile time error
/Janerio.java:3: error: <identifier> expected
System.out.println(new Janerio().class);}
^
/Janerio.java:3: error: ';' expected
System.out.println(new Janerio().class);}
^
2 errors
I don't see why such a situation comes up because in the previous snippet I was able to access the static "enemy" function with the help of an instance of the class but here it's proving false. I mean why can't I access the ".class" static method with the help of the instance of the class. Am I wrong to consider ".class" to be a static function or member of the class Janerio and is it wrong to be analogous to the static features of both the snippets?
But as soon as I call the ".class" with the class name things appear to be that ".class" is static in nature but it deviates to the be static on calling ".class" with an instance of the class.
public class Janerio {
public static void main(String[] args) {
System.out.println(Janerio.class);
}
}
Output we get:
class Janerio
.class references the Class object that represents the given class. it is used when there isn't an instance variable of the class. Hence it doesn't apply to your usage
Read more here:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2
With .class you do not select a field (besides class is a keyword).
It is a pseudo operation, usable with a class name, yielding a Class instance:
int.class, Integer.class, java.util.List.class
Am I wrong to consider ".class" to be a static function or member of the class Janerio?
Yes, it's not a variable and it's definitely not a method. You have to use the Object#getClass method when you want to get the class of an instance.
Yes, you can access these static members of classes that way, but the better practise is to use name of that class instead of the name of specific referece to object of that class. It makes your code clearer to understand and to read as static members of class do not belong to specific object but to whole class. For example:
class MyClass {
static int count = 0;
}
It is better to access this field that way:
MyClass.field = 128;
instead of changing that value using the name of specific reference, for example:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.field = 128;
Because it can be confusing when you realize that this way even obj2.field has assigned new value of 128. It might look a bit tricky, so again, I would suggest the first presented method of calling methods or changing values assigned to fields.
Alright, so I have a driver class and an arraylist (as you can probably guess).
My arraylist is full of strings and I'm accessing it through a getter that I've created in my other class.
It says that "The static method getMouseList() from the type Desktop should be accessed in a static way". How should I go about fixing this? Do you see any other errors?
Thanks to everyone who can help!
So here's my code:
Class:
static ArrayList <String> Strings;
public static void main(String[] args) {
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hi");
Strings.add("hello");
}
public static ArrayList<String> getStrings() {
return Strings;
}
Driver class:
Desktop test4 = new Desktop();
System.out.println(test4.getStrings());
Since it's static, it belongs to its class, not to a class instance. Thus, you need to access it using the class: Desktop.getStrings()
UPDATE
I'd need to see more of your code to exactly explain what's going on. So, I'll try to explain on what I imagine is your code. Please note that Java programs start from one main method. Depending on how you execute your program, one of them is going to be invoked, the others will not.
In any case, one way would be to create another static method in Desktop and move the initialization code from main to that method, such as:
public static void initializeStrings(){
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hi");
Strings.add("hello");
}
Then, make sure that you call that method, via Desktop.initializeStings(); before trying to access the Strings array (for example in the start of the actual main method of your program.
EDIT 2:
OK, so your main should now look something like this:
public static void main(String[] args) {
Desktop.initializeStrings();
Driver.doSomething();
}
and your Driver's method (inside Driver class):
public static void doSomething() {
//some code
//strings are initialized and will get printed
System.out.println(Desktop.getStrings());
}
That should give you a hint on how to move forward. On a side note, all this staticness is hindering the Object oriented nature of Java. I would suggest a tutorial in Java's object oriented programming model: https://docs.oracle.com/javase/tutorial/java/index.html
I was looking at another post here which was describing what seems to be my problem:
How to make a method which accepts any number of arguments of any type in Java?
However, when I attempted to do this method, when I compiled the program it gave me the error "int cannot be converted to java.util.Objects"
What am I doing wrong?
Code:
public static void clearArray (Objects... args)
{
System.out.println("Error, non character value");
}
How I called the function:
import java.util.Objects;
// Stuff...
clearArray(1);
// Other stuff...
Thank you for checking out my problem!
Look at the signature
public static void clearArray (Objects... args)
That method receivng Objects type and you are passing integer to it. Perhaps changing that to
public static void clearArray (Object... args)
Helps.
You want java.lang.Object, not java.util.Objects.
java.util.Objects is a class with utility methods, not a class you can actually extend and instantiate.
java.lang.Object on the other hand is the superclass of all objects in Java.
And even in a multi-param (varargs) method, the signature needs to be Object ..., not Objects ....
I don't understand why methods on arrays, in Java, have to be static. Static methods can only be used on static variables right? So this would mean arrays are static variables, variables shared by a class? But what class would this be?
Can someone help me understand this?
Edit: to be more specific, I am creating methods to act on arrays but if I just write "public int[] expandArr(int[]a, int v)" and I try to use this method in the main method, I get an error saying I can't make a static reference to a non-static method. When I write "public static int[] expandArr(int[]a, int v)" it works then.
I understand you cannot change the size of an array, the method I wrote makes a new array with increased size and copies the first one into it.
Thank you.
You say you tried to write this:
public int[] expandArr(int[]a, int v)
The thing is, you had to write it in some class, since you can't just have free-floating methods in your program. Therefore, it must operate on a instance of the class. For example:
public class MyProgram {
public int[] expandArr(int[]a, int v) { ... }
public static void main(String[] args) { ... }
}
expandArr requires an instance of MyProgram, since you didn't declare it to be static. And that has nothing to do with arrays. It would be the same if you wrote
public class MyProgram {
public String expandString(String s, int v) { ... }
public static void main(String[] args) {
String s = expandString(args[0], 1); // ILLEGAL
String s2 = args[0].expandString(1); // ILLEGAL
}
}
Although the first parameter of expandString is a String, this actually operates on a MyProgram, and you cannot use expandString without an instance of MyProgram to operate on. Making it static means that you can (the first use of expandString in my example would become legal.)
In general, you can't add methods to a class without modifying the source of that class. If you want to write a new method that does something with objects of a certain class C, and you can't modify class C (perhaps because it's in the Java library or someone else's library), then you'll need to put the method in some other class C2, and most of the time you will need to make the method static since it doesn't involve objects of class C2.
You can't call a non-static method from a static method unless you first instantiate the an object of the class.
e.g.
In class Whatever...
public boolean ok() {
return true;
}
public static void main(String[] args) {
Whatever w = new Whatever();
System.out.println(w.ok());
}
You cant call a non static method from a static context. A static method belongs to the class, non static or instance methods are copied to each instance of the class (they each have their own). If I have 10 instances of class A, and class A has a static method, which all of them share, then I try to invoke a non static method in class A from class A's static method, which instance of class A gets its method invoked? The behavior is undefined.
The question really has nothing to do with arrays.
This question is related: Can't call non static method
I think what you're referring to is the fact that you can't extend an array class and hence can't add a method to it:
// No way to do this
int[] array;
array.myMethod();
This means your only option is to make a static helper method somewhere:
// So you have to do this
int[] array;
Utils.myMethod(array);
class Utils {
static void myMethod(int[] array) {
...
}
}
An example of this is the Arrays class, which has lots of static methods for operating on arrays. Conceptually it would be clearer if these methods could be added to the array classes, but you can't do that in Java (you can in other languages like Javascript).
That is why we use other classes like the ArrayList to make them grow dynamically in size. At the core of an arraylist you will simply find an array that is renewed in size whenever the class figures out it necessary. If I'm understanding your question right.
I am new to java and I am trying to understand the sequence in which JVM works.I have following queries.
1)Can a class be loaded at run time.
2)Can static variables be allocated memory during runtime.
3)Why static variables cannot be defined inside a function in java?
May be if you can explain me with the help of an example given below:
public class Test{
public static void main(String[] args)throws IOException {
static int d;
}
}
In this example static is written inside a method which will give an error.It would be helpful if you can explain this with above context.
simply answers
Yes
Yes/No
details
You can load any java class in runtime, usually this is done via Classloader
All static variables are actually allocated and initialized by JVM (not you) during runtime, usually just before you use them, check out this answer: Order of initialization of static variable in Java
also you can re-allocate not final static variables in your code with new values/memory, like:
static String a = "a"; // default value to be used by JVM during init
public static void main(String[] args)
{
System.out.println(a); // will print a, as JVM already initialized it with "a"
a = "b"; // we've changed value
System.out.println(a); // now will print b
}
but you cannot define static variable inside function, it is possible in c/c++, but not in java