String 7 « string « Java Data Type Q&A





1. Help in Strings    coderanch.com

Hi, Welcome to JavaRanch! Strings are indeed immutable. There are no methods that allow you to change the value of a String object. All the methods like toLowerCase() and concat() that might appear to change the string they're called on, do not actually change it; they create a new String instead. So for instance, the concat() method returns a new string ...

2. String search/replace.    coderanch.com

Earnest, thanks yet again. R U psychic, or WHAT? Without even seeing my code you knew I was using the != null test in my while loop. I think I'll need an additional book, the 2 I have are just not cutting it. Que's "JAVA Quick Reference", Michael Afergan, & the "Beginning Programming with Java for Dummies", Barry Burd, NEITHER tell ...

3. All about Strings    coderanch.com

Hi, Welcome to JavaRanch! In the first case (without the new) the String comes from a pool of unique strings held internally by the JVM; literal Strings are put into this pool when the classes defining them are loaded. In the second case, a new String object is allocated at that point while the program is executing.

4. == and String objects    coderanch.com

It depends on what class b1 is and whether that class provides any guarantees about what its String method does. But in general, there are no guarantees about whether toString() will create a new String or reuse an existing one. You could look at the source code for b1's class to find out exactly what happens in this case, but usually ...

5. Saving strings    coderanch.com

Sure, you just need to think a bit about the scope of the data, which means when and where you want to use it. For example, here's method scope. I declare a string, get a value and use it all in one method. When I leave the method, it goes "out of scope" and is no longer available. String name = ...

6. String And instanceof?    coderanch.com

