In C++, if you need to have 2 objects modified, you can pass by reference. How do you accomplish this in java? Assume the 2 objects are primitive types such as int.
You can't. Java doesn't support passing references to variables. Everything is passed by value.
Of course, when a reference to an object is passed by value, it'll point to the same object, but this is not calling by reference.
Wrap them in an object and then pass that object as a parameter to the method.
For example, the following C++ code:
bool divmod(double a, double b, double & dividend, double & remainder) {
if(b == 0) return false;
dividend = a / b;
remainder = a % b;
return true;
}
can be rewritten in Java as:
class DivRem {
double dividend;
double remainder;
}
boolean divmod(double a, double b, DivRem c) {
if(b == 0) return false;
c.dividend = a / b;
c.remainder = a % b;
return true;
}
Although more idiomatic style in Java would be to create and return this object from the method instead of accepting it as a parameter:
class DivRem {
double dividend;
double remainder;
}
DivRem divmod(double a, double b) {
if(b == 0) throw new ArithmeticException("Divide by zero");
DivRem c = new DivRem();
c.dividend = a / b;
c.remainder = a % b;
return c;
}
Java does not have pass by reference, but you can still mutate objects from those references (which themselves are passed by value).
java.util.Arrays.fill(int[] arr, int val) -- fills an int array with a given int value
java.util.Collections.swap(List<?> list, int i, int j) -- swaps two elements of a list
StringBuilder.ensureCapacity(int min) -- self-explanatory
As you can see, you can still modify objects (if they're not immutable); you just can't modify references or primitives by passing them to a function.
Of course, you can make them fields of an object and pass those objects around and set them to whatever you wish. But that is still not pass by reference.
Using generics you can create a pointer class which would make this at least somewhat less painful. You pass in the object, change it's value property and when the function exits your object will contain the new value.
MyPointerClass<int> PointerClass = new MyPointerClass<int>(5);
myFunction(PointerClass);
System.out.println(PointerClass.Value.toString());
// ...
void myFunction(myPointerClass<int> SomeValue)
{
SomeValue.Value = 10;
}
Related
I'm taking a java course on lynda.com, and the course was explaining how to "cast" a variable if you want to shorten it.
WIDENING: Widening a variable is making it larger (e.g. int int1 = 4030; long long1 = int1;)
SHORTENING: Shortening a variable is making it smaller, and requires special syntax. (e.g. int int2 = 5024; short int3 = (short) int2;).
So, my question is, why would anyone want to do this? What's the advantage? If you know you'll need to widen a variable at some point, why don't you just start it as that variable? And why would you want to make your data type smaller if you're shortening? If you think that it could be used like this:
byte byte1 = 127;
byte1++;
if (byte1 > 127) {
short short1 = byte1;
}
(I know that this would give an error message, but you get the rough idea.)
You could do this, but why? It wouldn't save data, because it just adds more lines of code which would take up that data.
There are several reasons you might want to "shorten" a variable.
One is that an API or library you are working with requires data to be passed that is of a "shorter" type than the type you were using in your code.
Another is to save space. For example, if I only need to store a two digit number, using a long would be overkill as it would use much more system memory than is needed. This isn't something you normally need to worry too much about, but it could be an issue on certain systems or for very large projects.
There may be even more reasons; these are just a few examples.
You absolutely can't avoid this if you must pass a value received from a function that is out of your control into another function that is also out of your control:
package abc.def:
public class Foo {
public static long foo() { ... }
}
package xyz.qwerty:
public class Bar {
public static void bar(int n) { ... }
}
Your code:
import xyz.qwerty.Bar;
import abc.def.Foo;
...
Bar.bar((int)Foo.foo());
There may be intermediate variables temporarily holding the value received from Foo.foo() before it gets to Bar.bar() but that doesn't eliminate the inevitable need for converting from one type to another, which must happen somewhere in between.
Imagine you want to implement a min(...) method to calculate the minimum of two numbers. You could simply write:
public static double min(double lhs, double rhs) {
if (lhs >= rhs) {
return (lhs);
}
// else if (rhs > lhs) {
return (rhs);
// }
and through auto-casting (or what you refer to as "widening"), you could call this method with all primitives in Java. The downside, however, is that the result would always be double and if you want to save it as an int, you would have to downcast the result:
int i1 = 0;
int i2 = 100;
int max = (int) max(i1, i2);
It would be nice if the method returned an int iff. both parameters are int, a long iff. one parapeter is long and the other parameter is long or int and so on. This would result in the following code1:
public static int min(int lhs, int rhs) {
if (lhs >= rhs) {
return (lhs);
}
// else if (rhs > lhs) {
return (rhs);
// }
}
public static long min(long lhs, long rhs) {
if (lhs >= rhs) {
return (lhs);
}
// else if (rhs > lhs) {
return (rhs);
// }
}
public static float min(float lhs, float rhs) {
if (lhs >= rhs) {
return (lhs);
}
// else if (rhs > lhs) {
return (rhs);
// }
public static double min(double lhs, double rhs) {
if (lhs >= rhs) {
return (lhs);
}
// else if (rhs > lhs) {
return (rhs);
// }
}
Then you could write:
int i = 0;
long g = 1L;
float f = 2f;
double d = 3.0;
int intMax = max(i, i);
long longMax = max(i, g);
float floatMax = max(i, f);
double doubleMax = max(l, d);
Through the means of autocasting and method overloading, the most specific method will be called2,3.
1 You culd write those methods for byte, short and charas well. I would not recommend doing so since all arithemtic operations in Java return at least something of type int (e.g. byte + byte will return an int). This is due to the fact that the JVM does not know of the primitives boolean, char, byte and short, they are represented as int (see JLS §2.11.1).
2 The exact behaviour is specified in JLS, §15.12.2.5
3 This is actually the same mechanism used forjava.lang.Math's implementation of min(...), its implementation is slightly different.
I'm not habitual to casting a primitive data type to an object. Saw some code like:
public static int CompareAges(Person p1, Person p2) {
Integer age1 = p1.getAge();
return age1.compareTo(p2.getAge());
}
The instantiation of age1 seemed extraneous, so I tried to write the code as:
public static int CompareAges(Person p1, Person p2) {
return p1.getAge().compareTo(p2.getAge());
}
But that raised a compiler error because p1.getAge() is a primitive data type int and not an Integer, which is an object.
Intuitively, I did:
public static int CompareAges(Person p1, Person p2) {
return ((Integer) p1.getAge()).compareTo(p2.getAge());
}
and it worked!
The question: What did I miss? Since when did we start casting primitives as value types?
It's what happens internally:
1. Integer age1 = p1.getAge();
Integer != int
Integer = Integer.valueOf(int)
Integer age1 = Integer.valueOf(p1.getAge());
2. p1.getAge().compareTo(p2.getAge());
int.compareTo(int)
^^^
// it's just a primitive type, as a result - the compile error
3. ((Integer) p1.getAge()).compareTo(p2.getAge())
Integer.compareTo(int)
Integer.compareTo(Integer.valueOf(int))
((Integer) p1.getAge()).compareTo(Integer.valueOf(p2.getAge()))
4. (Integer) p1.getAge() ---> Integer.valueOf(p1.getAge())
// why so? look at callOfCode's answer
But, in my opinion, ((Integer) p1.getAge()).compareTo(p2.getAge()) looks ugly.
I would replace it to
p1.getAge() > p2.getAge() ? 1 : (p1.getAge() < p2.getAge() ? -1 : 0)
or to
Integer.compare(p1.getAge(), p2.getAge()) // java 7+
I wouldn't like to do casting in this case.
More about "autoboxing/unboxing" you may find here.
Each primitive has its own boxing type
The Boxing could be implicit (Autoboxing) or explicit like you did it in your code.
p2.getAge() is an Example of AutoBoxing or Implicit Boxing. The method compareTo takes an Object. As it is a primitive, Java converts it automatically to the correspondent Boxing Object (Integer). You did the explicit Boxing with the cast (Integer) p1.getAge()
Difference between new Integer(primitive); and Integer integer = (Integer)primitive; Is only on bytecode level. In the first case, new object of Integer class is created in memory. In the second case, Integer.valueOf(primitive) is called internally. This is the static method that checks if primitive falls into range of -128 to 127 and if it falls, it returns value from integer cache and no new object is being created. If it not falls into that range, new Integer object is instantiated. It is used for efficiency. But such efficiency is unsignificant novadays.
int z = 1;
Integer a = (Integer)z;
Integer b = (Integer)z;
//Prints true, since Integer object is retrieved from cache (range of -128 to 127)
System.out.println(a == b);
int w = 999;
Integer c = (Integer)w;
Integer d = (Integer)w;
//Prints false, since 999 is not in cache, new Integer objects are instantiated and they points to different places in memory
System.out.println(c == d);
I have a question: I work in environment of Eclipse.
Sometimes the computer does not give to the following casting:
int a ...
Object ans = (int) a;
But only this conversion:
int a ...
Object ans = (Integer) a;
I understand why you can do the casting between Object to Integer, but why primitive variable - there are times when you can, and there are times you can not do a casting?
Thank you
I am attaching the code which the compiler not let me make casting between int variable to object:
/** #return minimum element */
public Object minimum(){
return minimum(this.root);
}
public Object minimum(BSTNode node){
if (node.left != null) return minimum(node.left);
return node.data;
}
/** #return maximum element */
public Object maximum(){
return maximum(this.root);
}
public Object maximum(BSTNode node){
if (node.right != null) return maximum(node.right);
return node.data;
}
public Object findNearestSmall(Object elem) {
int diff;
diff = (int)maximum() - (int)minimum();
if (compare(minimum(), elem) == 0) return elem;
else return findNearestSmall(elem, this.root, diff);
}
public Object findNearestSmall(Object elem, BSTNode node, int mindiff){
if(node == null) return (int)elem - mindiff;
int diff = (int)elem - (int)node.data;
if(diff > 0 && mindiff > diff) mindiff = diff;
/* Case 2 : Look for in left subtree */
if(compare(node.data, elem)>-1)
return findNearestSmall(elem, node.left, mindiff);
else
/* Case 3 : Look for in right subtree */
return findNearestSmall(elem, node.right, mindiff);
}
Before Java 1.5, you couldn't even do this:
int a;
...
Object x = (Integer) a;
The compiler would complain that a is of a primitive data type, and therefore cannot be cast to an object.
Starting with Java 1.5, Java introduced the concept of automatic boxing. So, the following became OK:
int a;
...
Object x = (Integer) a;
Because the compiler knows how to convert from a primitive int to the boxed type Integer automatically; and from Integer to an Object it's, well, not a problem.
However, what you're trying to do:
int a;
...
Object x = (int) a;
Is basically telling the compiler to avoid boxing. You explicitly tell the compiler to leave a as an int, and put a reference to that int into an Object. The compiler isn't designed to deal with such a case.
You cannot cast from a referenced data-type to a primitive data-type i.e. you cannot:
Object x = (int)a;
You can however do:
Object x = (Integer)a;
because Integer is a class and int is a primitive data-type.
If I assume it correctly, the functionality you want to achieve is get the integer's value from Object x which can be done as:
Object x = (Integer)a;
//Do something and somewhere else
int z = ((Integer)x).intValue();
This may through a ClassCastException if it is not of Integer class.
You should look into the difference between int which is a primitive type, and Integer, which is a wrapper class in Java.
An Integer is also an Object and stays as an Object on the Heap.
An int is a primitive type. It is NOT an Object. An Object has its own state and behavioral properties, int doesn't have those. So you get a compilation error when trying to convert an Object to a primitive. On the other hand, Converting an int to Object is possible because of Autoboxing
But I am able to execute the following code. I am using jdk 1.6 and the following code is not throwing me any errors or runtime exceptions.
int i=5;
Object test = (int)i;
System.out.println(test.getClass());
Output: class java.lang.Integer
int is a primitive type.
Way of declaration: int a = 5;
Integer is a wrapper class (it extends Object).
Way of declaration: Integer a = new Integer(5);
When you write
Integer a = 5;
compiler automatically converts it to
Integer a = new Integer(5);
This feature is called Autoboxing (since Java 5.0)
int can not be casted to Object as it is not a referenced data type (object) at all.
But it can be casted to other primitive types.
On the other hand, Integer can be casted to Object.
When you write
Object ans = (Integer) a;
compiler does autoboxing and then casts it.
Object ans = (int) a;
gives a compiler error because the cast to int is successful, but it can not be assigned to an Object reference.
Hope this helps.
Good luck.
How can I cast an Object to an int in java?
If you're sure that this object is an Integer :
int i = (Integer) object;
Or, starting from Java 7, you can equivalently write:
int i = (int) object;
Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.
This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.
int is a primitive so it can't be stored as an Object, the only way is to have an int considered/boxed as an Integer then stored as an Object.
If your object is a String, then you can use the Integer.valueOf() method to convert it into a simple int :
int i = Integer.valueOf((String) object);
It can throw a NumberFormatException if your object isn't really a String with an integer as content.
Resources :
Oracle.com - Autoboxing
Oracle.com - Primitive Data types
On the same topic :
Java: What's the difference between autoboxing and casting?
Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
Convert Object into primitive int
Scenario 1: simple case
If it's guaranteed that your object is an Integer, this is the simple way:
int x = (Integer)yourObject;
Scenario 2: any numerical object
In Java Integer, Long, BigInteger etc. all implement the Number interface which has a method named intValue. Any other custom types with a numerical aspect should also implement Number (for example: Age implements Number). So you can:
int x = ((Number)yourObject).intValue();
Scenario 3: parse numerical text
When you accept user input from command line (or text field etc.) you get it as a String. In this case you can use Integer.parseInt(String string):
String input = someBuffer.readLine();
int x = Integer.parseInt(input);
If you get input as Object, you can use (String)input, or, if it can have an other textual type, input.toString():
int x = Integer.parseInt(input.toString());
Scenario 4: identity hash
In Java there are no pointers. However Object has a pointer-like default implementation for hashCode(), which is directly available via System.identityHashCode(Object o). So you can:
int x = System.identityHashCode(yourObject);
Note that this is not a real pointer value. Objects' memory address can be changed by the JVM while their identity hashes are keeping. Also, two living objects can have the same identity hash.
You can also use object.hashCode(), but it can be type specific.
Scenario 5: unique index
In same cases you need a unique index for each object, like to auto incremented ID values in a database table (and unlike to identity hash which is not unique). A simple sample implementation for this:
class ObjectIndexer {
private int index = 0;
private Map<Object, Integer> map = new WeakHashMap<>();
// or:
// new WeakIdentityHashMap<>();
public int indexFor(Object object) {
if (map.containsKey(object)) {
return map.get(object);
} else {
index++;
map.put(object, index);
return index;
}
}
}
Usage:
ObjectIndexer indexer = new ObjectIndexer();
int x = indexer.indexFor(yourObject); // 1
int y = indexer.indexFor(new Object()); // 2
int z = indexer.indexFor(yourObject); // 1
Scenario 6: enum member
In Java enum members aren't integers but full featured objects (unlike C/C++, for example). Probably there is never a need to convert an enum object to int, however Java automatically associates an index number to each enum member. This index can be accessed via Enum.ordinal(), for example:
enum Foo { BAR, BAZ, QUX }
// ...
Object baz = Foo.BAZ;
int index = ((Enum)baz).ordinal(); // 1
Assuming the object is an Integer object, then you can do this:
int i = ((Integer) obj).intValue();
If the object isn't an Integer object, then you have to detect the type and convert it based on its type.
#Deprecated
public static int toInt(Object obj)
{
if (obj instanceof String)
{
return Integer.parseInt((String) obj);
} else if (obj instanceof Number)
{
return ((Number) obj).intValue();
} else
{
String toString = obj.toString();
if (toString.matches("-?\d+"))
{
return Integer.parseInt(toString);
}
throw new IllegalArgumentException("This Object doesn't represent an int");
}
}
As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.
You have to cast it to an Integer (int's wrapper class). You can then use Integer's intValue() method to obtain the inner int.
Answer:
int i = ( Integer ) yourObject;
If, your object is an integer already, it will run smoothly. ie:
Object yourObject = 1;
// cast here
or
Object yourObject = new Integer(1);
// cast here
etc.
If your object is anything else, you would need to convert it ( if possible ) to an int first:
String s = "1";
Object yourObject = Integer.parseInt(s);
// cast here
Or
String s = "1";
Object yourObject = Integer.valueOf( s );
// cast here
I use a one-liner when processing data from GSON:
int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;
If the Object was originally been instantiated as an Integer, then you can downcast it to an int using the cast operator (Subtype).
Object object = new Integer(10);
int i = (Integer) object;
Note that this only works when you're using at least Java 1.5 with autoboxing feature, otherwise you have to declare i as Integer instead and then call intValue() on it.
But if it initially wasn't created as an Integer at all, then you can't downcast like that. It would result in a ClassCastException with the original classname in the message. If the object's toString() representation as obtained by String#valueOf() denotes a syntactically valid integer number (e.g. digits only, if necessary with a minus sign in front), then you can use Integer#valueOf() or new Integer() for this.
Object object = "10";
int i = Integer.valueOf(String.valueOf(object));
See also:
Inheritance and casting tutorial
int i = (Integer) object; //Type is Integer.
int i = Integer.parseInt((String)object); //Type is String.
Can't be done. An int is not an object, it's a primitive type. You can cast it to Integer, then get the int.
Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class
int num = i; //Java 1.5 or higher
You can't. An int is not an Object.
Integer is an Object though, but I doubt that's what you mean.
If you mean cast a String to int, use Integer.valueOf("123").
You can't cast most other Objects to int though, because they wont have an int value. E.g. an XmlDocument has no int value.
I guess you're wondering why C or C++ lets you manipulate an object pointer like a number, but you can't manipulate an object reference in Java the same way.
Object references in Java aren't like pointers in C or C++... Pointers basically are integers and you can manipulate them like any other int. References are intentionally a more concrete abstraction and cannot be manipulated the way pointers can.
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
ArrayList list = null;
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
while (result.next()) {
list.add(result.getInt(1));
}
statement.close();
int id[] = new int[list.size()];
for (int i = 0; i < id.length; i++) {
try {
id[i] = ((Integer) list.get(i)).intValue();
} catch(NullPointerException ne) {
} catch(ClassCastException ch) {}
}
return id;
}
// enter code here
This code shows why ArrayList is important and why we use it. Simply casting int from Object. May be its helpful.
For Example Object variable; hastaId
Object hastaId = session.getAttribute("hastaID");
For Example Cast an Object to an int,hastaID
int hastaID=Integer.parseInt(String.valueOf(hastaId));
Refer This code:
public class sample
{
public static void main(String[] args)
{
Object obj=new Object();
int a=10,b=0;
obj=a;
b=(int)obj;
System.out.println("Object="+obj+"\nB="+b);
}
}
so divide1=me.getValue()/2;
int divide1 = (Integer) me.getValue()/2;
We could cast an object to Integer in Java using below code.
int value = Integer.parseInt(object.toString());
If you want to convert string-object into integer...
you can simply pass as:
int id = Integer.valueOf((String) object_name);
Hope this will be helpful :-)
Integer x = 11
int y = x.intValue();
System.out.println("int value"+ y);
Finally, the best implementation for your specification was found.
public int tellMyNumber(Object any) {
return 42;
}
first check with instanceof keyword . if true then cast it.
I am trying to convert these small math calls to Java from C# and just wanted to make sure that they operate the same way. I added one additional call as it is not supported in Java.
Here is code in C#
public override int CompareTo(object a)
{
EquationGenome Gene1 = this;
EquationGenome Gene2 = (EquationGenome)a;
return Math.Sign(Gene2.CurrentFitness - Gene1.CurrentFitness);
}
Java:
Notice the Math.Sign is not being called.
/**
* Compare to.
*/
public int compareTo(final Object a) {
final EquationGenome gene1 = this;
final EquationGenome gene2 = (EquationGenome) a;
return (int) ((-1.0) * (gene2.currentFitness - gene1.currentFitness));
}
And here is one to replicate C#'s 'next' with two int parameters in Java:
public static final int nextInt(final Random r, final int min, final int max) {
final int diff = max - min;
final int n = r.nextInt(diff);
return n + min;
}
Are these methods equivalent from C# to Java?
Why not just use Java's compareTo? This is assuming currentFitness is of type Integer and not the primitive type int. Otherwise you can just wrap it in Integer. This is not the most efficient method but it's more clear to me.
/**
* Compare to.
*/
public int compareTo(final Object a) {
final EquationGenome gene1 = this;
final EquationGenome gene2 = (EquationGenome) a;
return gene1.currentFitness.compareTo(gene2.currentFitness);
}
No, because Math.Sign in C# returns one of three values: -1 if the value is < 0, 0 if the value is equal to 0, and 1 if the value is greater than 0. It doesn't flip the sign by multiplying by -1 as you're doing in the Java code.
In C# the CompareTo function expects -1 to mean that the object on which it is called is less than the object being passed in. Since you're returning the sign of subtracting value 1 from value 2, this will be switched. I doubt this is what you want for your algorithm, given your Java code. Traditionally you would subtract value 2 from value 1 and use that sign.
If your Java version of EquationGenome implements the Comparable interface, you'll be able to take advantage of many Java APIs. This would alter your class to look like this:
final class EquationGenome
implements Comparable<EquationGenome>
{
...
public int compareTo(final EquationGenome gene2) ...
Then, what you are doing with the multiplication isn't clear. I assume the "natural order" is from most fit to least fit. Then I'd implement the comparison like this:
public int compareTo(final EquationGenome that) {
if (currentFitness == that.currentFitness) {
/* TODO: Add more tests if there are other properties that distinguish
* one EquationGenome from another (secondary sort keys). */
return 0;
} else
return (currentFitness > that.currentFitness) ? -1 : +1;
}
By convention, you should either implement the equals method to be "consistent" with your compareTo method, or clearly document your class to note the inconsistency. If you implement equals, you should also implement hashCode for consistency too.
public boolean equals(Object o) {
return o instanceof EquationGenome && compareTo((EquationGenome) o) == 0;
}
public int hashCode() {
return currentFitness;
}
The method for producing random numbers is alright, as long as you understand that max is excluded; the method generates random numbers from the half-open interval (min, max]. If you want to include max in the range, add one to diff.
I would write something like.
Note: You have be very careful using Comparator with mutable fields as this can have undesirable side effects.
public class EquationGenome implenents Comparable<EquationGenome> {
private final double currentFitness;
public EquationGenome(double currentFitness) {
this.currentFitness = currentFitness;
}
public int compareTo(EquationGenome eg) {
return Double.compareTo(currentFitness, eg.currentFitness);
}
}