This question already has answers here:
String is immutable. What exactly is the meaning? [duplicate]
(19 answers)
Closed 6 years ago.
As far as I know a String in Java is not a primitive but an object. Java also has some shortcuts to make working with Strings easier, so that we don't have to use new String() or joining two Strings with the + operator.
So I wrote the following little test:
package programming.project.test;
public class JavaStringTests {
public static void main(String[] args) {
String test1 = new String("uno dos ");
MyString test2 = new MyString("uno dos ");
System.out.println(test1);
System.out.println(test2);
extendMe(test1);
extendMe(test2);
//primitive-like behavior?
System.out.println("(String) -> " + test1);
//expected if String is not a primitive
System.out.println("(MyString) -> " + test2);
}
private static void extendMe(MyString blubb) {
blubb.add("tres ");
}
private static void extendMe(String blubb) {
blubb = blubb + "tres ";
}
}
The MyString class:
public class MyString {
String str;
public MyString(String str) {
this.str = str;
}
public String toString() {
return str;
}
public void add(String addme) {
str += addme;
}
}
Produces the following output:
uno dos
uno dos
(String) -> uno dos
(MyString) -> uno dos tres
If String is an object, why does it automatically create a new instance of it when passed as an argument? Is String some sort of primitive-like object, something in between primitive and object?
extendMe doesn't do what you think it does. Strings are immutable, they can't be changed. String.concat() doesn't change the string, it returns a new instance, which you discard in your code.
private static void extendMe(String blubb) {
blubb.concat("tres ");
}
Here String.concat returns a new String with concated value.
Where as
private static void extendMe(MyString blubb) {
blubb.concat("tres ");
}
Here you are adding the concated value to your internal str state.
Related
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 2 years ago.
I am having trouble figuring out how to ge the program to reject inputs that contain only white spaces and changing it into the string "N/A" with the trim() method. I have also tried to use the replaceAll() methods, but they aren't working either.
Here is the program:
public class Object1
{
//attributes
private String name;
//symbolic constant
private final String NA = "N/A";
// getter/setter methods for name
public void setName(String n)
{
if (n.trim() != "")
name = n.trim();
else
name = NA;
}
public String getName()
{
return name.trim();
}
public Object1()
{
name = NA;
}
}
public class Object2
{
public static void main(String[] args)
{
// create object
Object1 x;
x = new Object1();
// the name of the object
a.setName(" ");
// report the name of the object
System.out.println("The name of the object is: " + x.getName());
}
}
The output for the name would remain blank instead of changing into the string "N/A"
Does anyone know how to fix this?
The behavior of the if statement, if (n.trim() != ""), is probably not what you are expecting. You should instead use: if (n.trim().equals("")).
This question already has answers here:
How to use the toString method in Java?
(13 answers)
Closed 3 years ago.
I've got two classes, below. When I run the class TestSimple, it prints out "blueblueblue is blue repeated". That print statement is executed as System.out.println(item) which is an instance of the Simple() class. I've never seen an object print out as a phrase before, and I'm having a hard time pinning down why this is happening.
I see that there is a method in the Simple class called toString which should print this out when it is called, but I don't see that method called anywhere. What's going on here?
public class Simple {
private String word;
private String phrase;
public Simple(int number, String w) {
word = w;
phrase = mystery(number, w);
}
private String mystery(int num, String s) {
String answer = "";
for (int k=0; k<num; k++) {
answer = answer + s;
}
return answer;
}
public String toString() {
return phrase + " is " + word + " repeated";
}
}
And
public class TestSimple{
public void print() {
Simple item = new Simple(3, "blue");
System.out.println(item);
}
public static void main(String[] args) {
new TestSimple().print();
}
}
System.out is a PrintStream, PrintStream.println(Object) (from the linked Javadoc) calls at first String.valueOf(x) to get the printed object's string value and String.valueOf(Object) returns the value of obj.toString()
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Please help to escape NullPointExeption error in the String.split() method in Java. String got from the user entering. It can't compile. In the case of hard code of the variable all is fine.
Class Calculator:
public class Calculator {
private String mathExpression;
public void setMathExpression(String mathExpression) {
this.mathExpression = mathExpression;
}
private String[] parts = mathExpression.split(" ");
private String firstNumber1 = parts[0];
//add other elements to the array...
public void calculatorRun() {
//using all the variables
}
}
Class CalculatorTest:
public class CalculatorTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String userAnswer = "y";
Calculator calculator = new Calculator();
while (userAnswer.equals("y")) {
System.out.print("Please put the math expression: ");
calculator.setMathExpression(scanner.nextLine());
calculator.calculatorRun();
}
}
}
You need to put your split call into a method otherwise it will be executed as soon as you instantiate the Calculator. See this
private String[] parts = mathExpression.split(" ");
private String firstNumber1 = parts[0];
put both into the method calculatorRun
Make sure that mathExpression not empty or null
if(mathExpression!= null && !mathExpression.isEmpty()) {
private String[] parts = mathExpression.split(" ");
private String firstNumber1 = parts[0];
/* other code */ }
How would I create a method that has the input of a string and output of all the strings that were input into it like a super string?
for example in the main class:
a= "fido"
b= "rufus"
c= "dog"
superString(a);
superString(b);
superString(c);
System.out.println(superString()); should be "fidorufusdog"
so far I have=
public static String superString (String sb) {
StringBuilder ssb = new StringBuilder(32);
ssb = ssb.append(sb);
return ssb.toString();
}
My code below is what I am working on for a stock simulator:
public class Operators {
public static void operate(double price, double low, String company){
double percent = (price/low-1)*100;
double rpercent = Math.round(percent * 100.0) / 100.0;
StringBuilder sb = new StringBuilder(32);
if(rpercent <= 10) {
sb.append(company + " is trading at:");
sb.append("the current price is: " + price);
sb.append("the 52 week low is: " + low);
sb.append("percent of 52 week low is: " + rpercent);
}
}
}
The operate method is called in a for loop in my main method 506 times and I would like to take all 506 sb string and create a super string of all the results
I hope I do not underestimate the depth of the question or have your question wrong, but to me it sounds like you are asking for the static keyword?
class SomeClass {
static StringBuilder accumulator = new StringBuilder();
public String superString (String sb) {
SomeClass.accumulator.append(sb);
return ssb.toString();
}
}
This is simple usecase of the Java static keyword. Since accumulator is declared static there will be a single instance of the variable. And this single instance will be accessed by instances of the class SomeClass. For example:
SomeClass a;
SomeClass b;
a.superString("aaa");
b.superString("bbb");
// now accumulator.toString() returns "aaabbb"
Declare that string builder as the static member containing class and initialize it only once
static StringBuilder ssb;
public static String superString (String sb) {
if(ssb == null)
ssb = new StringBuilder(32);
ssb = ssb.append(sb);
return ssb.toString();
}
For this kind of probelm you've two choice :
Simple : create a static variable in the Java class, and manipulate it.
improve : create a design model which support your need.
Ex 1 :
public class Operators {
private static String text ="";
public static String superString(String sb) {
if (sb != null) {
text = text.concat(sb);
}
return text;
}
}
Ex 2 : you can use a Collecion or a List of strings.
This is poor OOP design. You would be much better off creating a class for Stock objects and overriding toString in the Stock class(or creating some other simple output method). Then add each instance of Stock to an array and call the each object's toString (or other output method you defined).
Why the next method does not print nothing but when i change the String s to array , it works Properly?
not working:
public String toString(){
//In-Order - left,root,right.
String s ="";
toString(root,s);
return s;
}
public void toString(BSTNode root,String s){
if (root!=null){
toString(root.left,s);
s=s+","+ root.data;
toString(root.right,s);
}
}
working:
public String toString(){
//In-Order - left,root,right.
String[] s =new String[1];
s[0]="";
toString(root,s);
return s[0];
}
public void toString(BSTNode root,String[] s){
if (root!=null){
toString(root.left,s);
s[0]=s[0]+","+ root.data;
toString(root.right,s);
}
When you create an array of String and pass, basically it is creating String object (like we create using new operator). So it sues the same reference and modifies the String as you work on it. But in the former case, it treat them as two separate variable like the primitive type are handled in java.
public class StringTest {
public static void main(String[] args) {
String s[] = new String[1];
System.out.println("before: "+s[0]);
updateString(s);
System.out.println("after: " + s[0]);
}
private static void updateString(String s[]) {
s[0] = "New String";
}
}
output of the program is:
before: null
after: New String
Otherwise, it does not print anything.
The reason is, that String is not a normal Reference-Type. If you change a String a new String is generated and the modified one is returned (String is immutable). (See String.replace() for example)
If you change your method to look like this, it should probably work:
public String toString(){
//In-Order - left,root,right.
return toString(root,s);
}
public String toString(BSTNode root,String s){
if (root!=null){
return toString(root.right,toString(root.left,s)+","+root.data);
}
return "";
}
Strings in java are immutable, this means that every time you assign them a new value a new object is actually created and the reference changes.