I was under assumption that String is just another object type and instanceof can be used to test if a particular object is of a particular type or descended from that type. When I try to test if an object is of type String with instanceof operator(haven't found need for this, but still think concept should work) receive compile error as ...

7. How to get address of String object?    coderanch.com

You can't, at least not in the Java language (or in any code running on the JVM itself.) Java's pointers aren't addresses. The concept of pointer/address equivalence is not part of the JVM architecture. In C/C++ code using the Java Native Interface (JNI), which Java code can call out to, you can get a more or less opaque handle to the ...

8. string reversal problem    coderanch.com

class c11 { public static void main(String args[]) { } public static String reverse( String s ) { String text = "Hello"; String reversedTextString = ""; char reversedText[] = new char[text.length()]; for (int i = 0; i < text.length(); i++) { reversedText[i] = text.charAt(text.length() - i - 1); reversedTextString = new String(reversedText); } System.out.println(reversedTextString); return s; }

9. Query on String class ?    coderanch.com

What's the problem with using a temporary variable? If you are convinced that you don't want to use one, the only way that I can think of is to define a separator character e.g. '#', "append" it to the end of one of the Strings followed by the other String and then parse the required bit of the compound String into ...





10. strings inside object inside object    coderanch.com

I am having difficulties getting strings to output when they are in an object which is inside another object. Best i have done so far is display the pointer for the 2nd object which is not very useful. Ill ignore the first object for the moment because i am able to access the 2nd object. Ill call the 2nd object "secondObject" ...

11. garbage collection and String type    coderanch.com

It is my understanding that literal String objects are a special case. There is a special pool of these in the JVM, without duplication. These will not get garbage-collected, I think. However, other String objects, created in any other way (deserialised, created from char[], created by concatenation etc.) are eligible for garbage collection, like any other object. When no-one is referencing ...

12. String question!    coderanch.com

13. String Class Method    coderanch.com

14. the "!"(not) in string conditions    coderanch.com

hello, i recently encountered a problem with "!"(not) and strings. Does this work? ex. if (!(strName == "")) It doesn't give me a compiliation error. I played around with it and I think "!"(not) with strings do not work. This condition is treated as if there was no "!"(not).... Am i right? Is there an alternative way to solve this? thanks ...

15. String Class    coderanch.com

16. modificating strings    coderanch.com





17. String question    coderanch.com

public class StringIdentity { public static void main(String[] args) { String s1 = new String("abcd"); String s2 = new String("abcd"); String s3 = "abcd"; String s4 = "abcd"; System.out.println("s1 == s2 : " + (s1 == s2)); System.out.println("s3 == s4 : " + (s3 == s4)); System.out.println("s1 == s3 : " + (s1 == s3)); } }

18. String arguments    coderanch.com

I'm really stuck. I only want this program accept integer input. Any other input like a char I want it to display a message that it is the wrong type of input and display the input in question. Here is what I've got so far. Any help would be appreciated. Thanks, Marie //ExceptDemo1b.java public class ExceptDemo1b { //Main Method with three ...

19. NullPointerException when using String[]    coderanch.com

Hi. I make reference to my earlier thread in this forum: http://www.coderanch.com/t/395645/java/java/howto-return-multiple-values-parent As stated earlier, I am trying to pass parameters between applets. For testing, I've created a class for holding the data that needed to be passed back. It is an array. import java.io.Serializable; /** * TXDetail object encapsulated a single record */ public class TXDetailData { public int var_counter ...

22. Naming Objects with Strings?    coderanch.com

String testName = "testName" int testName = 14 Hi Jason, I have not done a lot of basic, but I think that variables had more or less hidden extensions to denote their different types. I think Strings had a $ extension and so on. The two variables you quote above are actually stored in two different places and would take up ...

23. if (String == String)    coderanch.com

Hello... I'm having troubles comparing strings in an if statement... I have a file that I have read (line by line) and then tokenized with StringTokenizer. Now, the second token of every line is either the letter P or S (a sales spreadsheet, P stands for produced, and S for sales). But, when I take the token and assign it to ...

24. working within strings    coderanch.com

Ok I've spent the last couple of days trying to figure this one out. Heres what I'm trying to do: I have a string 'boothzan'. I have a set of rules to apply to this string 'z only appears at the beginning or end of a word' How do I have it go through the word and take out the letter ...

25. alphabetize a string    coderanch.com

Here is a start on the code for an application with a method that will alphabetize a string using the following signature: public static String sort(String s) I gave it a go, but I am so confused at this point I'm not sure what to do. The charArray string is not being recognized? Any help would be appreciated. I get really ...

26. Alphabetize a string. (again)    coderanch.com

This is a post in response to This one about alphabetising a String. The code in the original post of this thread was modified, so now I'm commenting on the changes. I'm doing this rather than adding to the original thread because on the original thread code changes were made after comments were added. This makes the thread a little nonsensical. ...

27. Quicky String Question    coderanch.com

Or, along the same lines as the last post, become familiar with the so-called "short-circuit" operators in Java, || and &&. These are called short-circuit operators because you can short-circuit the remainder of a logical operation using them. Example: boolean foo() { System.out.println( "foo!" ); return true; } boolean x = false; if( x && foo() ) { System.out.println( "bar!" ); ...

28. Strings    coderanch.com

Maha: Since you are a beginner, I thought it would be useful to show a simple way to see if a string contains a digit. Although there are more efficient methods of accomplishing this task, the following code is easy to understand and will give you a starting point. class StrChk { public static void main(String args[]) { String str = ...

29. calculate from String    coderanch.com

Hi, what you need, is a math expression parser. The grammar for simple arithmetic expression looks something like this: EXPR = TERM {("+" | "-") TERM} * TERM ::= FAC {("*" | "/") FAC} * FAC ::= UNARY {"^" NUM} * UNARY ::= ["-"] PRIMARY * PRIMARY ::= NUM | "(" EXPR ")" * NUM ::= DIGITS ["." DIGITS] ["e" ["+" ...

30. Query about String ??    coderanch.com

Hi, That means if i declare in any method String str = new String("abc"); or String str1 = "abc"; then at every call of this method it will create a new object of String class and allocate a new space for this object in the heap memory.Am I right ? Thanks & Regards Bikash

31. String Vs Object    coderanch.com

32. doubt in String    coderanch.com

Hi jai, Jvm internaly maintains a string pool, so when you assign a value to a string variable without the new operator jvm first searches for the string in the pool if it finds one then it will return the reference of that string else it will create a new string with the specified value and returns the reference. By using ...

33. Strings...    coderanch.com

34. string translation problem    coderanch.com

Hey there, First off I'm really new to Java so please bear with me. I need to translate a line of text from one form to another. An example line segment has the following format: " step(sent(1,A,B,vars(Na,Rv,ped(pk(B),cat(Na,A)))))" This means that at step 1, A sends to B that which is contained in vars() i.e. Na, Rv and encryption of Na and ...

35. arraycopy() with String[][]    coderanch.com

//ArrayCopy.java class ArrayCopy { public static void main(String[] args) { char[][] arrSrc = new char[][]{ {'A', 'B', 'C'}, {'E', 'F', 'G'}}; char[][] arrDest = new char[2][3]; System.arraycopy(arrSrc[0], 0, arrDest[0], 0, 3); System.arraycopy(arrSrc[1], 0, arrDest[1], 0, 3); for (int i=0; i<2 ;i++ ) { for (int j=0;j<3 ;j++ ) { System.out.println(arrDest[i][j]); } } } }

36. Strings and StringBuffers    coderanch.com

Hi there, Remeber that Strings are Immutable, that means once they are created they cannot be changed, however for our convenience, java makes strings into stringbuffers when we perform concatination. Eventough we are using strings, back there its actually stringbuffers. so why not use stringbuffers instead. Apart from that if you have a look at the various methods inside the stringbuffer ...

37. Doubt in the behaviour of 'String' class!!!    coderanch.com

== compares the reference variable only, not what is contained in it. In the first case, you have 2 distinct reference variables, therefore they are not the same. In the other 2 cases you have only 1 reference variable due to the way Java handles Strings, and therefore the comparison yields true. Essentially, Strings though Objects behave somewhat like primitives in ...

38. String Problem    coderanch.com

Hi Somkiat, Objects are passed as references in function calls in java. Somebody mentioned that variables are passed by value but it is a bit misleading in this case. Primitive types are passed my value. Variables that represent objects are not object but references to objects. Therefore you can say that variables are passed by value and objects are passed by ...

39. Strings    coderanch.com

40. More String Questions    coderanch.com

This is a very common homework problem which many Ranchers probably have done before. (If not, any programmer with some bit of experience can probably figure it out.) My point is that it doesn't help you much if we do it for you. So what have you done so far? Have you even started any code yet? You probably should look ...

41. Handling Strings    coderanch.com

(I used _ for blank here to make things format beter ...) You may be asking how to find a word and not a word fragment. You'd want to include "_word." and "_word\n" and "(word)" and maybe "_word's_" but not "wordsmith" or "sword". Is that right? You might try translating all non-alpha characters to blanks in your text, then use plain ...

42. How many String Object are created in the following code ??    coderanch.com

Rohan, I would say 5: 1 s1. 2 s2. 3 The string concatenation is not stored in s1 but it exists. 4 Same case for the s2 string concatenation. 5 The string you'll print is the concatenation s1, a blank and s2. To verify this I created a little testprogram: class Test { public static void main (String args[]) { String ...

43. going through a string    coderanch.com

44. How to form a new string out of several old strings excluding some??.......    coderanch.com

Hello, I have a slight problem. I have many appointments, in the form ^time%location?description , inside a schedule, in the form: ^14%Paul's house?Group Meeting ^9%Nutty Professor's Office?Office Hours ^12%MegaBits?Lunch I need to write a method to cancel the appointment scheduled at the given time, if it exists and return true if an appointment was canceled, and false otherwise. Here is my ...

45. Multiline Strings    coderanch.com

46. OCTET String and IA5String    coderanch.com

Hi How you would go about converting the binary back into human readable format depends on how it was converted to binary in the first place and what it represents. How did the binary you need to work with come to be in your possession? You need to know whether the binary represents and IA5 string or an octet string in ...

47. String handling    coderanch.com

48. String and String[]????    coderanch.com

The types are incompatible because "String[]" is an array of Strings: a block of memory that holds zero, one, or more String objects. Thus, you can't set the value of one String to be the value of zero or more other Strings. Can you explain what you're trying to do. Yes, you're trying to assign a String[] to a String, but ...

49. crypting a String    coderanch.com

50. "String" = "String" = False...?    coderanch.com

Hey, I'm trying to check and see if two strings are equal or not in a particular function. Here is my code: public int indexOf(String name) //returns the index of a given entry { for (int i=0; i

51. Divide a String    coderanch.com

53. Are Strings exeception to the rule    coderanch.com

In java when two reference variables holding identical data (different instances) are compared with == operator, the answer would be false. But this is slightly different in case of String. You can see that when you run the following program. In case we use 'new' operator and create an instance the string variable acts as 'Reference type'. When a string literal ...

54. Java Strings    coderanch.com

As of 1.4 String has a replace method that might do the job for you. If you're on an older JVM that doesn't have replace() the usual trick is: use indexOf to get position of the old string result = substring of original up to the position + new string + substring of the original after the old string Do you ...

55. change a string    coderanch.com

Because my wife calls me "Captain Literal", i feel obligated to point something out. You are not really changing the string here. cStr remains what it always was. What you are doing is createding a NEW string, based off the original, and creating a new reference to it. you could do cStr = cStr.replaceAll("CAT", "DOG"); but again, this creates a new ...

56. Strings are immutrable?    coderanch.com

Originally posted by Kedar Dravid: According to the Java API, Strings are immutable. How can this statement be explained with the help of an example? For example, the following code fragment is perfectly valid. String str1="XD"; String str2="DF"; str1=str2; str1="KL"; str2="LI"; In this case, aren't we changing the reference values of the String objects? So, in what way are they immutable? ...

57. String Evaluate    coderanch.com

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - ...

58. regarding Strings    coderanch.com

String str = "ABC"; Creates a new reference variable to a String object holding the data "ABC" which resides in the String constant pool. If there is no such String object in the pool a new one is created. String str = new String("ABC"); Creates a new reference to a new String object holding the data "ABC" which resides on the ...

59. Strings as function arguments    coderanch.com

I agree with Sripathi. My two-cents worth : Java always passes by value ( or as the Sierra and Bates put it ... pass by copy of the variable ) for all variables. - in case of primitive you are passing a copy of the bits representing the value. - in case of object references you are passing a copy of ...

60. java String UTF8    coderanch.com

import java.util.*; public class Test { public static void main(String[] aaaa){ Locale locale = Locale.getDefault(); // get zh_CN Locale.setDefault(Locale.FRENCH); String a = ""; // a Chinese chars try{ String u = new String(a.getBytes("UTF8")); //String u = new String(a.getBytes("zh_CN"),"UTF8");// doesn't work , I don't why System.out.println(u); // out of format }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println(a); // normal Chinese System.out.println(locale); // still ...

61. Substituting strings    coderanch.com

Thx Svend but i guess i'm even newer than i thought, i'm completely lost with the classes and methods. Looking at the StringTokenizer class i don't know how to incorporate that into the code. am i on the right path here: I have the user enter wordOne, wordTwo, and sentence(w/ wordOne) via the Scanner class(I'm actually on a Mac so I'm ...

62. problem in my String program    coderanch.com

hi friends can any one help me in following program my requirements are 1]to check if any String which we enter has any white space or not 2] to check our String has any number in it or not i have achieved first task by private boolean whitespace_check(String s) { for (int i = 0; i < s.length(); i++) { if ...

63. What is this? <String, Object>    coderanch.com

64. Strings behaving in abnormal manner    coderanch.com

Two distinct objects that are unequal (according to the Object.equals(Object) method) may produce the same hash codes (according to the Object.hashCode() method). In fact, unless construction is controlled (which best practices mandates anyway, but common practice ensure that it is prolific), it's impossible to enforce - all you need to do is construct 2^32 + 1 unequal instances and a hash ...

65. String and Immutability    coderanch.com

66. About string    coderanch.com

67. Determining width and height of a String    coderanch.com

Hello Folks, I have written an application that manages the x and y position of a String object through two seperate JSlider objects. The Display Area for the String object is a subclass of the JPanel class. The content of the String object is updated through a JButton and JTextField objects. I was successful in writing the code up until where ...

68. String class    coderanch.com

Hi, IMHO the main method here is getting overloaded here .. the public static void main(String args[]) is not found which is the entry point of any code.. That is if you replace the name String with StringBuffer than it runs fine....or to say a Integer ... (Class loader should create a problem there also) Now on to the second point ...

69. Instances of string objects    coderanch.com

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - ...

70. Manipulating String?    coderanch.com

I tried and tried to figure ways but cant, could someone please tell me a good way to read a name as a string, and manipulate it? I need to do this: Enter: John, Doe E. Output: Doe E. John When you see the ',' you have to put the word in front of it on the back, but I dont ...

71. Strings    coderanch.com

No stack overflow since no stack is involved. Limit is 2 gigabytes: String length() returns an int and that's your limit. You will exhaust your memory before you exhaust the upper limit of a String. If you have more than a 10K string I suggest looking at alternative strategies to manage that memory.

72. Can any one please tell the reason for the String related question.. given here    coderanch.com

String a="abc"; String b="abc"; String c= new String("abc"); String d= new String("abc"); if (a==b) {System.out.println(" a and b are equal"); } else System.out.println(" a and b are not equal"); if (b==c) {System.out.println(" b and c are equal"); } else System.out.println(" b and c are not equal"); if (c==d) {System.out.println(" c and d are equal"); } else System.out.println(" c and d are ...

73. System.getProperty(String)    coderanch.com

Hey guys, I'm a little confused as to what the parameter being passed in would look like. I know it's a String, but it's a String "key" that is suppose to return some system property to me? I'm a little confused as to what this means. The reason i ask is because i'm looking through some code and it reads the ...

74. strings    coderanch.com

Hello, is there a way to take input from the user. Say 3 words separated by spaces then display each new word on a new line. For example, I want to type into the console; Today is Friday. followed by enter key. The output should look like this Today is Friday I want to used only the following string operators. .length(); ...

75. String - can you improve my poor code?    coderanch.com

76. Problem with accepting a String    coderanch.com

I'm getting the desired out with the following two codes but i don't know wats actually happening inside can anyone help me by explaining these programs Method 1: import java.util.*; import java.util.Scanner.*; public class getInput { public static void main(String[] args) { Scanner scan = new Scanner(System.in); scan.useDelimiter("\r\n|[\n\r\u2028\u2029\u0085]"); String name = ""; while(scan.hasNext()) { if (!(name = scan.next()).equals(scan.useDelimiter("\r|\n|[\n\r\u2028\u2029\u0085]"))) break; } System.out.println(name); ...

77. iterate through string get elements    coderanch.com

78. String.toLowerCase()    coderanch.com

I have film titles that begin with the name of the film followed by ",The" if the original name begins with the. Example: Village, The When a user wants to search the collection for a film title, he or she will naturaly type in The Village, so I have some code that switches the word The around, then switches it back ...

79. Want to strip only part of a string    coderanch.com

i have string l_relatedMatterCode which has value something like this: (00205EPOPP) - 3M Dyneon against E.I. du Pont I want to strip only the value within the paranthesis and store it in another variable. I cannot do a substring bcos the length of the string within the paranthesis is not always 10. can anybody help me with any function for this?... ...

80. customise string?    coderanch.com

In short, it usually depends on where your output is going. For example, if you are outputting to HTML, you just surround the text with tags to make it bold, as well tags for sizing and other options. If you are using Swing, there are a wide variety of libraries for formatting. You can do some formatting of data ...

81. Strings    coderanch.com

Hi, Can anyone say me which one of the below two options would be better in perfromance and which one would create more string objects? One has String ,str within while loop and one outside while loop. Thanks in advance, Method : 1 public void printList(Vector v) { boolean flag = true; int i=0; while(flag){ String str = (String)v.get(i); System.out.println("The value ...

82. compressing a string    coderanch.com

83. " in String?    coderanch.com

84. strings    coderanch.com

I think one should also note that when you see: String s = new String("moose"); It's usually a sign that the programmer is new to Java! Perhaps a convert from C++. There's no practical reason to do that, although if they write: String y = new String(x); It could be because x is a substring of a larger string. The above ...

85. == in String    coderanch.com

Because the API Specification demands it: Returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned. Otherwise, if ...

86. Breaking a string down and tokenizers - help!    coderanch.com

Hi People. I'm trying to read in a line of text from a text file. Programming, Dr David Wake, Monday, 0900, 150 I want to seperate the string so that String module = Programming String lecturer = Dr David Wake String day = Monday Int time = 0900 Int groupSize = 150 I have used tokenizers to break strings down in ...

87. Problems manipulating string    coderanch.com

88. How to save a paragraph in a string    coderanch.com

How to save a paragraph (multi line) in a string.. then im going to display that string as a showMessageDialog. My problem is i can save in a string as a single line or use the special symbol like \n or \t. if i do so i have to type every thing in a line.. how can i type is like ...

89. string methods ..........HELP MI!!!    coderanch.com

90. String query    coderanch.com

"new" will create to new objects, that is why "==" returns false. However, using "=" will get an existing object from the pool, or create a new one if it does not exist. There is already a String whose value is "abc", so it will return the same reference to that String. Same reference, means that "==" will return true.

92. String Revers    coderanch.com

If you are using a character array as input, you can easily do this. If you are using the String class and still don't want to call things like charAt or toCharArray or others, this does not seem possible. As this sounds like an assignment, I won't post code Show us what you've got first.

93. string capitalise    coderanch.com

public static String convert(String s ) { String line = "", line1 = ""; StringTokenizer tok = new StringTokenizer(s," "); while(tok.hasMoreTokens()){ line1 = ""; String b = tok.nextToken(); for(int a = 0; a < b.length(); a++){ if(a == 0) { line1 += b.charAt(0); line += line1.toUpperCase(); } else line += b.charAt(a); } line += " "; } return line; }

94. Garbage collection of non-heap strings    coderanch.com

Hi, Welcome to JavaRanch! First, let me clear up a common misconception: the "String pool" is not a special area of memory where Strings are allocated; it's basically a hash table where references to Strings are kept. The Strings themselves, like all other Strings, are in the heap. Now, will such Strings ever be garbage collected? The JLS is silent on ...

95. String explanation    coderanch.com

Originally posted by Garrett Rowe: Maybe you could post your whole test code. I can't seem to duplicate the results you're getting. public class InitTest { public static void main(String[] args) { String x = "1"; String y = "1"; String aString; if (x.equals(y)) aString = "equal"; System.out.println(aString); } } or I test identity (x == y) public class InitTest { ...

96. doubt about strings creation    coderanch.com

All objects are created a runtime. The compiler emits code. The code must be loaded into a JVM and executed before any objects are created. No objects are created at compile time -- although the compiler might put code into a class file which results in an object being created more or less automatically. A String literal "like this" is actually ...

97. Can I caste Object[] to String[]?    coderanch.com

Originally posted by Jeroen T Wenting: In other words, you can try but it won't work. Both Object[] and String[] derive from Array so there's no parent-child relationship between them. Huh? import java.util.*; public class Test { static public void main(String[] args) { String[] strings = {"Hello", "World"}; test(strings); Object[] objects = {"Goodbye", "cruel", "World"}; test(objects); } static void test(Object[] array) ...

98. Related to String    coderanch.com

Adding to what previous posters have written, whenever I see something like new String("Sachin") in Java code, I'm inclined to assume that either: 1. The programmer is new to Java and doesn't know that they can simply write "Sachin", or... 2. Some horrible hack involving the string pool or equality versus identity is about to be attempted. Either way, my spidey ...

99. Strings    coderanch.com

100. String problem    coderanch.com

There are a few things you have to understand. First of all, the == operator compares object references and not the contents of the objects themselves. So, == will only return true if the operands on both sides of it refer to the exact same object. If you have two separate String objects it will return false, even if the String ...