Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have the next code in C++ and I want to write it in Java

C++
#include <iostream>
#include <cstring>
using namespace std;

class MyClass
{
private:
    char *firstName;
    char *secondName;
public:
    MyClass(const char *firstName, const char *secondName)
    {
        if (this->firstName != NULL)
            this->firstName = NULL;
        this->firstName = new char[strlen(firstName)+1];
        strcpy(this->firstName, firstName);

        if (this->secondName != NULL)
            this->secondName = NULL;
        this->secondName = new char[strlen(secondName)+1];
        strcpy(this->secondName, secondName);
    }
    ~MyClass()
    {
        if (firstName != NULL)
            delete firstName;
        firstName = NULL;

        if (secondName != NULL)
            delete secondName;
        secondName = NULL;
    }
    char *getFirstName()
    {
        return firstName;
    }
    char *getSecondName()
    {
        return secondName;
    }
    friend ostream& operator<< (ostream& out, MyClass &obj);
    friend istream& operator>> (istream& in, MyClass &obj);
};

ostream &operator<< (ostream& out, MyClass &obj)
{
    out << "\n First Name: " << obj.firstName << endl;
    out << "\n Second Name: " << obj.secondName << endl;

    return out;
}

istream& operator>> (istream& in, MyClass &obj)
{
    char aux[20];
    if (obj.firstName != NULL)
        delete[] obj.firstName;
    cout << "\n First Name: ";
    in >> aux;
    obj.firstName = new char[strlen(aux)+1];
    strcpy(obj.firstName, aux);

    if (obj.secondName != NULL)
        delete[] obj.secondName;
    cout << "\n Second Name: ";
    in >> aux;
    obj.secondName = new char[strlen(aux)+1];
    strcpy(obj.secondName, aux);

    return in;
}

int main()
{
    MyClass obj("Dragu", "Stelian");
    cout << "\n First Name: " << obj.getFirstName() << endl;
    cout << "\n Second Name: " << obj.getSecondName() << endl;
    cin >> obj;
    cout << obj;
    return 0;
}


I tried to write the code above in Java

Java
package myclass;
import java.util.Scanner;

class FirstClass
{
    private char firstName[];
    private char secondName[];
    public FirstClass(char firstName[], char secondName[])
    {
        this.firstName = firstName;
        this.secondName = secondName;
    }

    public char getFirstName()
    {
        return firstName;
    }

    public char getSecondName()
    {
        return secondName;
    }
};

public class MyClass
{
    public static void main(String[] args)
    {
        FirstClass obj = new FirstClass("Dragu", "Stelian");
        Scanner input = new Scanner(System.in);
        System.out.print("Enter First Name: ");
        obj.firstName = input.nextLine();
        
        System.out.print("Enter Second Name: ");
        obj.secondName = input.nextLine();
        
        System.out.println("Name is: " +obj.firstName + " " +obj.secondName);
    }
    
}


What I have tried:

Now, there are some aspects in Java.
1. There are no pointers in Java, so I am using char variables.
2. There is no destructor in Java.
3. The getFirstName(), getSecondName() functions returns or should return an array of char.
So, I get an error when I try to return an array of char.
4. In C++ to enter data from the keyboard and display them I am using overloading the stream operators.
In Java there is no overloading of operators.
I think it's easier if I use string data.

Please help me!
Posted
Updated 25-Oct-20 22:33pm
v2

First, you should write 'sensible' C++ code.
C++
#include <iostream>
#include <string>
using namespace std;

class Person
{
  string firstname, secondname;
public:
  Person( const char * firstname, const char * secondname ) : firstname(firstname), secondname(secondname)
  {
  }
  string getFirstName() const { return firstname; }
  string getSecondName() const { return secondname; }

  friend istream& operator>> (istream& in, Person & p);
};

ostream& operator<< (ostream& out, const Person & p)
{
  out << "\n First Name: " << p.getFirstName() << "\n";
  out << "\n Second Name: " << p.getSecondName() << endl;
  return out;
}

istream& operator>> (istream& in, Person & p)
{
  in >> p.firstname >> p.secondname;
  return in;
}

int main()
{
  Person dragu("Dragu", "Stelian");
  cout << "\n First Name: " << dragu.getFirstName() << endl;
  cout << "\n Second Name: " << dragu.getSecondName() << endl;

  cout << "\nPlease enter person't first and second name: ";
  cin >> dragu;
  cout << dragu;
}


Then you should consider that moving C++ code to Java is regarded as a crime against humanity.
 
Share this answer
 
