Reputation: 35
Is it possible to point to the first element of a char[] in java?
I have this code in C++ as an example of what I am trying to do:
char word[100] = " ";
char *p;
cout << "Enter a word: ";
cin.getline(word, 100);
p = word + strlen(word) - 1;
Is it possible to do something like this in Java? Thank you for your time!
Upvotes: 0
Views: 3294
Reputation: 201477
Java has no concept of pointers and Java String
(s) have a fixed length (they're also immutable so they have a fixed everything).
That being said, your posted code is reading one word which you could do with a Scanner
like
Scanner scan = new Scanner(System.in);
String word = scan.next(); // <-- nextLine() if you want a line.
int length = word.length();
Upvotes: 1
Reputation: 556
Short Answer: No
Long Answer: No... Java does not have any pointers. It only has Object references. Any non-primitive data type is pass-by-reference, meaning that if you have the following:
Object a = new Object();
Object b = a;
Object c = new Object();
a == b
is true, while b == c
and a == c
are false.
If you want to have pointer-like behavior in Java, you need to wrap it up in an Object and use references. For example, it is possible that an AtomicInteger[]
could be used, and you pass a reference to one of the AtomicInteger
s, but it would probably be best to hold the int
index as a 'pointer' to the location in the array. Furthermore, your snippet of code could just have a char
variable, set to word[0]
. It really depends on what you need a pointer for...
Upvotes: 0
Reputation: 125
Concept of pointers are not used in java reason been that memory release and allocation is done automatically by the java virtual machine , the only way to access an array reference is through the index
Upvotes: 0
Reputation: 726809
Java lacks the concept of pointers, so the answer is "no". All operations on an array must be performed using indexes.
The consequence of this is that you cannot pass a single argument so methods expecting to read or write arrays starting at a certain position; you always need an array and an index.
Note: In general, C++ approaches to reading strings do not translate to Java very well, because Java I/O libraries will manage memory for you, freeing you from having to worry about buffer overruns on reading a string.
Upvotes: 2