Java class Function doesnt work right - java

I have some very crazy Problem with my java class. The code will explan it:
This is my class:
public class myclass
{
public int myint;
public String mystring;
public myclass()
{
myint = 0;
mystring = "Test";
}
public void setStringInt(String s)
{
s = String.valueOf(myint);
}
public void somefunc()
{
setStringInt(mystring);
}
}
This is a Part of the MainActivity:
//...
public myclass thisismyclass;
public String mysecondstring;
//...
thisismyclass = new myclass();
thisismyclass.myint = 5;
thisismyclass.somefunc();
//...
The Output of thisismyclass.mystring is "Test". Why doesn't the code set it to "5"?
I tried something out. This works:
//...
thisismyclass.myint = 5;
thisismyclass.setStringInt(thisismyclass.mystring);
//...
But why did the other code not work?
mfg
lolxdfly
Edit: I am sorry.. I wrote it wrong.. I my code it was mystring!

s = String.valueOf(myint); within setStringInt does not change the string value in the caller.
This is because the string reference is passed by value, as are all Java function parameters.

Update your following method
public void setStringInt(String s)
{
s = String.valueOf(myint);
}
as follows
public void setStringInt(String s)
{
mystring = String.valueOf(myint);
}

You are not setting mystring value anywhere except in the constructor. Did you mean to write this:
public void setStringInt(String s)
{
mystring = String.valueOf(myint);
}

Java passes parameters by value.
When you pass that String reference into setStringInt and try to set it equal to the String value of the int state, you cannot alter the reference that's passed in. String is immutable, so you don't get what you want.
Your logic is rather convoluted. I can't tell what you want to do here. But here's my best guess:
public class MyClass
{
public int myint;
public String mystring;
public MyClass()
{
myint = 0;
mystring = "Test";
}
public void setStringInt(String s)
{
this.myint = Integer.valueOf(s);
this.mystring = s;
}
public void setStringInt(int i) {
this.myint = i;
this.mystring = Integer.parseInt(i);
}
public void somefunc()
{
setStringInt(myint);
}
}

You should correct this to:
public void somefunc()
{
setStringInt(mystring);
}
But as mentioned above these methods use call by value not call by references hence you won't change the callers variable.

Related

Java returning null and result

