I know there are other questions like this, but they do not answer my question.
in C#, you would use:
using System;
namespace Program
{
static void Main(string[] args)
{
Console.WriteLine("Helllo, World);
Console.ReadLine();
}
}
You use using System; from having to do this:
namespace Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Helllo, World);
System.Console.ReadLine();
}
}
In Java, is there an equivalent to C#'s using System;?
The comments are addressing why the communities of these languages have settled on different approaches, but to answer the question directly:
In Java, the import statement allows for a * suffix to indicate that all classes from a namespace should be imported and usable within the current file without any prefix:
import java.util.*;
This is basically equivalent to something like
using System.Collections.Generic;
However, the Java standard library and the C# standard library are organized quite differently, so there is no declaration that is exactly the same as C#'s using System.
In Java, however, the java.lang package is always implicitly imported, and java.lang contains many things that would be in C#'s System, so you could say that Java makes using System implicit!
For example, in C#, you need using System; to be able to write Console.WriteLine("Hello, World!");, but in Java, you don't need import java.lang.System; to be able to write System.out.println("Hello, world!");.
Java also has a feature called import static, where you can import members of a class rather than just the class itself or the classes in a package. So you could do something like import static java.lang.System.out; or import static java.lang.System.*; and then write out.println("Hello, world!"); if you prefer.
C# also has a feature called a namespace alias where you can import a single name from another namespace, optionally renaming it as you go. So you could write using C = System.Console; and then write C.WriteLine("Hello, world!"); if you prefer.
Both of these latter options are not commonly used with the standard library, but might be used in special cases, or with special classes that are designed to be used in such a way.
Addendum about:
... but then why do C# users use using statements?
Simple: because they only have using, and not Java import. It is a build in property of that language, similar to the fact that C# supports the .Net platform, and Java (mainly) supports the JVM platform.
In other words: different languages follow different paradigms and concepts, very much like "real" human languages. Thus, in essence, the question why does language A support feature X, but language B has Y are (often, not always) not leading to much else but "because that is what the individual people wanted to have".
Related
Coming from a C++ environment I got used to splitting up many of the functions that I needed into an funcs.h file and then do #include "funcs.h" and then adding the functions prototypes into the main .cpp file.
Now I am starting to work with Java (mainly with Minecraft ModloeaderMp), and I already made a funcs.java file where there are some premade functions (e.g., some functions for file copying, giving stacks of items, etc.). Since I am already using the statement Public class mod_mine extends BaseModMp, is there a way I can import the functions or do I can I just do another Public class mod_mine extends funcs?
You don't #include in Java; you import package.Class. Since Java 6 (or was it 5?), you can also import static package.Class.staticMethodOfClass, which would achieve some forms of what you're trying to do.
Also, as #duffymo noted, import only saves you from systematically prefixing the imported class names with the package name, or the imported static method names with the package and class name. The actual #include semantics doesn't exist in Java - at all.
That said, having a "funcs.java" file seems to me like you are starting to dip your toes into some anti-patterns... And you should stay away from these.
There's no #include in Java.
I would not like a design that had a funcs.java that stored all the variables. Objects are state and behavior encapsulated into a single component. You aren't designing in an object-oriented way if you do that.
Good names matter. A class named Stuff that extends Stuff2 had better just be a poor example.
That's not good Java. I wouldn't consider it to be good C++, either.
It sounds like you're putting all your methods in the same class. You should separate them:
Utility classes
These should contain static methods that do things like get the contents of a file, show a dialog screen, or add two numbers together. They don't really belong in an object class, they don't require instances, and they're used widely throughout the program. See java.lang.Math for a good example of this.
Constant class or configuration files
This can be a Constants class that contains static final members, like PI = 3.1415. You can access them using Constants.PI.
Or, you can use configuration files and load them into Configuration and access the configuration variables with something like config.get("database").
Other
If your code doesn't fit into any of these, you will want to put it into some class such that your code fits object-oriented programming concepts. From your question, it sounds like you'll want to read up on this. I would first read Head First Java, then maybe some other books on object-oriented programming in Java. After that, I'd look at some design patterns.
Java is an object-oriented programming language, and there is a reason for it.
There isn't any #include in Java, although you can import classes from other packages.
Making separate class, func.java, to store variables might not be a good idea, until or unless all of them are constants.
By extending some class, you can reuse the function. But does extending class pass the is a test? If not that, this might be a bad idea.
If moving from C++, going through some good book, for example, Head First Java might help a lot.
There isn't any #include in Java. You can use the import statement to make classes and interfaces available in your file.
You can run the C preprocessor on a Java file, ensuring you use the -P flag to disable line annotations. A quick Google search confirms that this has been attempted at least twice, and is even used in the popular fastutil library:
Using C style macros in Java
https://lyubomyr-shaydariv.github.io/posts/2016-09-06-fun-with-java-and-c-preprocessor/
This works for all directives (#include, #define, #ifdef, and so forth) and is both syntactically and semantically identical to the equivalent statements in C/C++.
Actually... There is a way to have the same semantics as in C's #include (the keyword was later borrowed by C++ for the sake of looking fancy...). It's just not defined with the same words, but it does exactly what you are looking for.
First, let's see what you do with #include in C++ to understand the question:
include #defines,
"forward" function definitions (their "body" being defined elsewhere, in a class implementation, if you remember Turbo Pascal, you get my point),
define structures,
and that's pretty much it.
For the structure definitions, there isn't any point. That's old-school C: in C++ you don't define struct {} anymore for ages; you define class structures with properties and accessor methods. It's the same in Java: no typedef struct {} here either.
For this, you have the "interface" declaration (see Interfaces (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)):
It does exactly what you're looking for:
public interface MyDefines {
final CHAR_SPACE : ' '; // ugly #define
int detectSpace(FileInputStream fis); // function declaration
// and so on
}
Then, to use:
public class MyClass extends MyAncestor implements MyDefines {
...
// implementation of detectSpace()
int detectSpace(FileInputStream fis) {
int ret = 0;
char Car;
if((Car = fis.read()) != -1) && (Car == CHAR_SPACE)) ret++;
...
}
Read the link given above; it's full of useful cases.
Similar to dynamic SQL, wherein a String is executed as an SQL at runtime, can we have Java code run dynamically? Like I return a String which is a Java code and then I execute at runtime. Is this possible?
For real Java code, this is possible using the JavaCompiler interface. However, it's very inconvenient to use since it's just an interface to a real Java compiler that expects to compile entire class definitions found in files.
The easiest way to execute code supplied at runtime would be to use the Rhino JavaScript engine.
Both of these options have been only in Java 6, though I believe the scripting interface existed before, so you could use Rhino in an earlier JRE if you download and add it to the classpath.
Javassist
You would need to use a bytecode manipulation library such as Javassist (Wikipedia), in order to run an arbitrary string that is provided at runtime. Javassist allows you to create a CtClass based on a string representing source code; and can then turn this into compiled Class object via a particular classloader, so that the class is then available to your application. Other libraries would need to do something similar to these two steps in order to achieve the same thing.
So it is possible, but it's very heavyweight and is likely to make your application very hard to reason about. If at all possible, consider designing a very flexible class statically, and having it accept parameters that control its behaviour.
If you want to do more than invoke an existing method dynamically, you may need to compile your String into bytecode. An easy way to do this is to include the Eclipse/JDT compiler jar in your classpath, and then you can use that to compile your String into a Class, which can then be loaded.
This type of dynamic code generation and execution is used to convert JSP files into Servlets and is used in other packages such as JasperReports to turn a report specification into a Class that is then invoked.
Remember that just as with SQL you must be careful to prevent code injection security problems if any of the String contains user-specified data.
You also may want to look at Java 6 scripting support:
http://download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.htm
Here is a version of hello world that creates array of strings and prints a first one:
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval("var a=java.lang.reflect.Array.newInstance(java.lang.String, 1);a[0]='Hello World';print(a[0])");
}
}
Yes it is possible. Look at the Java Compiler API. Have a look here:
http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
Have a look at Beanshell. It provides an interpreter with java like syntax.
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.
Originally I was using the underscore _ as a class name. The new Java8 compiler complains that it "might not be supported after Java SE 8". I changed that to $, and there is no warning any more. However I remember that $ is used by Java to indicate an inner/embedded class in the byte code. I am wondering if there is any risk to use a dollar sign $ as a class name
Some background to this question. What I want to do is to overcome the fact that Java doesn't support pure function, and the _ or $ is to put an namespace to encapsulate some very generic concept (classes/static methods). and neither do I have a good name for this, nor do I want the lib user type too many things to reference that namespace. Here is the code showing what I am doing under the way: https://github.com/greenlaw110/java-tool/blob/master/src/main/java/org/osgl/_.java
It is bad style, and potentially risky to use $ in any identifier in Java. The reason it is risky is that the $ character is reserved for the use of the Java toolchain and third-party language tools.
It is used by Java compilers in "internal" class names for inner and nested classes.
It is used by Java compilers in the names of synthetic attributes.
It could be used by third-party code generators (e.g. annotation processors) for various purposes.
It could be used by other languages that target the JVM platform, and that might need to co-exist with your code.
You probably won't have technical issues with a plain $ classname at the moment (at least with respect to the standard Java toolchain). But there's always the possibility that this will change in the future:
They have (effectively) reserved the right to change this1.
There is a precedent for doing this in the _ example.
If you really, really need a one-character classname, it would be better to play it safe and use F or Z or something else that isn't reserved.
But to be honest, I think you'd be better off trying to implement (or just use) a real functional language than trying to shoe-horn a functional programming "system" into Java. Or maybe, just switch to Java 8 ahead of its official release. 'Cos I for one would refuse to read / maintain a Java codebase that looked like jquery.
I don't mean to create a functional lib for Java, just want to create a lib to maintain some common utilities I used. Again, I am a advocate of minimalism and feel suck with things like apache commons. The functional stuff is added to help me easier to manipulate collection(s).
If it is your code, you can do what you like. Make your own decisions. Act on your opinions. Be a "risk taker" ... :-). (Our advice on $, etcetera ... is moot.)
But if you are writing this code for a client or employer, or with the intention of creating a (viable) open source product, then you need to take account of other people's opinion. For example, your boss needs to have an informed opinion on how maintainable your code will be if you find a better paying job somewhere else. In general, will the next guy be able to figure it out, keep your code, fresh, etc ... or will it be consigned to the dustbin?
1 - JLS §3.8 states "The $ character should be used only in mechanically generated source code". That is saying "use it at your peril". The assumption is that folks who build their own source code generators can change them if the standard toolchain uses a bare $ ... but it is harder to change lots of hand written code, and that would be an impediment to upgrading.
Huh, you're right, using a $ in a classname works. Eclipse complains that it is against convention, but, if you are sure, you can do it.
The problem (conventionally) with using a $ is that the $ is used in the class hierarchy to indicate nested classes.... for example, the file A.java containing:
class A {
class SubA {
}
}
would get compiled to two files:
A.class
A$SubA.class
Which is why, even though $ works, it is ill advised because parsing the jars may be more difficult... and you run the risk of colliding two classes and causing other issues
EDIT, I have just done a test with the following two Java files (in the default package)
public class A {
private static final class SubA {
public String toString() {
return "I am initializing Nested SUBA";
}
}
private static final SubA sub = new SubA();
public A() {
System.out.println("What is " + sub.toString());
}
}
public class A$SubA {
#Override
public String toString() {
return "I am A$SubA";
}
}
public class MyMain {
public static void main(String[] args) {
System.out.println(new A());
System.out.println(new A$SubA());
}
}
And the code will not compile.....
Two problems, type A$SubA is already defined, and can't reference a nested class A$SubA by it's binary name.
Yes, to be pedantic about answering your question there is a risk. As some other folks have mentioned, it violates java naming conventions. So the risk is that with future versions of the JDK this may cause problems. But beyond that, and some issues if you try to use nested classes you should be fine.
I think you're trying to avoid ugly names like Util.andThen. Consider using static imports. That lets you import all the methods in the header import static org.ogsl.Util.*, so then you can simply use you andThen without any prefix at all.
The Selenide project does it. Just look at the top of this documentation:
https://selenide.org/documentation.html
Maybe it is a more acceptable thing to do only in test code.
API ref:
https://selenide.org/javadoc/current/com/codeborne/selenide/Selenide.html
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.