When I type an entry for an array in java this way, Jalopy (an alternate program to Jindent) switches the square bracket to the other side. Am I typing the wrong way or what?
Before formatting:
After formatting:
Using square bracket after variable name is old style of C,C++. While placing it with the type name is recommended by Java. It is specific to java code style. Since Jalopy is specifically there to format java Code it uses recommended Java style to format. and Hence the code is changing.
Consistency for one, I guess.
And more importantly to make the types clearer. Java (similar to C, I think) allows the [] to appear after either the type or identifier (or even both, being the equivalent of [][]). Putting them after the type makes very clear what the actual type is, because nickFreq is an int[], not an int.
If you prefer the old C-style, you can configure it in your settings, see here:
http://www.triemax.com/products/jalopy/manual/java.html#ARRAY_BRACKETS_AFTER_IDENT
It gets quite interessting when it comes to multi-dimensional arrays...
Related
I am so used to C++ & C# where I can type bool. In Java, I am required to type boolean. Also, it requires me to type String with uppercase 'S'. I would love to be able to create project wide aliases for these variable types to enable me to create variables by typing bool and string. Do you have any ideas?
If you want to actually change the syntax of the language, that is not only impossible, but a terrible idea. Aliases would make code indecipherable to others.
However, it is possible to only type 'bool'+{TAB} and 'string'+{TAB} and have NetBeans change it to 'boolean' or 'String', respectively. In fact, you have much more flexibility than that (for example, you could make it 'boo'+{SPACE}='boolean' or 'bo'+{ENTER}='boolean').
Take a look at 'NetBeans->Preferences->Editor->Code Templates' if that is the kind of thing you need; should be pretty self-explanatory.
Im learning formatting in Java and have been using printf and format methods.
To me these seem to behave exactly the same.
Is there any reason why I should use one over the other ?
Is one considered newer and/or a better one to use as standard and if so why?
The situations in which you use them can be different; if you want to print a text it's normally easier to use printf(). If you want to do something else with the String (e.g. put it into a graphical element or a logger) then you'll use String.format().
The PrintStream#printf(...) methods actually delegate to the PrintStream#format(...) methods. So no, there should be no difference.
Edit:
If you are talking about String.format(...), this performs the formatting in exactly the same manner; the difference is that it returns the formatted String instead of writing it to the stream.
Lets take a
val m = "Scala is fun"
IntelliJ helps figure out a lot of things that can be done with this
Is there a way for me to know which of these functions come from Scala and which ones come from Java?
In IDEA's autocompletion, bold entries are methods defined on the type of the object itself, while underlined functions are added by implicit conversions and pimp-my-library (for explanation, see for instance here or search on StackOverflow or Google).
However, for the special case of types which are defined in Java (like String, the type of m), you happen to be right on the Java-vs-Scala distinction: there bold methods are real methods, which must be defined within the type of m (here String) and thus in Java. While pimp-my-library is a Scala pattern, so typically underlined functions will be written in Scala (this is just a rule of thumb, but I've never yet seen an exception).
Non-bold functions are simply inherited.
For the amount of documentation, as a rule of thumb the Java standard library has quite comprehensive documentation (it's supposed to be a specification for the method) while Scala varies typically between less and much less documentation.
I've searched for how to change the fonts used for this highlighting in IntelliJ 11, but I've not found much - you can change fonts used to highlight the code, but I suspect that doesn't make a difference here.
If you have IDEA 12 you can hit Ctrl-Q on any selected method in the pop-up to view "Quick documentation" for that method, not only that, you can traverse the list of methods and the quick doc will change to suit the new selections.
If you find any entries with no quick help, it's a good bet it will be a Scala method ;#)
I'll check for IDEA 11 too.
EDIT: It works for IDEA 11 CE and Ultimate too.
I'm using Java 6.
Suppose I have a file availableFruits.txt
APPLE
ORANGE
BANANA
Suppose I want an enum FruitType that contains values listed in availableFruits.txt, will I be able to do this?
You can't populate an enum type at execution time, no - at least, not without something like BCEL, or by calling the Java compiler.
You can write code to create a Java source file, of course, and build that when you build your app, if you don't need it to be changed afterwards.
Otherwise, I'd just create a wrapper class which is able to take a set of known values and reuse them. Exactly what you need to do will depend on how you wanted to use the enum, of course.
Well the point of an Enum is to use it at compile time.
If you don't know at compile time what values your Enum has then it's not an Enum it's a collection.
If you do know and you just want to create a class file base on the values in the text file then yes it's possible by reading the txt then generating the source code.
I expect it's possible, by writing your own ClassLoader subclass, creating the bytecode for the enum in a byte array, and using defineClass. Hard, maybe, but possible. I expect once you know the byte sequence for an enum, it's not that hard to custom-generate it from the info in the JVM spec.
Now, whether it's a good idea...well, I suspect only in a very small number of edge cases. (I can't think of one; I mean, having created it, you'd have to generate code to use it, right?) Otherwise, you're probably better off with a Map or similar.
No, not unless you generate the enum source file from the text file.
As everyone else said- no. It's not possible. Your best shot is to use the Registry pattern. Read in the values, store them in some sort of query-able map. Sort of like an Enum.
As everyone pointed out, it's not possible. However, you could create a Map where the key of your map would be the value you read from you file (APPLE,ORANGE,BANANA) and the ? would be an associated valu (int for example).
This way you could basically achieve the same goal without the type safety, of course.
int i = fruitsMap.get("BANANA") // get the assoicated value
You can with dynamically generated code. e.g. Using the Compiler API. I have written a wrapper for that API so you can compile classes in memory. See the code below.
The problem you have is that its not very useful as you cannot use these values except in classes which were compiled AFTER your enum was compiled. You can use Enum.valueOf() etc. But a lot of the value of enums is lost.
As other have suggested, using a Map would be simpler and give the same benefit. I would only use the enum if you have a library has to be passed an Enum. (Or plan more generated code)
public static Class generateEnum(String className, List<String> enums) {
StringBuilder code = new StringBuilder();
code.append("package enums; public enum enums." + className + " {\n");
for (String s : enums)
code.append("\t"+s+",\n");
code.append("}");
return CompilerUtils.CACHED_COMPILER
.loadFromJava("enums."+className, code.toString());
}
One of things I find useful with text generated code is that you can write it to a file and debug it even at run time. (The library supports this) If you byte code generation, its harder to debug.
The library is called Essence JCF. (And it doesn't require a custom class loader)
How would you do this in a dynamic language like JavaScript: it would be just string with one of values: "APPLE", "ORANGE", "BANANA".
Java types (classes, interfaces, enums) exist only for compiler to do some optimizations, and type checking, to make refactoring possible, etc. At runtime you don't need neither optimizations, type checking nor refactoring, so normal "string" is OK, just like in JavaScript every object is either a number (Double in Java), a string (String in Java) or a complex object (Map in Java) - that's all you need to do anything at runtime even in Java.
Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?
List comprehensions. I often find myself filtering/mapping lists, and being able to say [line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")] is really nice.
Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and have lexical scope. This makes it really easy to say things like people.sort(key=lambda p: p.age) and thus sort a bunch of people on their age without having to define a custom comparator class or something equally verbose.
Everything is an object. Java has basic types which aren't objects, which is why many classes in the standard library define 9 different versions of functions (for boolean, byte, char, double, float, int, long, Object, short). Array.sort is a good example. Autoboxing helps, although it makes things awkward when something turns out to be null.
Properties. Python lets you create classes with read-only fields, lazily-generated fields, as well as fields which are checked upon assignment to make sure they're never 0 or null or whatever you want to guard against, etc.'
Default and keyword arguments. In Java if you want a constructor that can take up to 5 optional arguments, you must define 6 different versions of that constructor. And there's no way at all to say Student(name="Eli", age=25)
Functions can only return 1 thing. In Python you have tuple assignment, so you can say spam, eggs = nee() but in Java you'd need to either resort to mutable out parameters or have a custom class with 2 fields and then have two additional lines of code to extract those fields.
Built-in syntax for lists and dictionaries.
Operator Overloading.
Generally better designed libraries. For example, to parse an XML document in Java, you say
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml");
and in Python you say
doc = parse("test.xml")
Anyway, I could go on and on with further examples, but Python is just overall a much more flexible and expressive language. It's also dynamically typed, which I really like, but which comes with some disadvantages.
Java has much better performance than Python and has way better tool support. Sometimes those things matter a lot and Java is the better language than Python for a task; I continue to use Java for some new projects despite liking Python a lot more. But as a language I think Python is superior for most things I find myself needing to accomplish.
I think this pair of articles by Philip J. Eby does a great job discussing the differences between the two languages (mostly about philosophy/mentality rather than specific language features).
Python is Not Java
Java is Not Python, either
One key difference in Python is significant whitespace. This puts a lot of people off - me too for a long time - but once you get going it seems natural and makes much more sense than ;s everywhere.
From a personal perspective, Python has the following benefits over Java:
No Checked Exceptions
Optional Arguments
Much less boilerplate and less verbose generally
Other than those, this page on the Python Wiki is a good place to look with lots of links to interesting articles.
With Jython you can have both. It's only at Python 2.2, but still very useful if you need an embedded interpreter that has access to the Java runtime.
Apart from what Eli Courtwright said:
I find iterators in Python more concise. You can use for i in something, and it works with pretty much everything. Yeah, Java has gotten better since 1.5, but for example you can iterate through a string in python with this same construct.
Introspection: In python you can get at runtime information about an object or a module about its symbols, methods, or even its docstrings. You can also instantiate them dynamically. Java has some of this, but usually in Java it takes half a page of code to get an instance of a class, whereas in Python it is about 3 lines. And as far as I know the docstrings thing is not available in Java