can someone take a look at this example and tell me why I get null10 as printed value instead of 10 only?
and is there and easier solution for this program without using global String variable "word"
public class UserInput {
public static String word;
public static class TextInput {
public void add(char c) {
word = word + c;
}
public static String getValue() {
return word;
}
}
public static class NumericInput extends TextInput {
#Override
public void add(char c) {
if (Character.isDigit(c)){
word = word + c;
}
}
}
public static void main(String[] args) {
TextInput input = new NumericInput();
input.add('1');
input.add('a');
input.add('0');
System.out.println(input.getValue());
}
}
EDIT: I need use inherits from TextInput
You need to give your static word field an initial value, otherwise it will default to being null. And when Java concatenates String objects, it will treat a null reference as the literal string "null". So you're effectively always starting off with the String "null".
If you give your class field a starting value of "" (empty string) then your code should do what you expect.
With regard to a better way of doing this, I would instead give the class a non-static field of type StringBuilder (and initialise it so that it's not null). Then your add method can simply append(c) the new characters to the StringBuilder field object, which will be more efficient than repeatedly using string concatenation (which is what you get with word + c).
You are not initializing input, so it is null. You need to initialize input first in order to make concatenating work.
So, use this:
public static String word = "";
Rather than using a static variable that is shared over all instances and children of the TextInput class, you should be using an instance variable.
You'll still have to initialize a non null value
That would look like
public static class TextInput {
protected String word;
public TextInput() {
this.word = "";
}
public void add(char c) {
word = word + c;
}
public String getValue() {
return word;
}
}
To better understand the problem, try your code with this
TextInput input = new TextInput();
input.add('a');
System.out.println(input.getValue());
TextInput input2 = new NumericInput();
input2.add('1');
input2.add('0');
System.out.println(input2.getValue());
Additional, see #Bobulous comment about using StringBuilder
You were not initializing the "word".
public class TextInput {
public static String word=""; // a lil change here
public static class TextInput {
public void add(char c) {
word += c;
}
public String getValue() {
return word;
}
}
public static class NumericInput extends TextInput {
public void add(char c) {
if (Character.isDigit(c)){
word += c;
}
}
}
public static void main(String[] args) {
NumericInput input = new NumericInput();
input.add('1');
input.add('a');
input.add('0');
System.out.print(input.getValue());
}
}

How to use a method append(String) onto itself in Java?

What I am trying to do is use method().method() in the following code:
public class Practice {
public static void main(String[] args){
Message m = new Message("test");
m.append("in").append("progress").append("...");
m.printMessage();
}
}
My class Message is this:
public class Message {
private String astring;
public void append(String test) {
astring += test;
}
public Message(String astring) {
this.astring = astring;
}
public void printMessage() {
System.out.println(astring);
}
}
How can I use .append().append()?
Change the method to the following:
public Message append(String test) {
astring += test;
return this;
}
Change
public void append(String test) {
astring += test;
}
into
public Message append(String test) {
astring += test;
return this;
}
In effect, each append() will return a pointer to the relevant Message object, allowing you to apply append() to that Message repeatedly in a chain.
I would use an internal char array to avoid O(N^2) String concatenation though. Alternately, append to an internal StringBuilder delegate object, whose append() method allows for the chained calls.

using class as method in java

How do I use (if possible) a class as a method parameter in Java?
public class validators() {
public int minLength(int l) {
// do something
}
}
public class formField() {
public void addField(String field, validators val) {
//do something
}
}
I want to be able to do the following :
addField("username", new validators() {
minLength(6);
});
Is it possible?
If you want to pass the current instance, you can use this.
Though I am not sure what are you trying to achieve yet the following code will compile fine:
public class Validators {
public int minLength(int l) {
// do something
return 0;
}
}
And
public class FormField {
public void addField(String field, Validators val) {
//do something
}
}
And then we can use it as:
public static void main(String[] args) {
FormField ff = new FormField();
ff.addField("username", new Validators() {
int result = minLength(6);
});
}
And it is making use of anonymous derived class.
If you want to pass a class instance as a parameter and define some value it'll use, you have to make this variable as attribute of the class and set it via the constuctor, like:
public class Validators {
int l;
public Validators(int l) {
this.l = l;
}
public int minLength() {
// do something
//here you can use l variable
}
}
And
public class FormField {
public void addField(String field, Validators val) {
//do something
}
}
Then you can call it like:
addField("username", new Validators(6)) {
...
And may be you have to take a look at Java naming conventions

Is it possible to update a reference in a method?

I have asked this question here. I will try to make this one more specific.
class Example {
public static void main(String[] args) {
A a = null;
load(a);
System.out.println(a.toString());
// outcome is null pointer exception
}
private static void load(A a) {
a = new A();
}
}
class A {
public void String toString() {
return "Hello, world!"
}
}
So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.
Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = new A("outer");
System.out.println(a[0].toString());
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
EXAMPLE 2:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = null; // not needed, it is null anyway
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.
As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {
public static void main(String[] args) {
A[] aArray=new A[1];
load(aArray);
System.out.println(aArray[0].toString());
// outcome is Hello, world!
}
private static void load(A[] aArray2) {
aArray2[0] = new A();
}
}
class A {
public String toString() {
return "Hello, world!";
}
}
You could just have:
public static void main(String[] args) {
A a = load();
}
private static A load() {
return new A();
}
No you can't.
In java everything is passed as value not as reference.
I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}

Delegating method calls using variable number of arguments

This question came up in the course of my work programming; it's become irrelevant to the current task, but I'm still curious if anyone has an answer.
In Java 1.5 and up you can have a method signature using a variable number of arguments, with an ellipsis syntax:
public void run(Foo... foos) {
if (foos != null) {
for (Foo foo: foos) { //converted from array notation using autoboxing
foo.bar();
}
}
}
Suppose I want to do some operation on each foo in the foos list, and then delegate this call to some field on my object, preserving the same API. How can I do it? What I want is this:
public void run(Foo... foos) {
MyFoo[] myFoos = null;
if (foos != null) {
myFoos = new MyFoo[foos.length];
for (int i = 0; i < foos.length; i++) {
myFoos[i] = wrap(foos[i]);
}
}
run(myFoos);
}
public void run(MyFoo... myFoos) {
if (myFoos!= null) {
for (MyFoo myFoo: myFoos) { //converted from array notation using autoboxing
myFoo.bar();
}
}
}
This doesn't compile. How can I accomplish this (passing a variable number of MyFoo's to the run(MyFoo...) method)?
Is this what you want?
public class VarArgsTest {
public static class Foo {}
public static class MyFoo extends Foo {
public MyFoo(Foo foo) {}
}
public static void func(Foo... foos) {
MyFoo [] myfoos = new MyFoo[foos.length];
int i=0;
for (Foo foo : foos) {
myfoos[i++] = new MyFoo(foo);
}
func(myfoos);
}
public static void func(MyFoo... myfoos) {
for (MyFoo m : myfoos) {
System.out.println(m);
}
}
public static void main(String [] args) throws Exception {
func(new Foo(), new Foo(), new Foo());
}
}
I tried it and did NOT get a compile error. What is the actual error you are seeing? Here is the code I used. Perhaps i did something different:
public class MultipleArgs {
public static void main(String [] args){
run(new Foo("foo1"), new Foo("foo2"), new Foo("foo3"));
}
public static void run(Foo... foos){
MyFoo[] myFoos = null;
if (foos != null) {
myFoos = new MyFoo[foos.length];
for (int i = 0; i < foos.length; i++) {
myFoos[i] = wrap(foos[i]);
}
}
run(myFoos);
}
public static void run(MyFoo... myFoos){
if (myFoos!= null) {
for (MyFoo myFoo: myFoos) {
myFoo.bar();
}
}
}
private static class Foo {
public final String s;
public Foo(String s){
this.s = s;
}
#Override
public String toString(){
return s;
}
}
private static class MyFoo{
private final String s;
public MyFoo(String s){
this.s = s;
}
public void bar(){
System.out.println(s);
}
#Override
public String toString(){
return s;
}
}
private static MyFoo wrap(Foo foo){
return new MyFoo(foo.s);
}
}
This doesn't answer your question; it's incidental, but you don't need the null test. Here's proof:
public class VarargsTest extends TestCase {
public void testVarargs() throws Exception {
assertEquals(0, fn());
}
private int fn(String...strings) {
return strings.length;
}
}
If the method is called without any arguments, the varargs list is an empty array, not null.
I think the actual solution to your question would be to rename the second function.
use java reflections.

Categories