Indentation Check not working properly for statement label - java

In checkstyle I have enabled the check for Indentation. I'm getting a weird problem with it.
The check is working fine for everything other than statement label.
I have a code snippet like the following :
public void doIt(int k) {
for (int i = 0; i < k; i++){
search:{
for (int j = 0; j < i; j++){
if (j == i){
break search;
}
}
}
}
}
The indent level is set as 4.
Now, if I put the statement label (search) at level 11, it should give one warning as
- label child at indentation level 11 not at correct indentation, 12
But the problem is, its giving Multiple markers at that line :
- label child at indentation level 11 not at correct indentation, 12
- label child at indentation level 11 not at correct indentation, 8
So, no matter in which level I indent the label, there will always be one/two warnings.
I didn't enabled duplicate checks for indentation with two different Indent Level.
How am I getting two warnings for a single check? How to resolve this issue?

This is a limitation of the IndentationCheck. The label indentation is hardcoded to be one level less than the normal indentation at this point in the tree (verified by looking at the Checkstyle 5.6 sources). The next token, which is the left curly brace, or, if you leave out the braces, the for statement, must be on the expected level. So you could format the code like this with no errors:
public void doIt(int k) {
for (int i = 0; i < k; i++){
search:
for (int j = 0; j < i; j++){
if (j == i){
break search;
}
}
}
}
It is of course a matter of personal taste, but I don't like it. I would recommend not using Checkstyle for checking the formatting, and instead use an automatic code formatter. Eclipse, for instance, has a nice formatter built in.

Related

How braces affect code output

While I am implementing Selection sort method and executing it, some of elements are sorted while other are not. I checked over the internet about a correct implementation but I didn't find any difference except an extra opening and closing braces.
Here is my code:
public void selectionSort()
{
for(int i = 0;i<=arrSize;i++)
{
int min = i ;
for(int j = i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
}
}
}
And here is what I found on the internet:
public void SelectionSort()
{
for(int i = 0;i<=arrSize;i++)
{
int min = i ;
for(int j=i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
{
min = j ;
swap(min,i);
}
}
}
}
I have tried to track where the error is but I failed so I decided to ask here about this logical error, I hope you to answer the question and explain how braces can affect the output of code in this particular case.
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
and this
if(theArray[j]<theArray[min])
{
min = j ;
swap(min,i);
}
are two different codes.
in first code you swap elements EVERYTIME
in second code you swap elements only if the if statment is true.
The braces limit the if condition actions. With no baces after the if condition, only one expression will be run conditionally and the swap in the second line after the if will always be executed.
Search more info about the scope of if else expressions limited in Java by braces.
i am trying to learn java myself
You should really get a book about java basics and read though it.
i didn't find any difference except an extra opening and closing braces.
But they make the difference:
Without the braces: if the condition in the if statement is not matched the if skips the next statement only.
In Java the curly braces create so called blocks. In conjuncton with the if statement such a block as a hole is the next statement.
If there are no brackets then the compiler adds internally a bracket only for the next line. So,
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
is similar to
if(theArray[j]<theArray[min])
{
min = j;
}
swap(min,i);
That's why you are getting the wrong output.
See
for(int j = i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
}
Above will execute swap method in every iteration of for loop. Because its in for loop block.
And,
for(int j=i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
{
min = j ;
swap(min,i);
}
}
Above will execute swap method only when if condition satisfied.
Loops, if or any block will consider statements inside braces. If you don't use braces then it will consider only next single statement in block.

Java symbol not found when it should be

here's my code:
for(int i=0; i<plainTextUpper.length()-1; i++)
{
System.out.println(charCodeAt(i));
}
It won't compile though, because it says charCodeAt's symbol was not found. Am I missing a library? The only one I have imported right now is java.util.*
Assuming that this is Java and not Javascript, you probably want this:
for(int i=0; i<plainTextUpper.length()-1; i++)
{
System.out.println(plainTextupper.codePointAt(i));
}
Note that this will not process the last character of plainTextUpper. You probably also want to either get rid of the -1 or change the comparison operator to <= in the for termination test.

Why is printing "B" dramatically slower than printing "#"?

I generated two matrices of 1000 x 1000:
First Matrix: O and #.
Second Matrix: O and B.
Using the following code, the first matrix took 8.52 seconds to complete:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("#");
}
}
System.out.println("");
}
With this code, the second matrix took 259.152 seconds to complete:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B"); //only line changed
}
}
System.out.println("");
}
What is the reason behind the dramatically different run times?
As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....
As others who pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.
Test Conditions:
I ran this test from Netbeans 7.2, with the output into its console
I used System.nanoTime() for measurements
Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).
But that's pure speculation.
I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8;
I used System.nanoTime() for measurements.
Eclipse:
I got the same time on both cases - around 1.564 seconds.
Netbeans:
Using "#": 1.536 seconds
Using "B": 44.164 seconds
So, it looks like Netbeans has bad performance on print to console.
After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:
for (int i = 0; i < 1000; i++) {
long t1 = System.nanoTime();
System.out.print("BBB......BBB"); \\<-contain 1000 "B"
long t2 = System.nanoTime();
System.out.println(t2-t1);
System.out.println("");
}
The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.
And so on..
Summary:
Eclipse works perfectly with "B"
Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
First Matrix: O and # = 6.03 seconds
Second Matrix: O and B = 50.97 seconds
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

