translate c++ code into java - java

I need to translate some c++ into java, but I have I few issues.
How to I have to deal with pointers when they are declared as arguments in the Method?
static void test( double *output){}
Also what is and how can I replace struct?
struct test { int t;
int arg;
float *pva;
double *array;
}
And then in the code they use:
double test(struct test *test)
{}
Oh and a last one.. this is also inside struct test, what means :
test->arg

static void test( double *output){}
This needs more context, it can mean a pointer to a double or an array of doubles.
struct test { int t;
int arg;
float *pva;
double *array;
}
A struct is a class with default public access level. You can replace it with a class with public members.
test->arg
This accesses the arg member in test.

You do not have pointers in Java, only references and only for objects (not for primitive types). References are like pointers, but you use the '.' notation instead of '*' or '->'. Also, you do not need to delete objects in Java, you just stop using them and eventually the garbage collector with destroy them.
Answering your points above, from bottom to top:
If test is a pointer to a struct or class in C++, and arg is a member variable of test, then
test->arg
is used to access the member through the pointer. This would map to
test.arg
in Java, if arg is a public member variable of the test object.
I would translate the following:
struct test
{
int t;
int arg;
float *pva;
double *array;
}
...
double test(struct test *test)
{}
to
public class Test
{
public int t;
public int arg;
float [] pva;
double [] array;
}
...
public static double test(Test test)
{}
For the first case, i.e. the function
static void test( double *output){}
you cannot pass a pointer to double and modify the double in Java. You have to return a double. If you need the double also as an input parameter, you specify it as a normal parameter that is passed by value:
static double test(double output)
{}
I hope this helps.

In the simple cases you can replace float * and double * with float [] and double [] However C++ allows you to do all sorts of unpleasant things which are difficult to translate into Java because it is not allowed in Java.
You can replace a struct with a class
If you want to understand basic C++ syntax, I suggest you read a guide on how to program in C++.

(1) static void test( double *output){}
Here double* can be replaced with a Double[] (assume that you do a new Double[]) and the method can be put inside a class.
class testMethod {
public static void test (Double []output) { }
}
(2) how can I replace struct?
It can be replaced with a class.
class test {
public int t;
public int arg;
public Float []pva;
public Double []array;
}
(3) double test(struct test *test) {}
It can be,
double test (test t) {}
(4) test->arg
Java doesn't have pointers (though it's implemented with reference); so above statement will be test.arg

Related

How do I provide byte value specifically to a class having m1(byte) and m1(int) signatures

