Java returning null and result - java

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());
}
}

Related

New to java; how do I make the String static within conditionals?

public class testing {
public static void main(String[] args)
{
boolean a = true;
if (a) {
public static String word = " ";
}
else if (a == false) {
public static String word = "not";
}
System.out.println(word);
}
}
Instead of printing the value, it tells me "Illegal modifier for the variable word; only final is permitted.
I tried to use public static final String word = "not";
but I still got an error saying that it is wrong.
The variable should be created outside of your main:
public class Testing {
public static String word;
public static void main(String[] args)
{
boolean a = true;
if (a) {
word = " ";
} else {
word = "not";
}
System.out.println(word);
}
}
Alternatively you can create a variable inside you main as well.
public class Testing {
public static void main(String[] args)
{
boolean a = true;
String word;
if (a) {
word = " ";
} else {
word = "not";
}
System.out.println(word);
}
}
When variables, blocks or methods are made static, they are made available during load time. Rest all reserves memory during run time. All the local variables created inside a static method are present in the method stack, which as a package is already present during load time. So creating a static variable inside method, be it be static or non-static method, is not allowed.

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.

replace(String, String) | how to do this with stringBuilder

I am trying to change the value of a final String variable to "#mango" without re-assignment, preferably by using StringBuffer and StringBuilder:
public static void main(String[] args) {
String finaal = "i am #apple";
//Case 1: Apache Commons Lang 3
StringUtils.replace(finaal, "#apple", "#mango");
System.out.println(finaal);//--expected "i am #mango" but actual "i am #apple"
//Case 2 :
finaal.replace("#apple", "#mango");
System.out.println(finaal);//--expected "i am #mango" actual "i am #mango" but need re-assignment here
}
Strings are immutable, the result of the replace is returned from the replace method. If you want to do a replace without re-assign you need to wrap your string in another class.
public static void main (String[] args) {
StringHolder stringHolder = new StringHolder("#apple");
stringHolder.replace("#apple", "#mango");
System.out.println(stringHolder);
}
private static class StringHolder {
private String str;
public StringHolder(String str) {
this.str = str;
}
public void replace(String from, String to) {
String newStr = str.replace(from, to);
this.str = newStr;
}
public String toString() {
return str;
}
}

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;
}
}

Java class Function doesnt work right

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.

Categories