1

That is a phone interview question.

Assume you have a C++ code, you want to implement the code by using Java rather than rewriting the code. How would you solve that?

I cannot figure out this question. Can anyone told me the solution?(is it possible by import some package or java library?)

Thanks

11
  • 5
    That's a terrible interview question. Commented Apr 17, 2014 at 23:02
  • Use ProcessBuilder to run a C++ compiler. Well, you'd be using Java like they asked... Commented Apr 17, 2014 at 23:04
  • I am almost certain that there are libraries available to convert C++ code to Java. I cannot imagine you should be responsible for knowing those libraries rather just knowing that they likely exist (and they do, I believe). Commented Apr 17, 2014 at 23:05
  • It depends on the C++ code and the task at hand. Java has some constructs that are more appropriate, such as interfaces. Commented Apr 17, 2014 at 23:05
  • 3
    can you use JNI to call the C++ code? I agree with @Mystical, this is a stupid question. I don't really even know what it means. Commented Apr 17, 2014 at 23:07

1 Answer 1

2

Using Java Native Interface (JNI), you can use a method written in c++(or some other language) in your java code

  1. Begin by writing the Java program. Create a Java class that declares the native method; this class contains the declaration or signature for the native method. It also includes a main method which calls the native method.
  2. Compile the Java class that declares the native method and the main method.
  3. Generate a header file for the native method using javah with the native interface flag -jni. Once you've generated the header file you have the formal signature for your native method.
  4. Write the implementation of the native method in the programming language of your choice, such as C or C++. (this is what you are already given in this case).
  5. Compile the header and implementation files into a shared library file.
  6. Run the Java program.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.