I am new to programming and have a simple question: is there a "better" or more efficient way of doing this...
if (x != 0) {
y = x;
}
or
if (getMethod() != null) {
value = getMethod();
}
I'm new to programming and above code (esp the 2nd one) seems inefficient.
Thanks in advance.
You second example can suffer from a "Time of check, to time of use" weakness. If the first invocation of getMethod() returns non-null, it is possible that your second invocation will return null. A better way to do it would be:
value = getMethod();
if(NULL != value)
{
/* use value as planned */
}
else
{
/* handle a null value, probably an error */
}
if interested, you can read more about TOCTTOU weaknesses here.
For your first example, I don't really see a better way of doing this.
N.B. This answer is from the perspective of a C programmer (seeing as how C was one of your tags).
Hope this helps
- T.
You can make it shorter
if ( x ) y = x;
is the same as
if (x != 0) {
y = x;
}
And
if ( getMethod() ) value = getMethod();
is the same as
if (getMethod() != null) {
value = getMethod();
}
First code snippet:
In C any non-zero value is treated as true and 0 treated as false. So, for the first example, you can rewrite it as:
if (x) {
y = x; // this line will be executed if x not equal to zero
}
Second code snippet:
You called getMethod() twice which is not efficient. As per your code, you are assigning the return value of getMethod() into value if getMethod() returns anything but NULL. So you can use a temporary variable to check the return value of getMethod(), like following:
temp = getMethod();
if (temp != null) {
value = temp;
}
That will reduce calling same method twice.
Related
UPDATE: Apologies for the confusion. All code MUST be written between the forward slashes i.e. the "//" beginning at the TO DO comment. And ends the line before the return answer.
Consequently this:
return price<20 ? "Buying new shirt" : null
is unfeasible as return answer is OUTSIDE the allowed code modification area.
I also didn't know if it was possible to assign a null object to a String object (as my comment indicated. And yes, I'm aware of the difference between "null" v null. That is the entire issue I'm having with the code failing to compile.
The ConditionalStatements() method is supposed to pass an integer input and return a string variable called answer.
If the passed integer price < 20 (to include negative integers), then the return variable answer = "Buying new shirt". Otherwise the compiler's expected return value for answer must be null i.e. the OBJECT null and NOT the string "null" which answer is initialized with.
Constraints:
if statement MUST be a Simple Conditional Statement with no branching.
cannot use catch try or other statements. Limited to use of compound conditionals and variables.
MUST be WITHIN the area designated by // forward slashes.
Because of this last constraint, I can't see a way to typecast/return the null as the test errors are indicating. Apologies again for the confusion.
I've tried short circuiting using && and the || operators. Tried getting creative with && and II operators in the if statement to make compound statements. e.g:
if ( (answer.equals(null) && (price >=20) ) etc.
to trap the incorrect test input and change answer data type. But compiler fails test cases of required answer = null for cases where price >= 20. Returning answer = "null" throws an error as a String object is returned v. the desired null.
How to type cast answer variable e.g. (null) answer = null; in my code below?
public class ConditionalStatements {
/**
* This method is used for problem one in the README.
* #param price A price that will be passed in by the test.
* #return String A string used to validate the test.
*/
public String simpleConditional(int price) {
String answer = "null";
**// TODO: Write Step 1 code between the forward slashes** <--start code modification area
(answer == null ) || (price < 20) )
answer = "Buying new shirt";
if( (price >= 20) ) {
answer = null; //this assignment is legal according to post feedback.
//However it STILL results in test failure message (shown in URLs below).
//Where the compiler is expecting a null object and not a string object....
//compiler won't accept answer = null; How to typecast answer String variable so it will accept null object?
}
// **<---this is the END of the code modification area**
return answer;
}
When compiler tries to compile, it fails with these test run errors:
All tests. Only price < 20 passed:
https://i.postimg.cc/TYrH051P/allTests.png
Test 3: price = 20, expected return for answer = null
https://i.postimg.cc/W3GJCVk0/Test3-err1.png
Test 4: price = 21, expected return for answer = null
https://i.postimg.cc/bNJsHk3x/Test4-err2.png
All you have to do assign null to answer variable, rather than "null" string. Check the below code, I think it does what you want to achieve.
public class ConditionalStatements {
/**
* This method is used for problem one in the README.
* #param price A price that will be passed in by the test.
* #return String A string used to validate the test.
*/
public String simpleConditional(int price) {
String answer = null;
// TODO: Write Step 1 code between the forward slashes (answer == null ) || (price < 20) )
if(price < 20){
answer = "Buying new shirt";
}
return answer;
}
public static void main(String[] args){
ConditionalStatements var = new ConditionalStatements();
System.out.println(var.simpleConditional(10)); // prints "Buying new shirt"
System.out.println(var.simpleConditional(25)); // return null object
}
}
To use null with explicit type you have to put a cast in front of null, in you example
if( (price >= 20) ) {
answer = (String) null;
}
I have a List that contains many rows of data.What i want to do is return only the first iterated value and nothing else.
public int getnumber() {
for (Bike temp : bikes) {
return temp.getBikeID();
break;
}
}
I tried something like the above..but the break statement is unreachable. How may i achieve this ?
I know that i could still just declare a variable outside of the loop then assign the value in the loop but the returned value will be the last row.
This is because of the return statement before break. The return statement will take the execution to the calling method. so, the break statement is unreachable.
You don't need to iterate to get the first value of the collection. The first index would be 0. so, just make it
if(bikes!=null && bikes.size() > 0)
return bikes.get(0).getBikeId();
return -1; // `-1` denotes failure or put anything relevant to failure
Do not loop and try directly :
return bikes.get(0).getBikeId();
Try like this -
// null and size check to make sure if there is something on 0 index
return bikes != null && bikes.size > 0 ? bikes.get(0).getBikeId() : 0;
Simply delete the break statement. In fact, this is all you need:
for (Bike temp : bikes) return temp.getBikeID();
return -1;
In place of return -1 put the behavior you prefer for the "not found" case.
You can access you list's indices via .get() directly. No need for an iteration if you only need one or a hand full of specific elements:
public int getnumber() {
int result = 0;
if (bikes != null && bikes.size() > 0)
result = bikes.get(0).getBikeID();
return result;
}
Or even shorter, with the use of the ternary operator (condition ? true : false;):
public int getnumber() {
return (bikes != null && bikes.size() > 0) ? bikes.get(0).getBikeId() : 0;
}
In the expression of a while loop, is it possible to initialise a variable, then use that as part of the expression?
It's probably simpler in code:
while (int a = someMethod(), a<b)
It would be possible to just add another method, and so have to following:
private boolean whileLoopTest() {
int a = someMethod();
return a<b;
}
public void originalMethod() {
while (whileLoopTest()) {
//...
but this doesn't seem as neat.
EDIT
I also don't want to directly compare the method to my variable, as it is compared to several variable, and so if would be a long, unreadable mess. A better example of what I want would be:
while (int a = SomeClass.someStaticMethod(), -1<a && a<b)
It's not true in my case, but this would be a equally valid question if someStaticMethod() took a long time to return - I would only want to call it once.
I'm fairly new to StackOverflow, so I'm not sure if giving other situations where this would apply is what I should be doing.
int a;
while((a = someMethod()) < b){
//do something
}
A common use for this is reading from a file:
BufferedReader fileIn = ...
String line;
while((line = fileIn.readLine()) != null){
//do something
}
fileIn.close();
/edit
You can do this for your new scenario:
int a;
while(-1 < (a = SomeClass.staticMethod()) && a < b) {
//do something
}
Once the left hand portion of the && statement is executed, the return value of SomeClass.staticMethod() is stored in a, which carries over the the right hand portion of the statement.
Why not just not assign the value to "a" if you are not using it anyways?
while (someMethod() < b) { doSomething() }
If you actually do need "a" then your alternate solution would not work. The solution then would be either to save it (which I do not consider unneat) or what Kerrek said.
You can use the function directly without using a local variable like this:
while ( someMethod() < b) { /* ... */}
This, if your method returns intended value. (If you are casting it to a local variable, it's supposed to)
EDIT: For your second question.
Your concern is understandable, but if you are assigning that methods value to a local variable inside while loop's boolean expression, in every loop where "While" checks the expression, you are assigning methods' return value to local variable, which means you are calling that method in every iteration. That doesn't change anything from my first answer.
I'm very new to Java, so I'm sorry if this is a bit too stupid for you. So, I have a class called Construct that has an instance variable previousState. I have a setter in that class, with the signature setPreviousState.
Then, in an other class I set the previous State of a Construct object with this code :
ArrayList<Construct> sequence = new ArrayList<Construct>();
do {
Construct minimum = priorityQueue.delMin();
for (Construct neighbor : minimum.neighbors()) {
neighbor.setPreviousState(minimum);
priorityQueue.insert(neighbor);
}
System.out.println(minimum);
if (minimum.isGoalState()) {
// Construct sequence backwards and return it
sequence.add(minimum);
while(minimum.previousState() != null) {
sequence.add(0, minimum.previousState());
}
return sequence;
}
} while (true);
But while(minimum.previousState() != null) is an infinite loop because previousState() always references the same object. Why?
You never change the value of minimum in this loop, and it seems that the value of minimum.previousState() is also constant for each object [no side affects to method previousState()], you might want to add minimum = minimum.previousState(); to your while loop:
while(minimum.previousState() != null) {
sequence.add(0, minimum.previousState());
minimum = minimum.previousState();
}
Just because you never change what the minimum variable points to in the loop. So you're checking again and again that the same minimum's previousState is not null, without ever changing the minimum's value nor the minimum's previousState.
I have written this function which will set
val=max or min (if val comes null)
or val=val (val comes as an Integer or "max" or "min")
while calling i am probably sending checkValue(val,"min") or checkValue(val,"max")
public String checkValue(String val,String valType)
{
System.out.println("outside if val="+val);
if(!val.equals("min") && !val.equals("max"))
{
System.out.println("Inside if val="+val);
try{
System.out.println("*Inside try val="+val);
Integer.parseInt(val);
}
catch(NumberFormatException nFE)
{
System.out.println("***In catch val="+val);
val=valType;
}
return val;
}
else
{
return val;
}
}
But the problem is if val comes null then
outside if******val=null
is shown.
Can any1 tell me is this a logical mistake?
And why will I correct?
If val is null, then the expression val.equals("min") will throw an exception.
You could correct this by using:
if (!"min".equals(val) && !"max".equals(val))
to let it go inside the if block... but I would personally handle it at the start of the method:
if (val == null) {
// Do whatever you want
}
Btw, for the sake of readability you might want to consider allowing a little more whitespace in your code... at the moment it's very dense, which makes it harder to read.
...the problem is if val comes null then outside if****val=null is shown. Can any1 tell me is this a logical mistake?
The output is correct; whether you want it to come out that way is up to you.
Your next line
if(!val.equals("min") && !val.equals("max")){
...will throw a NullPointerException because you're trying to dereference val, which is null. You'll want to add an explicit check for whether val is null:
if (val == null) {
// Do what you want to do when val == null
}
you should use valType instead of val to check either minimum or maximum is necessary to check.
My advice to you in such cases to use boolean value or enum instead of strings. Consider something like that:
/**
* check the value for minimum if min is true and for maximum otherwise
*/
public String checkValue(String val, boolean min){
if (min) {
// ...
} else {
// ...
}
}
If you need to compare strings against constants you should write it the other way around to make it null-safe:
if (! "min".equals(val))
And while this is mostly a style issue, I would make all method arguments final and not re-assign them (because that is confusing), and you can also return from within the method, not just at the end. Or if you want to return at the end, do it at the very end, not have the same return statement in both the if and the else branch.