Strange performance drop after innocent changes to a trivial program

Imagine you want to count how many non-ASCII chars a given char[] contains. Imagine, the performance really matters, so we can skip our favorite slogan.
The simplest way is obviously
int simpleCount() {
int result = 0;
for (int i = 0; i < string.length; i++) {
result += string[i] >= 128 ? 1 : 0;
}
return result;
}
Then you think that many inputs are pure ASCII and that it could be a good idea to deal with them separately. For simplicity assume you write just this
private int skip(int i) {
for (; i < string.length; i++) {
if (string[i] >= 128) break;
}
return i;
}
Such a trivial method could be useful for more complicated processing and here it can't do no harm, right? So let's continue with
int smartCount() {
int result = 0;
for (int i = skip(0); i < string.length; i++) {
result += string[i] >= 128 ? 1 : 0;
}
return result;
}
It's the same as simpleCount. I'm calling it "smart" as the actual work to be done is more complicated, so skipping over ASCII quickly makes sense. If there's no or a very short ASCII prefix, it can costs a few cycles more, but that's all, right?
Maybe you want to rewrite it like this, it's the same, just possibly more reusable, right?
int smarterCount() {
return finish(skip(0));
}
int finish(int i) {
int result = 0;
for (; i < string.length; i++) {
result += string[i] >= 128 ? 1 : 0;
}
return result;
}
And then you ran a benchmark on some very long random string and get this
The parameters determine the ASCII to non-ASCII ratio and the average length of a non-ASCII sequence, but as you can see they don't matter. Trying different seeds and whatever doesn't matter. The benchmark uses caliper, so the usual gotchas don't apply. The results are fairly repeatable, the tiny black bars at the end denote the minimum and maximum times.
Does anybody have an idea what's going on here? Can anybody reproduce it?
Got it.
The difference is in the possibility for the optimizer/CPU to predict the number of loops in for. If it is able to predict the number of repeats up front, it can skip the actual check of i < string.length. Therefore the optimizer needs to know up front how often the condition in the for-loop will succeed and therefore it must know the value of string.length and i.
I made a simple test, by replacing string.length with a local variable, that is set once in the setup method. Result: smarterCount has runtime of about simpleCount. Before the change smarterCount took about 50% longer then simpleCount. smartCount did not change.
It looks like the optimizer looses the information of how many loops it will have to do when a call to another method occurs. That's the reason why finish() immediately ran faster with the constant set, but not smartCount(), as smartCount() has no clue about what i will be after the skip() step. So I did a second test, where I copied the loop from skip() into smartCount().
And voilà, all three methods return within the same time (800-900 ms).
My tentative guess would be that this is about branch prediction.
This loop:
for (int i = 0; i < string.length; i++) {
result += string[i] >= 128 ? 1 : 0;
}
Contains exactly one branch, the backward edge of the loop, and it is highly predictable. A modern processor will be able to accurately predict this, and so fill its whole pipeline with instructions. The sequence of loads is also highly predictable, so it will be able to pre-fetch everything the pipelined instructions need. High performance results.
This loop:
for (; i < string.length - 1; i++) {
if (string[i] >= 128) break;
}
Has a dirty great data-dependent conditional branch sitting in the middle of it. That is much harder for the processor to predict accurately.
Now, that doesn't entirely make sense, because (a) the processor will surely quickly learn that the break branch will usually not be taken, (b) the loads are still predictable, and so just as pre-fetchable, and (c) after that loop exits, the code goes into a loop which is identical to the loop which goes fast. So i wouldn't expect this to make all that much difference.

The Java search: "block"

Has anyone ever seen the following in Java?
public void methodName(){
search:
for(Type[] t : Type[] to){
do something...
}
}
Can someone point me to documentation on the use of "search:" in this context? Searching for "search:" has not been productive.
Thanks
It's a label. From §14.7 of the Java Language specification:
Statements may have label prefixes...
(Boring grammar omitted, pain to mark up)
Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.
One place you frequently see labels is in nested loops, where you may want to break out of both loops early:
void foo() {
int i, j;
outerLoop: // <== label
for (i = 0; i < 100; ++i) {
innerLoop: // <== another label
for (j = 0; j < 100; ++j) {
if (/*...someCondition...*/) {
break outerLoop; // <== use the label
}
}
}
}
Normally that break in the inner loop would break just the inner loop, but not the outer one. But because it's a directed break using a label, it breaks the outer loop.
This is an example of a labelled loop.
It allows you to break or continue the target loop instead of your current loop.
Outer:
for(int intOuter=0; intOuter < intArray.length ; intOuter++)
{
Inner:
for(int intInner=0; intInner < intArray[intOuter].length; intInner++)
{
if(intArray[intOuter][intInner] == 30)
{
blnFound = true;
break Outer; // this line breaks the outer loop instead of the inner loop.
}
}
}
example taken from : http://www.java-examples.com/java-break-statement-label-example
It is a Java label as defined here in JLS: http://docs.oracle.com/javase/specs/jls/se5.0/html/statements.html#78994

Categories

Resources