how to use a variable in the entire java class [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am quite new to java and I have two questions!
First how can I make a variable usable entire a java class?
This is part of my method:
public void createID() {
ObjectId Id = (ObjectId) documentClient.get("_id");
StringID = clientId.toString();
}
And I want to use StringID in another method but it is either null (when I create public StringID =null in the main class) or not known.
My other question is that when I change the createID() to
public String createID() {
ObjectId Id = (ObjectId) documentCleint.get("_id");
StringID = clientId.toString();
return Id;
}
It says that the method should be void! I am looking for a way to return the variable from my method.
Any idea?
Thanks

First of all, in order to define a class variable, you should define it under the class definition. For example
public class Example{
private int classVariable; // Variable to be reached from any method in class.
private void someMethod(){
}
}
In your clientID method, you assigned return type as String, but you are returning objectId. I guess you meant to return StringID variable.
Also I guess, documentCleint.get("_id");
should have been documentClient.get("_id");
You should try after correcting these syntax issues.

Question 1 :
First how can I make a variable usable entire a java class?
That createID limited to the scope of createID() method. To avail that in whole class, move them to top. (instance members).
Question 2 :
It says that the method should be void!
public **String** createID() {
ObjectId **Id** = (ObjectId) documentCleint.get("_id");
StringID = clientId.toString();
return **Id**;
}
That is not the exact error. Return type is mistamatch there. That method should return a String but you are returning Id which is of type ObjectId. You might want to return StringID

To use a variable in more than one method you need to use a global variable, to declare it simply declare it outside any method inside the class.
As for the second part of your question, it looks to me that you are not returning a string as id is not declared as a string

Related

How do you know you need to define a new method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
We want each method to do a distinct task, right? How do you draw that line?
For example, say I have a class with an int array that I need to have set to certain numbers when the class is constructed. Should I loop through the array right there or make a separate method for what is ultimately a simple task?
Make a new method whenever you have a sensible name for one. When you have a good name for a new method, it suggests that what you're doing there is a separate task and potentially reusable.
Note that this is just a rule of thumb and may not apply to all cases. Another rule is to make a new method if your current method is too long (I've heard 48 lines cited as an upper bound).
Here is a sample class that I hope points out what you are looking for:
class Sample {
private int[] myInts = null;
// we need a constructor if we are going to pass in stuff
// if we don't provide a constructor, java will create one for us
public Sample(int[] inputs) {
// I can just set this array, I don't need a separate method to
// loop through and create a new array and copy the old one.
myInts = inputs;
}
// here we are going to do something discreet, so I need a new method.
public int add() {
int returnValue = 0;
for (int i = 0; i < myInts.length; i++) {
returnValue += myInts[i];
}
return returnValue;
} // end my "add()" method
} // end my Sample class

Using reference to "this" object from member variable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am asked to say what does this code do but I really cannot figure it out.
I've tried to execute it in netbeans and got the answer 6 but really cannot understand why.
public class Quattro {
int x = 5;
Quattro s = this;
Quattro f(){
s.s.s.x++;
return s;
}
void g(){System.out.println(x);}
public static void main (String[] args){
Quattro a4 = new Quattro();
a4.f().g();
}
}
Question 1: What does Quattro s = this; do? Am I declarind a pointer to my self? If so, it means that I can write
Quattro f(){
s.s.s.x++;
return s;
}
or even
Quattro f(){
s.s.s.s.s.s.s.s.x++;
return s;
}
and I'll always get the same result because I'm in a loop?
Question 2: I do not understand what a4.f().g(); does... seems so weird to me.
If you assign this reference to a member variable, you have a recursion. Yes, it doesn't matter how many s's you'll add, because they are always the same object, which is this object. It's the same as if you wrote:
this.this.this.this.this.this.x++;
Function f() returns reference to this object after doing some other operations on it. It's a common design pattern in Java, called builder. Adding ability to do a4.f().g(); to a class is called method chaining. In other words, f() is this object at the end of the call, just like s is, so you can do:
a1.f().f().f().f().f().f();
And it means you just called f() function from a1 object 6 times.

Remove all pointers to an object in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
OK, here is the thing. I have multiple pointers to an object and I want to remove both of them. I have simplified it, below, so don't bother asking why on earth I would try the thing below :)
String first = "ASSIGNED";
String second = test;
second = null;
System.out.println(first);
In the example above, the output still results in "ASSIGNED". However, I want first to be no longer assigned. In the example above, it is easy, by setting it to null, but in my real example, this is not possible (first being passed into a method, where I want to remove the assingment).
EDIT:
So, I guess the question is, if it is possible to remove all pointers to a given object.
Apparently it was a bit vague what I was asking, so let's try to give a better example:
String first = "Assigned";
doSomethingAndRemove(first);
public void Remove(String string) {
//Do something
//...and remove
string = null;
}
The thing is that first still is referencing to "Assigned"... But from what I read in the answers so far, there is no way around this?
No, it is not possible to remove all "pointers" to a given object, for one because Java doesn't have pointers, they are called references.
Neither Java nor the JVM knows all references to a given object. This is why the garbage collector has to scan everything to find unused objects.
You have to clear references, and you cannot clear a reference variable that was used to pass a parameter from within the called method, because Java is pass-by-value, meaning the reference (not the object) is copied.
Example:
public static void main(String[] args) {
String var1 = "Hello";
doSomething(var1); // The value of var1 is copied to param1
}
private static void doSomething(String param1) {
param1 = null; // Only clears the param1 reference
var1 = null; // Cannot do this, because doSomething() does not have access to var1
}
Only code in method main can change the reference value of var1.
Update
If you want method doSomething to be able to update var1 to a different value, incl. null, then a common practice is to simply return the updated value.
public static void main(String[] args) {
String var1 = "Hello";
var1 = doSomething(var1);
}
private static void doSomething(String param1) {
// do something with param1
return "Goodbye";
}
This of course only works if you didn't already have a different kind of return value, and only works for a single value.
Output (and In/Out) parameters can be simulated in Java using the holder pattern, e.g. see Output Parameters in Java
C# can do it using ref, but Java cannot. The following is the last resort in Java if you must do it.
public class Nullify
{
public static void main(String[] args) {
String[] first = { "ASSIGNED" };
System.out.println("first[0] = " + first[0]);
nullify(first);
System.out.println("first[0] = " + first[0]);
}
private static void nullify(String[] array) {
array[0] = null;
}
}
String s=ASSIGNED;
String s2=s;
String s2=null; // means just remove the link s2 is pointing to
System.out.println(s); // print ASSIGNED
seen the picture.
if you want to remove you have to assign null to all individual objects.

Java storing method into arraylist [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Currently I am storing method of page into array. But I want to store these method into arraylist but not sure what is wrong with it.
WizardPage[] pages={pageone(), pagetwo(), pagethree()};
versus
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(pageone());
pageStore.add(pagetwo());
pageStore.add(pagethree());
public WizardPage pageone() {
WizardPage pageone = new WizardPage("one","page 1");
Do something~
return pageone;
}
public WizardPage pagetwo() {
WizardPage pageone = new WizardPage("two","page 2");
Do something~
return pagetwo;
}
public WizardPage pagethree() {
WizardPage pageone = new WizardPage("three","page 3");
Do something~
return pagethree;
}
if you want to store the methods instead of their return values then
instead of
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(pageone());
pageStore.add(pagetwo());
pageStore.add(pagethree());
try
List<Method> pageStore = new ArrayList<Method>();
try {
pageStore.add(this.getClass().getMethod("pageone"));
pageStore.add(this.getClass().getMethod("pagetwo"));
pageStore.add(this.getClass().getMethod("pagethree"));
} catch ...
}
On an different note than the fact that you aren't actually storing the methods, but their return types, you've got this
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(pageone());
pageStore.add(pagetwo());
pageStore.add(pagethree());
Since all the methods pageX() are all instance methods, you need an instance to call them on. Assuming the class those methods appear in is called WizardBook, you would need something like
WizardBook book = new WizardBook();
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(book.pageone());
pageStore.add(book.pagetwo());
pageStore.add(book.pagethree());
Or make the methods static.
...unless of course you are running it within an instance member context.
In Java, methods are not objects. You can't store methods in an array or ArrayList.
Fist point to say You cannot store a method, you can only store its return value.
I don't see any problem in storing the returned values into a list.
Store an array of objects. Objects have methods, so you can then access (either call or for special purposes use reflection) the methods.
What you are trying to do is unclear, but it looks as though you want 3 objects of class WizardPage, with some String fields, and which perhaps has a method like void doPageUpdateStuff(). On the other hand, maybe all the work can be done in the constructor.

How parameter.method() method works? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Well, i was thinking about that kind of methods.
They dont recive parameters, but they work with them.
An example: .replace(Char, Char) of String API, it works with a String followed by a dot.
Like:
String test = "= Text = without = equals";
String output = test.replace("=","");
How it works without receive the parameter test?
I'm just being curious, want to do a method like these.
Sorry for my bad english!
Thanks.
Let's say you build a new type of String, that only does replace stuff (why not?!):
public class MyString {
private final String s;
public MyString(String s) {
this.s = s;
}
public String replace(String search, String replace) {
return s.replace(search, replace);
}
}
Now you can call it like this:
MyString myString = new MyString("= Text = without = equals");
String output = myString.replace("=", "");
Et voila, you have done the same "trick"! And you can see how it works: your MyString object keeps some data internally (the s variable) and can access that data from its methods.
These are instance methods, which means that they require an instantiated class object to operate. So, the string class knows the value of test in your example, because it has access to the instantiated data.
To create these types of methods, simply define them within your class and do not mark them as static.
String is an object. The class definition is part of the Java standard library. That definition includes the replace method.
Since String is a final class you can not subclass it to add additional methods. So you can not do what you are trying to do.

Categories

Resources