We know that in Java when a method returns a value we have to store that value in a variable of that type.
For example the getString() returns String and we store that value in a String variable.
In J2ME I was trying to create radio-buttons i.e. using the ChoiceGroup class.
ChoiceGroup radio;
radio=new ChoiceGroup("Select your Color",Choice.EXCLUSIVE);
radio.append("Red",null);
radio.append("White",null);
radio.append("Green",null);
In book the signature of append() method is
int append(String string, Image img)
I want to ask that even though I am not storing the integer value returned from the append() method my code runs perfectly.
I am using Wireless toolkit 2.5.2
Note the book has not given any reasons for this and that's why I asked here.
We know that in Java when a method returns a value we have to store that value in a variable of that type.
Every part of that sentence is false.
You should get a better book.
ChoiceGroup append method returns the assigned index of the element. If you don't intend to use it, it's OK to ignore returned value.
Method signature - return value and parameters have meaning clearly defined in API documentation:
public int append(String stringPart,
Image imagePart)
Appends an element to the ChoiceGroup.
Specified by:
append in interface Choice
Parameters:
stringPart - the string part of the element to be added
imagePart - the image part of the element to be added,
or null if there is no image part
Returns:
the assigned index of the element
Throws:
NullPointerException - if stringPart is null
If you want to use the return value then you store in a variable or object.If you dont want then leave it .Its not a mistake in java
Related
txtRate.setText(emp.getRate());
I cant display the data from the csv file in the textbox because it keeps on saying
double cannot be converted to java.lang.String.
My method is public Double getRate()
If i try to make is public String it would work but i cant use the value for calculation because it already has been set
to String
The class you are working on contains method with signature setText(String value) but there's no method with signature setText(Double value).
When you call a method compiler checks the parameter type and tries to recognize what method should be in use for this case.
As you are using Double type for the parameter, the compiler is unable to find a method with signature setText(Double value) and you get the error you have reported in your question.
To overcome this issue, convert your parameter from Double to String type before passing it to setText method.
txtRate.setText(String.valueOf(emp.getRate()));
or
txtRate.setText(emp.getRate().toString());
But the second approach may throw NullPointerException if emp.getRate() returns null, so the first approach is safer.
In case you want to format your numbers in a fancy way, consider this tutorial: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Displaying data on the textbox require variable to be string, But calculation require variable to be double the answer is when displaying cast to string and when calculation don't
we can have two declaration for String array
1>String... sampleStringArray;
2>String sampleStringArray[];
can anyone tell me the difference
The first is an example of varargs and the wikipedia notes These values will be available inside the method as an array, must be the last parameter in a given method, and is otherwise accessed as an array (also it wasn't added to the language until Java 5).
Say you have a string where you are part way processing it but you ran into a part that is to be handled by a different method. Is it better to pass the entire string and use ints to show the boundaries or should a substring be created and passed as the argument to the other method?
The use is for a method that is processing an expression but if brackets are encountered another method is called.
So for example say I have a method process (String str). In it there's a line if(str.charAt(i) == '(') that calls another method that is responsible for finding the closing bracket. Would it be better to pass the method str.substring(i, str.length) or just have the method take a second parameter and pass it i so it knows where to start working from?
Because string are immutable. When you call subString on a instance you create new object. So in case of performance is better to pass the whole String and the indexes of start and end, but instead passing the String you may want to pass char[].
In Java 7 you can use class Segment for representation.
You could also use the CharSequence as attribute for methods. This will assure that you will not mutate the object and still have the flexibility of array of chars.
Hi y'all I have a very simple question. I am studying different websites that talk about arrays and I see this part which I don't understand very well.
In the (1) Why does the 'myString.length()' has a '()', why not just myString.length as in the example (2)??
In the (1) Why does the 'System.out.println(myString.substring(i,i+1))' has 'myString.substring(i,i+1)' why not just 'myString(i,i+1)' ??
In the (1) Why does the 'System.out.println(myString.substring(i,i+1))' has two values '(i,i+1)' why not just 'System.out.println(myString.substring(i))' as in example (2)??
1. String myString="abcedaslkhldfag";
for(int i=0; i<myString.length(); i++)
System.out.println(myString.substring(i,i+1));
2. for(int i=0; i<anArrayOfints.length; i++){
System.out.println(anArrayOfints[i]);
}
Thank you
I found it in this website http://www.javaclass.info/classes/java-array/array-examples-demonstration-and-code-snippets.php
First, about Arrays and Strings.
You are comparing totally different classes.
Array types are special objects that are dynamically created. Even array of primitives are objects (unlike in C) so it might have certain member variables/methods.
Have a look here: Array members
String is a class which encapsulates behavior suitable for strings, such as substring, trim etc. The actual data is stored internally as a character array, so there is a close connection between them, but the class itself represents more than just the characters.
Secondly, about subString method.
Methods called on a string object follow the syntax as specified by the API.
public String substring(int beginIndex)
public String substring(int beginIndex,int endIndex)
Have a look at the String API here. You will find there a length() method that returns the length of the String.
A note about "Arrays" class.
There is a class called "Arrays" that became available as part of the collections framework. The purpose of this class was to include behaviors that where commonly used on all types of arrays(such as sorting and searching).
The Array class extends java.lang.Object. Therefore array is an instance of Object. Arrays have one instance variable called length. It's a variable so you dont need the ().
And the string class has a member function called length, which is why you need the ().
The first one, myString is a string, which is an object. You are calling a method called length() of type String to know the length of the string. This method calculates the number of chars in the string and returns that number. And subString() is also a method that takes two parameters, begin and end index. This is just standard that is created by Java. To know more about the string methods, here.
The second one is continuous memory of data, an array. The length of the array is also stored in the array and is accessed using '.length'
This is because length() is a method on the String class, while length is an instance variable on the Array class.
As for myString.substring(i, i + 1), this is a method being called on an instance of the String class, which will return a new String instance containing the substring. In fact, myString.substring(i) does exist in the API, and would return the substring that starts at i and ends with the last character in myString.
Note that anArrayOfints[i] returns the int stored at element i in the array.
1, myString has a method named length. When use a method, you must specific the arguments which should be included in "()". In the (2), length means an attribute. Just use it as a variable.
2, substring is method. When use a method of some object, you can imagine you are sending command to this object. myString can not understand "myString(i,i+1)". You should specific the method or the command "subString"
3, anArrayOfints is an array object. Just like a list of something. You should specific a number to pick a element up.
I've got a function filling a HashMap(rMap) of String arrays. Once certain conditions are met e.g r.Map.size() != 0 I then, in another file (rMap is a Global variable) call the following String array[] = rMap.get(0) from this I attempt to System.out.println(array[0]) .
Thats the run of the program and I get a null pointer at System.out.println(array[0]);. Anyone have any ideas why this happens?
EDIT: I'm filling the map like so..
String center[] = new String[] { tname, tmessage, tlink, tsname };
Global.rMap.put(index, center);
Where all values in the array are variables that are strings. So the value I'm accessing it tname and It's not equal to null. I've checked. My Key value is a String
The array reference is null, most likely because no value (or a null) has been added to rMap, with key 0.
If possible, use generics to ensure that your keys are the correct type. You might also print out the values of the map prior to fetching array to see what is in the map. Stepping through the code with a debugger, with a watch on the rMap will also show what the map contains and when it is changed.
How are you filling the map? Are you certain that you're putting an non-null entry with an Integer key of 0 into it?
Well, we can be pretty certain that you aren't. Possible reasons:
An error in the filling code that results in the intended put not being executed, or with a different key value
You're using Short or Byte objects as keys
You're putting a null value into the map under the 0 key
You can answer this question for yourself by running the code in a debugger and looking at the contents of the map.
Update:
My Key value is a String
Well, that's your problem right there. rMap.get(0) will look for an Integer, and it will not match the entry for a String "0".
HashMap allows null values, so the value you are getting with String array[] =rMap.get(0); may be null. Accessing the null array then throws the NPE.
Try rMap.get(Integer.valueOf(0));
It's an issue when you invoke the get method of Map implementation, the signature of get method of java.util.Map is get(java.lang.Object),thus,any object will be accepted as its argument.
The key that works fine is either pass a string(value=0) as a key or overrides the hashCode and equals methods of argument object that is not a java.lang.String object.
The get() method of Hashmap takes a key, not an index, to identify the value you want to get. If you want an ordered list of items, you'll need to use a List subclass (or enforce the ordering, yaourself). If you want to use a Hashmap, use the keys() method to get an enumeration of all the map's keys.
(removed above text, due to question clarification. leaving below text as, even though it's not the problem, it is an important consideration)
Also, you'll need to be very careful not to create race conditions, since you're working across threads. While Java's native Hashtable is synchronized, that doesn't mean the data in it is. That is, you can MyObj obj = get(xxx) in one htread, Nd start manipulating the obj in two separate threads, possibly stepping on each other. Depending upon your application, you may want to use Hashtable.remove() so that the data is gone from the map and cannot be re-used, or you may need some synchronized blocks (remove() may well be the simpler implementation, thoguh you'd have to gracefully handle conditions where the map first has data, then that data is gone).