What does the colon mean in Java (Part 2)? - java

This question has already been asked, but the answers seem to be incomplete. What does the first colon in the following context mean?
import hudson.model.SCMS;
(...)
SCMS: for (SCM scm : scmTriggerItem.getSCMs()) {
(...)
Additionally, the colon has some new uses in Java 8.
This question (which has originally been asked two years ago) is different from loop-in-java-code, because it is wider. While the answers of the original question do not mention the use of the colon as label, which is answered in question "loop-in-java-code", the latter question doesn't ask for the use of the colon within for loops nor in Java 8.
As the answer from biziclop shows, there are colon usages in the Java syntax that are easily forgotten and not mentioned in the other two questions.

There are four six uses of the : character in the Java language.
To denote a label. Labels can be used to break or continue to in loops.
In an enhanced for statement (also called for-each statement), which allows easy iteration across collections and arrays.
As one half of the ?: conditional operator.
And since Java 8, as part of the :: method reference operator.
In a switch statement, after case or default.
And you can also use it in an assert statement to specify an error message when the assertion fails.
In your case, SCMS: is a label, while for (SCM scm : scmTriggerItem.getSCMs()) is an enhanced for statement.
You can always look up the full syntax reference of Java here. It is amazingly dull but without it I easily missed two of the six cases.

Related

Is there a ternary assignment operator in Java? [duplicate]

This question already has answers here:
How to write a ternary operator (aka if) expression without repeating yourself
(17 answers)
Is using Optional.ofNullable as a replacement for the ternary operator a good practice?
(6 answers)
Avoid violation of DRY with ternary?
(2 answers)
Closed 2 years ago.
I'm fairly new to Java and I'm trying to check if a variable is null and use its value if its not. Previous developer wrote something like this:
xModel.setName(xService.getName(xID) != null ? xService.getName(xID) : "");
And I would like to refactor it so I wouldn't have to use xService twice to just get the name.
I know I can store the value beforehand but this is just an example. I just wonder if there is a way to do this in Java?
Thanks.
I disagree with all other answers. They require special functionality from specific versions by importing structures from the standard library, or obscure calls that works in this specific case, and all in all just hides the simplicity of what you're trying to do.
Keep it simple (KISS). Don't introduce more complexity and concepts when you don't need them. You're refactoring another developers code, which means this is a project where someone else will probably be reading your code later on. So keep it dead simple.
String name = xService.getName(xID);
xModel.setName(name != null ? name : "");
This is more readable than all other examples and doesn't require intimate knowledge of the standard library and its API.
Objects.toString​( Object o, String nullDefault )
In this particular case you can use java.util.Objects.toString. Second argument is a default value to use in case of a null in the first argument.
xModel.setName(Objects.toString(xService.getName(x.ID), ""));
What you have is already the best core Java can do pre Java 8. From 8 onwards, you may use optionals:
xModel.setName(Optional.ofNullable(xService.getName(xID)).orElse(""));

How can i add variables inside Java 15 text block feature? [duplicate]

This question already has an answer here:
How to have placeholder for variable value in Java Text Block?
(1 answer)
Closed 2 years ago.
Just came across a new feature in Java 15 i.e. "TEXT BLOCKS". I can assume that a variable can be added inside a text block by concatenating with a "+" operator as below:
String html = """
<html>
<body>
<p>Hello, """+strA+"""</p>
</body>
</html>
""";
But are they providing any way so that we can add variables the way which is becoming popular among many other languages as below:
String html = """
<html>
<body>
<p>Hello, ${strA}</p>
</body>
</html>
""";
This question might sound silly but it may be useful in certain scenario.
Java 15 does not support interpolation directly within text blocks nor plain string literals.
The solution in Java 15 is to use String.formatted() method:
String html = """
<html>
<body>
<p>Hello, %s</p>
</body>
</html>
""".formatted(strA);
From the spec for text blocks:
Text blocks do not directly support string interpolation.
Interpolation may be considered in a future JEP.
"String interpolation" meaning
evaluating a string literal containing one or more placeholders,
yielding a result in which the placeholders are replaced with their
corresponding values
from Wikipedia
As stated above, maybe we'll get it in the future. Though it is difficult to say how they could possibly implement that without breaking backwards compatibility -- what happens if my string contains ${}, for example? The Java language designers rarely add anything that is likely to break backwards compatibility.
It seems to me that they would be better off either supporting it immediately, or never.
Maybe it would be possible with a new kind of text block. Rather than the delimiter being """, they could use ''' to denote a parameterized text block, for example.
As already discussed, this is not possible in JDK15 and you cannot change that fact.
But, I suppose you are trying to suggest a thing like this in C# language.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
Although this is just a syntax sugar thing over string.Format() method in C# (which is a counterpart of String.format() in Java), apparently it is nice if we can have this in Java. This is an extension to the existing way of describing string literal in the language syntax, but of course this can be easily adapted onto text block specification as well.
If this is what you have in your mind, you can make a proposal to Java Community Process to expand Java Language Specification. This is very much lighter syntax/semantics enhancement than adding full-featured template engine in Java Compiler/Runtime specification, and it is possible that they would agree with you.
As user #Michael mentioned: No. 'they' (team Project Amber, who are implementing JEP 368) are not providing any way to interpolate the string in the text block.
Note that I somewhat doubt it'll ever happen. For starters, there is the backwards compatibility issue; any such attempt to introduce interpolation requires some marker so that any existing text blocks aren't all of a sudden going to change in what it means depending on which version of javac to invoke.
But more to the point, you yourself, asking the question, can't even come up with a valid example, which is perhaps indicative that this feature is less useful than it sounds. It looks like you came up with a valid use case, but that's not actually true: If what you wrote would compile and work, then you just wrote a webapp with a rather serious XSS security leak in it!
The point is, what you really want is 'templating', and whilst templating sounds real simple (just evaluate this expression then shove the result into the string right where I typed the expression, please!) - it just isn't. Escaping is a large reason for that. But you can't blanket-apply the rule that ${strA} in a text block means: Evaluate expression strA, then HTML escape that, then put it in, for two reasons: Who says that the string you're interpolating things into is HTML and not, say, JSON or TOML or CSV or whatnot, and who says that the interpolation I desire requires escaping in the first place? What if I want to dynamically inject <em> or not, and I don't want this to turn into <em>?
Either we update the langspec to cater to all these cases and now we're inventing an entire templating system and shoving that into a lang spec which seems like a job far better suited to a dedicated library, or we don't, and the feature seems quite useful but is in fact niche: Either you rarely use it, or you have security and other bugs all over your code base - any lang feature that invites abuse is, and I'd hope one would agree with me on this - not a great feature.
Yes, many languages have this, but the current folks who get to decide what java language features make it into future versions of the language seem to be in the phase that they acknowledge such features exist and will learn lessons from it, but won't add features to java 'just because all these other languages all have it' - some thought and use cases are always considered first, and any such analysis of interpolation on string literals probably leads to: "Eh, probably not a worthwhile addition to the language".

While debugging Java codes what does # mean in statements like {Instance#789} or "SomeThread"#321: RUNNING? [duplicate]

This question already has an answer here:
Deciphering variable information while debugging Java
(1 answer)
Closed 6 months ago.
The "#" seems to be everywhere when I debug. They are always preceded by some instance/variable name and followed by a (usually three digits) number. What does it mean? I have an image below
Taken from https://medium.com/#andrey_cheptsov/intellij-idea-pro-tips-6da48acafdb7 .
#730 means the 730th object created since the application started.
It is not the hashcode. Length of this can be more or less than 3 digits.
It's totally depends upon which IDE you are using, may eclipse will give something else instead of #730 and in different format also, so it is the way of intellij to maintaining the debugging.
This is Intellij debugger's way of displaying a "unique identifier" for an object. It consists of the short classname and a unique number. The unique number seems to be generated using a simple counter, so the "meaning" of 729 in Owner#729 is (presumably) "this is the 729th object that the debugger has allocated an identifier for". However, you probably shouldn't rely on that.
There is no overt relationship between these numbers and Java identity hashcode values, though I expect Intellij maintains a mapping behind the scenes.
The Owner#5f9d02cb in the screenshot is reminiscent of the result of Object::toString ... when it hasn't been overridden. If that it is what it is, then the 5f9d02cb will be the object's identity hashcode.

Why does Java have an empty statement? [duplicate]

This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 7 years ago.
Just a general Java question. Why does the null variable exist? I'm working with some introduction to CS students and one of the most common mistakes is semi-colons where they are not supposed to be. For example
if(isTired());{
sleep(10);
}
The misplaced semi-colon before the open parenthesis keeps the if statement from working correctly, and I was wondering why the null line did in a Java program. In this example null seems to be a detriment and was wondering when someone would use it when coding.
The null statement is useful because there are some places in Java where you want to do nothing. They are not frequent, but they exist. Often they are the 'compulsory' statements that you have to put in as part of a construct. For example, if you want to write a for loop that only terminates on a 'break', then you want there to be nothing in the 'conditional' part of the for:
for (int i=0;;i++) {
int j = complexCalculation(i);
if (j<0 && complexCondition(j)) {
break;
}
}
If the null statement wasn't allowed, that wouldn't compile. If it was allowed there, but not in other places, that would be inconsistent (and make life more difficult for compiler writers).
The reality is that, once you get to be fairly proficient with the language, errors caused by accidentally adding null statements are rare.

Java one line if statement [duplicate]

This question already has answers here:
Is it ok if I omit curly braces in Java? [closed]
(16 answers)
Closed 9 years ago.
I am using if condition without braces in java something like
if(somecondition)
//Only one line Business logic
but some told use braces always even one line statement something like this
if(somecondition){
//Only one line Business logic
}
What is the better way according to java sandard?
there's no real "standard". i prefer always using braces because if you dont you risk someone adding an innocent looking logging statement turning your code from
if(somecondition)
//Only one line Business logic
into
if(somecondition)
log.debug("condition was true");
//Only one line Business logic
and then things stop working :-)
That's a matter of taste. I would use braces or else no braces but write all code in one line to improve readability.
Also you might consider using a ternary operator
booleanExpression ? value1 : value2
In addition to #radai answer, if you are a real evil mind, when you see a if with no braces you can do something that will make you ennemies by adding a semi-colon on the same line of the if but at the 800th column of the line(or something).
like
if(condition) /*a loooot of whitespace*/ ;
//Only one line Business logic that will get executed whatever is the condition
This is why i prefer to use braces and recommend people to use them
No naked if statements. You're just asking for trouble. Always use { }
it is better to use braces when checking for errors or updating the code.
imagine.
if(answer.equals("add"))
addedValue += Scanner.readInt();
but you have a new requirement to add only the absolute value, so you change to.
if(answer.equals("add2))
valueToBeAdded = Scanner.readInt();
if(valueToBeAdded < 0) valueToBeAdded = - valueToBeAdded;
addedValue += valueToBeAdded;
this is not a really correct algorithm, is just an example of what can happens.
Using if statement with braces is better way to java standard, because it increase the readability and reduce unwanted error.
The two statements have exactly the same effect but I have suffered so often from the lack of braces that I also always comment that there should be braces even around 1 line statements. This makes the code easier to maintain and can save a lot of headache. My experience shows that one line if statements often turn into multi-line statements on later iterations so what you save by not writing two { the first time, you will give later on.
According to java standard braces are better because if they are not there compiler has to work around more and also would be performance issue.

Categories