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;
}
}
Related
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());
}
}
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.
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;
}
}
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) {
...
have two strings, String1 = hello String2 = world, I want to call a class Hello and send to the two strings. The class should return a boolean value and a string. If the boolean is true it should do the followig:
System.out.println("Hello to you too!");
Can someone help me out with this code?
First, a terminology problem: you cannot "call a class." You can call a method on a class, such as:
someObject.someMethod(string1, string2);
More to the point, you can't return two different values from a method. You could certainly store two different values in the object and return them from different methods, though. Perhaps a class like:
public class Foo {
protected boolean booleanThing;
protected String stringThing;
public void yourMethod(String string1, String string2) {
// Do processing
this.booleanThing = true;
this.stringThing = "Bar";
}
public String getString() {
return this.stringThing;
}
public boolean getBoolean() {
return this.booleanThing;
}
}
Which would be used as:
someObject.yourMethod(string1, string2);
boolean b = someObject.getBoolean();
String s = someObject.getString();
Having said all that, though, this may not at all be the best way to solve your actual problem. Perhaps you can explain better what you're trying to accomplish. Perhaps throwing an Exception is better than trying to return a boolean, or perhaps there's another solution entirely.
The more detail we have, the better.
You should review your definition of classes but for now I'll assume this is what you meant, comment if this isn't what your looking for:
public class Hello {
private final String first;
private final String second;
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
Hello h = new Hello(s1,s2);
if(h.isHelloWorld()) {
System.out.println("Hello to you too!");
}
}
private Hello(String first, String second) {
this.first = first;
this.second = second;
}
private boolean isHelloWorld() {
return (first.equals("Hello") && second.equals("World"));
//If that scares you then do this instead:
/**
if(first.equals("Hello") && second.equals("World") {
return true;
} else { return false; }
**/
}
}
When you run this program it will always print "Hello to you too!", if you change s1 or s2 it won't print anything.
public class Hello{
boolean val = false;
String str = "";
public Hello(String a, String b){
if(a == "hello" && b == "world"){
this.val = true;
this.str = "hello to you too";
}
}
public static void main(String args[]){
String a = "hello";
String b = "world";
Hello hello = new Hello(a,b);
if(hello.val == true)
System.out.println(hello.str);
}
}