Comments
Richard MacCutchan 18-Apr-19 8:18am    
Look at the date of the question.
CPallini 18-Apr-19 9:34am    
Oh My God, I am a bit late. Thank you for pointing it out.
From where did you got that (bad) C++ code and did you even compiled both versions?

A much better version would use std::string instead of char arrays. Then it can be converted to Java using the Java String class. So change your members to that type in your Java class.

Because you are setting strings of existing objects and the members are private, you must also provide setFirstName() and setLastName() functions (in the C++ and Java version) or make the string members public (which would be bad style).

[EDIT]
Using std::string in the C++ version avoids handling the buffers yourself and reduces the source code: No allocation and deleting is required and the default created destructor will call the destructors of the string members so that there is no need to implement a destructor. While there might be reasons to do such sometimes, it is usually not necessary with strings. Just keep it simple.

Some notes when using your own C++ memory allocation:

  • There is no need to check for NULL pointers in the constructor. The values are undefined there until set.
  • There is no need to check for NULL pointers with delete.
  • There is no need to set the pointers finally to NULL in the destructor.

The above explains why I wrote of bad code. Note also that the get functions should be const and return const chars:
// Allocated string versions
const char *getFirstName() const { return firstName; }
// std::string version
const char *getFirstName() const { return firstName.c_str(); }

Java is a garbage collected language so that there is no need for a destructor or releasing of objects. While it would be possible to create your own char based objects to hold strings it is even more useless than with C++ (for the same reasons and it is rather uncommon with Java).

The stream operations can't be simply converted to Java. But I think your solution fits so that I did not provide a solution.

But you might create a function that prints the values out.
[/EDIT]
 
Share this answer
 
v2
Comments
kinderu 9-Aug-17 9:13am    
Both codes are made by me(for the sake of practice).
Yes I did compiled both version, C++ code run ok, Java code no.
As you saw in the previous post, I said it would have been easier to use String data.

Ok, I changed the type of members.

package myclass;
import java.util.Scanner;

class FirstClass
{
    private String firstName;
    private String secondName;
    public FirstClass(String firstName, String secondName)
    {
        this.firstName = firstName;
        this.secondName = secondName;
    }

    public String getFirstName()
    {
        return firstName;
    }
    
    public void setFirstName(String firstName)
    {
       this.firstName = firstName; 
    }

    public String getSecondName()
    {
        return secondName;
    }
    
    public void setSecondName(String secondName)
    {
       this.secondName = secondName;
    }
};

public class MyClass
{
    public static void main(String[] args)
    {
        FirstClass obj = new FirstClass("Dragu", "Stelian");
        Scanner input = new Scanner(System.in);
        System.out.print("Enter First Name: ");
        obj.setFirstName = input.nextLine();
        
        System.out.print("Enter Second Name: ");
        obj.secondName = input.nextLine();
        
        System.out.println("Name is: " +obj.firstName + " " +obj.secondName);
    } 
}



So I get an error in the lines Obj.firstName = input.nextLine();
Obj.secondName = input.nextLine();
which is normal because firstName and secondName members are private.


I just want to input firstName and secondName from keyboard like in C++ code where I am using stream operator overloading.
Jochen Arndt 9-Aug-17 9:22am    
I must admit that I missed the friend with the C++ version.

To avoid the Java error use the new functions:
obj.setFirstName(input.nextLine());

And you must also use the get functions when printing on the last line like in the C++ version.
kinderu 9-Aug-17 9:42am    
import java.util.Scanner;

class FirstClass
{
private String firstName;
private String secondName;
public FirstClass(String firstName, String secondName)
{
this.firstName = firstName;
this.secondName = secondName;
}

public String getFirstName()
{
return firstName;
}

public void setFirstName()
{
Scanner in = new Scanner(System.in);
firstName = in.nextLine();
}

public String getSecondName()
{
return secondName;
}

public void setSecondName()
{
Scanner in = new Scanner(System.in);
secondName = in.nextLine();
}
};

public class MyClass
{
public static void main(String[] args)
{
FirstClass obj = new FirstClass("Dragu", "Stelian");
System.out.println("Name is: " +obj.getFirstName() + " " +obj.getSecondName());

System.out.print("Enter First Name: ");
obj.setFirstName();

System.out.print("Enter Second Name: ");
obj.setSecondName();

System.out.println("Name is: " +obj.getFirstName() + " " +obj.getSecondName());
} 
}


Still I have a question: Why is so bad to use char arrays ?
Jochen Arndt 9-Aug-17 9:45am    
I will update my solution with some information answering that too.
kinderu 9-Aug-17 12:46pm    
Thank you for your time Jochen Arndt!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900