public class HelloWorld
{
public void m1(int i)
{
System.out.println("int-arg");
}
public void m1(byte j)
{
System.out.println("byte-arg");
}
public static void main(String []args)
{
HelloWorld n=new HelloWorld();
n.m1(12);
}
}
O/P: int-arg
Question: 12 is int type and byte type too. so in this case int is the exact match everytime. so what value should I provide if I want to call m1(byte) method?
Thanks.
You can either declare it with type or cast it
byte b = 12;
n.m1(b);
or cast
n.m1((byte)b);
As others have said, you will need to cast it.
In Java, plain numbers (ex: 12) are int by default, if the number has decimals (ex: 12.0), it will default to float double type (thank you #Sushil for the correction). There are suffixed to force some types, but not for all types (ex: 12L is long, 12.0f is float).
You'll need to cast prior to passing the value.
n.m1((byte)12);

Is this a correct way to use Enum?

So I have a field called optionType and I want it to be able to take on 4 different integer values corresponding to certain options. For example optionType = 0 means the user wants to handle something a certain way, optionType = 1 means another way, etc.
But numbers by themselves are meaningless so I wanted to define constants instead in the class.
public class MyClass {
public static final int OPTION_TYPE_DO_THIS = 0;
public static final int OPTION_TYPE_DO_THAT = 1;
public static final int OPTION_TYPE_DO_SOMETHING_ELSE = 2;
public static final int OPTION_TYPE_DO_COOL_THING = 3;
private int optionType;
....
Is it considered normal to define all the constants out like that or is it better to use an enum like
public enum OPTION_TYPE {DO_THIS, DO_THAT, DO_SOMETHING_ELSE, DO_COOL_THING};
Or am I supposed to be using Enum instead somehow?
The key point is more on "how will that information be used at runtime". You see, if you starting thinking about writing code such as
switch(someEnum) {
case DO_THIS: ...
case DO_THAT:
... then you are already going into the wrong direction!
The point is: very often think that enums (or their even-more-low-level numeric constant cousins) are a good way to express such designs.
But that actually leads to quite some problems. Very often, the better, "more OO" way of thing is to use some abstract base class with specific subclasses; in other words: polymorphism!
Edit: just to make that more clear ... a "single" switch over an enum isn't really a problem. But far too often, people end up with many many places in code where they switch over their enums. And all of those places might need updates when you create additional enum constants. A coworker of mine calls that the "enum trap".
Take a look at this question and answer,
Even though it is written in the C# context, the conclusion states that:
Enums are great for lightweight state information.
Static class members would be able to support this multiple state without any extra functionality.
In java enums are more than just "enumerated names" as they are in other language (e.g. in C/C++).
My preferred use is to provide stateless behavior:
class Calculator {
enum Operation {
ADD{
double calculate(double a, double b){ return a + b;}
}
SUB{
double calculate(double a, double b){ return a - b;}
}
MUL{
double calculate(double a, double b){ return a * b;}
}
DIV{
double calculate(double a, double b){ return a / b;}
}
abstract double calculate(double a, double b);
}
Map<String,Operation> operations = new HashMap<>();
Calculator(){
operations.put("+",ADD);
operations.put("-",SUB);
operations.put("*",MUL);
operations.put("/",DIV);
}
public double calculate(double a, String operation, double b){
return operations.get(operation).calculate(a,b);
}
}

C++11: Class storing a function pointer (templatized, non-member function) to Java

I am not primarily a Java programmer... I would like to find a corresponding Java syntax for class storing a function pointer (templatized) as a variable. The function pointer points to a function "outside" the class. The original code is in C++11:
#include <memory>
template <typename T>
using p_function = T(*)(T, T, T);
template <typename T>
class A
{
private:
int k;
p_function<T> pf;
public:
A() { pf = NULL; k = 0; }
A(p_function<T> pf_, int k_) { pf = pf_; k = k_; }
T getF(const T a1, const T a2, const T a3) const { return pf(a1, a2, a3); }
};
template <typename T>
T f1(T x, T y, T z) { return x + y + z; }
template <typename T>
T f2(T x, T y, T z) { return x - y - z; }
int main()
{
A<double> aa (f1<double>, 1.0);
double val= aa.getF(1.0, 2.0, 3.0);
}
Thinking about the problem, is it reasonable to use the interface?
public interface Function <T> {
T pf(T x, T y, T z);
}
or, is there any better way? Java is relatively rapidly develops, there might be "straighter" constructions than few years ago. There are several requirements which I am not able to join together. Could I ask for a short code sample in Java? Thank you very much for your help.
Use java 8. That uses "functional" interfaces (indeed) where an interface defines just one single function.
To not overuse the existing Function class, introduce your own name.
#FunctionalInterface
public interface TriFunction<T> {
T apply(T x, T y, T z);
}
Marking it with the FunctionalInterface annotation is a practice that prevents adding a second function and such.
class Foo {
public static Bar hop(Bar x, Bar y, Bar z) { ... }
}
TriFunction<Bar> pf = Foo::hop;
TriFunction<Integer> pg = (x, y, z) -> x + y + z;
Bar bara = pf.apply(a, b, c);
For primitive types better define own interfaces without generic parameter types. Above pg needs 3 times to unbox the wrapper objects, and one time to box it again to an object.
The package java.util.function contains many functional interfaces, like BinaryOperator and IntBinaryOperator.
In Java 8, you can use method references. More information here: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
Basically, Java 8 gives interfaces with only one method the special property that they can be used (sort of) like function pointers. You can assign a lambda or a method reference to an object of such a type.
For example, somewhat related to your question:
public class HelloWorld {
public interface Function <T> {
T op(T x, T y);
}
public static class Functions {
static int add(int x, int y) { return x + y; }
static int sub(int x, int y) { return x - y; }
}
static Function<Integer> f1, f2; // <-- "function pointer"
public static void main(String []args) {
f1 = Functions::add; // <-- static method reference
f2 = Functions::sub; // <-- static method reference
System.out.println("Test: " + f1.op(1,2) + ", " + f2.op(1,2));
}
}
This code prints, as you'd expect:
Test: 3, -1
So that part of your question should work. However, the part where you define a generic addition is more problematic, because Java doesn't allow you to overload the operator '+'. So the following will not compile in Java:
T add(T x, T y) {
return x + y; // compile error -> no '+' defined for T
}
If you need T to be base types, you'll need to define your f1 and f2 for each base type you want to use. See also this question: Can I do arithmetic operations on the Number baseclass?
I am not sure if I get your question correctly, but have a look at this stackoverflow post.
There are several answers on how to implement function pointer in java.
EDIT
I am not experienced enough in C++ to provide a code sample.
EDIT 2
According to the post I mentioned above, you could try something like this:
public class WithFunction {
//Empty constructor, can be left out
public WithFunction () {...}
//The function you want to reference
public int myReferencedFunction () {...}
}
Then
public class MethodCaller {
public static Object call (Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
//catch Exceptions
}
}
Then you can have it like
public static void main (String [] args) {
WithFunction obj1 = new WithFunction();
Object result = MethodCaller.call (obj1, "toString");
int result = (int) MethodCaller.call (obj1, "myReferencedFunction");
}
Notice:
You need to catch a lot of exceptions. Strong error handling needed..
If you use an interface, you can also implement it multiple times and should have the freedom you need

Incorrect Casting

For some reason I am getting a precision error when I try to compile my code. The precision error comes in the return of my second method where I am trying to calculate the circumference. What am I doing incorrectly?
public class Methods2
{
public static final double PI = 3.14;
public static double calcCirc(double x)
{
return PI*x;
}
public static int calcCirc(int x)
{
return (2*(double) x)*PI;
}
public static void main(String[]args)
{
System.out.println(calcCirc(10.2));
System.out.println(calcCirc(4));
}
}
You are attempting to return a double value in a method declared to return an int. Java won't let you implicitly narrow your value like that.
If you're okay with the loss of precision, then explicitly cast the value to int -- Java will let you do that.
return (int) ((2*(double) x)*PI);
However, I would change the method to return double instead, not to lose precision:
public static double calcCirc(int x)
... as you already did with your other calcCirc method.
Both versions of calcCirc() ought to return doubles.
Also, side note--consider using different method names since they accept inputs that differ not only in type but also in semantics.
E.g. calcCircFromRadius(double radius), calcCircFromDiameter(double diameter). There's not really a reason to take an int as an input type here since Java will automatically cast ints to doubles for you.
try
public static int calcCirc(int x){
return (int)((2*x)*PI);
}

MATLAB function in Java

I tried to run a simple matlab code in java (I'm new to Java).
In matlab, I created this function :
Function [y] = square[x]
y = sqrt(x)
end
I named the class: square
But when I run the function in Eclipse, I couldn't make it work.
Here is the code in Eclipse:
import square.*;
import com.mathworks.*;
import com.mathworks.toolbox.javabuilder.*;
public class square {
/**
* #param args
*/
public static void main(String[] args) {
square x = new square();
Double z = x.square(8);
}
}
The error is: The method square(int) is undefined for the type square
Any idea? Thanks so much!
You can use the Math.Pow() function in Java to square a number. If you wanted to write your own function, you could do:
class Mymaths
{
public static double Square(double exponent, double number)
{
return Math.pow(number,exponent);
}
}
Then you could use that inside your main method:
public static void main(String[] args)
{
Mymaths.Square(2.0,8.0); //should return 64
}
Sorry if I misunderstood, but that's what I read.
The problem you have is that you do not have defined the method square. That is exactly what the compiler complains about.
Define it like this to return a Double object:
private Double square(int x) {
// do whatever you like here
}
However I think it will be better if you use the primitive double type for simple tests (just be aware for the precision).
Another option is to use one of the methods defined in the Math utility class.

Categories