Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Steven Wood   on Jan 11 In Java Category.

  
Question Answered By: Aylin Kaya   on Jan 11

In Java there are two general types of data: primitive types
(int, double, char, etc.) and objects.
Objects are really pointers, and because string  is a class,
any string in Java is a pointer.

Every variable in Java is passed by value, never by reference.
When you pass  a primitive type, this concept is clear, but
when you pass a class, this concept is not so clear.

So I will explain this thing "What happens when you pass an
object as a parameter of a function?"
- The pointer is passed by value, so you can't change the pointer,
assigning things like: c = new MyClass(...) or c = "my string",
- But you can change its content, accesing its attributes or
its methods.

Here is an example of what you can do:

*** MyClass.java
public class  MyClass {
private int code;
private String name;

public MyClass (int acode, String aname) {
setCode (acode);
setName (aname);
}
public void  setCode (int acode) { code  = acode; }
public int getCode () { return code; }
public void setName (String aname) { name = aname; }
public String getName () { return name; }
}

*** MyApp.java
public class MyApp {
public static  void anyMethod (MyClass p) {
p.setCode (101);
p.setName ("Any other name");
}

public static void main  (String[] args) {
MyClass c = new MyClass (1,"Any name");
System.out.println ("code=" + c.getCode() + ", name=" + c.getName());
anyMethod (c);
System.out.println ("code=" + c.getCode() + ", name=" + c.getName());
}
}

Share: 

 

This Question has 4 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Pass By Reference Or get search suggestion and latest updates.


Tagged: