Dynamic string concat in java - java

I want to contact two string.
Here my code
public class StringTest {
public String concat = "";
public String txt = "Hello "+concat;
protected void print() {
System.out.println("Output: " + txt);
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat = "World";
tb.print();
}
}
Output: Hello
But I need "Hello World".
It's possible ?
Conditions:
Should't re-assign variable (get/set , inside method)

For the execution to be dynamic you need a method.
public class StringTest {
public String concat = "";
private String txt() { return "Hello "+concat; }
protected void print() {
System.out.println("Output: " + txt());
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat = "World";
tb.print();
}
}
A field is only calculated when you write an assignment = but a method is evaluated each time it is called.

You can't change the constant String once declared in that way, and that too it is private, you can't access that variable outside.
You almost there but you have to change your Structure and concatination won't work that way.
public class StringTest {
private String txt = "Hello ";
protected void print() {
System.out.println("Output: " + txt);
}
protected void concat(String toBe) {
txt = txt + toBe;
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat("World");
tb.print();
}
}

The value in concat only will be assigned to txt variable when you create a StringText. Instantiate the correct from to concatenate value dynamically and assign this value inside print method like this
public String concat = "";
private String txt = "Hello ";
protected void print() {
txt = txt.concat(concat);
System.out.println("Output: " + txt);
}
public static void main(String[] args) {
StringTest tb = new StringTest();
tb.concat = "World";
tb.print();
}
each call to print method add value contained in concat variable.

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.

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

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

String method is undefined for type string?

When I try to compile/read Eclipse, I come up with the following error:
"The method titleCase(String) is undefined for the type String"
Why is that?
Below is code:
public class Main {
String titleCase(String s) {
String k = s.substring(0, 1).toUpperCase()
+ s.substring(1).toLowerCase();
return k;
}
public static void main(String args[]) {
String name;
do {
System.out.println("Enter a new name");
Scanner namescanner = new Scanner(System.in);
name = namescanner.nextLine();
String editednames = editednames.titleCase(name);
ArrayList<String> names = new ArrayList<String>();
names.add(editednames);
System.out.println(names);
} while (!(name.equalsIgnoreCase("Stop")));
}
}
Replace this:
String editednames = editednames.titleCase(name);
with this:
String editednames = titleCase(name);
Also, you should declare the titleCase() method static so you can call it from inside the static main method:
static String titleCase(String s) {
...

Categories