Learn about the spec while shortening FizzBuzz written in Java

I will write it for the time being

class FizzBuzz{
    public static void main(String[] args){
        for(int i = 1; i <= 100; ++i){
            if(i % 3 == 0 && i % 5 == 0){
                System.out.println("FizzBuzz");
            }else if(i % 3 == 0){
                System.out.println("Fizz");
            }else if(i % 5 == 0){
                System.out.println("Buzz");
            }else{
                System.out.println(i);
            }
        }
    }
}

Try to shorten

Currently, the shortest Java source code for FizzBuzz seems to be 96byte . Let's shorten it because it's a big deal (what?).


Shorten using the conditional operator

class FizzBuzz{
    public static void main(String[] args){
        for(int i = 1; i <= 100; ++i){
            System.out.println(((i % 3 == 0 && i % 5 == 0) ? "FizzBuzz" : ((i % 5 == 0) ? "Buzz" : ((i % 3 == 0) ? "Fizz" : i + ""))));
        }
    }
}

The code will be convenient and easy to read if you do not make a mistake in using it. (Although I have different tastes) However, the above usage is overkill by any means, so do not do it unless you have a specific reason.


Devise an algorithm

This is a matter of pure idea or not. Daily training and sense are important. I think you should read a lot of good code and write a lot of code yourself.


Devise an algorithm

Code up to Java 1.4 (JLS 2nd Edition)

class FizzBuzz{
    public static void main(String[] args){
        for(int i = 1; i <= 100; ++i){
            System.out.println((i % 3 > 0 ? "" : "Fizz") + (i % 5 > 0 ? (i % 3 > 0 ? i + "" : "") : "Buzz"));
        }
    }
}

Devise an algorithm

Java5 (JLS 3rd Edition) and later code

class FizzBuzz{
    public static void main(String[] args){
        for(int i = 1; i <= 100; ++i){
            System.out.println((i % 3 > 0 ? "" : "Fizz") + (i % 5 > 0 ? (i % 3 > 0 ? i : "") : "Buzz"));
        }
    }
}

What's the difference?

--Until JLS 2nd Edition, the second and third expressions of the conditional operator had to return the same type. ――So, I forcibly make it a String with a power technique such as ʻi + "" . ――Ah, I didn't use String # valueOf` because I wrote it for short coding purposes. --The automatic type conversion rules have changed in JLS 3rd Edition so that i can now be passed without explicitly converting it to a String. --Relationship with auto boxing and generics introduced?


Reduce parentheses

class FizzBuzz{
    public static void main(String[] args){
        for(int i = 1; i <= 100; ++i)
            System.out.println((i % 3 > 0 ? "" : "Fizz") + (i % 5 > 0 ? i % 3 > 0 ? i : "" : "Buzz"));
    }
}

--If you understand the priority order of operators, you can reduce unnecessary parentheses. ――However, I think it is better to put parentheses appropriately so that the processing breaks can be clearly seen even if it becomes a little redundant so as not to impair readability. --The for block can also be deleted if there is only one sentence ――In addition, I personally usually do not omit parentheses even in one sentence for if and for blocks.


Increment specifications

class FizzBuzz{
    public static void main(String[] args){
        for(int i = 0; ++i < 101;)
            System.out.println((i % 3 > 0 ? "" : "Fizz") + (i % 5 > 0 ? i % 3 > 0 ? i : "" : "Buzz"));
    }
}

--In Java, the language specification guarantees the evaluation order of the increment operator, so if you use the pre-increment operator, it will always be incremented before ** <101 is evaluated. --Along with that, the start is changed from 1 to 0 --It has nothing to do with increment, but by the way, <= 100 is changed to <101 to reduce it by 1b.


Finish

class F{public static void main(String[]a){for(int i=0;++i<101;)System.out.println((i%3>0?"":"Fizz")+(i%5>0?i%3>0?i:"":"Buzz"));}}

Remove extra whitespace and line breaks to make variables a single character. Decent? This 130 bytes is the limit in the source code. Perhaps.


Thank you for the time being


A little digression

I have an array declaration thanks to short coding

String[]a

I noticed that I can write by sticking together like this. Also

String

[]

a

It doesn't matter if you disassemble it like this.

Well, I don't choose and use arrays on my own nowadays ...


Road to 96 bytes

At the beginning, I said that the shortest is 96 bytes, but in the previous code it is 130 bytes. In fact, it is still shorter with special conditions.


Take advantage of bugs

It seems that VMs up to a certain version have a problem, and it was possible to output characters without the main method. (With the current VM, nothing should work without the main method.)


Static initializer

class F{static{for(int i=0;++i<101;)System.out.println((i%3>0?"":"Fizz")+(i%5>0?i%3>0?i:"":"Buzz"));}}

It became 102 bytes. It seems that VMs up to a certain version will be executed in the static initializer earlier than the timing specified in the original VM specifications, and even such code will be executed. For this code, after FizzBuzz is run, I get angry that there is no main method.

By the way, a static initializer is a block of code declared in static that is executed only once when a class is loaded. Please google how to use it.


enum and instance initializer

enum F{A;{for(int i=0;++i<101;)System.out.println((i%3>0?"":"Fizz")+(i%5>0?i%3>0?i:"":"Buzz"));}}

It became 97 bytes.


enum

For Java enums, it's best to read Effective Java 2nd Edition. no doubt. As for the above code, it uses the following properties.

--enum is also a type of class --Fields, methods, and initializers can be defined only for classes. --The enumeration is an object of the enum and is instantiated when the enum is loaded


Instance initializer

An instance initializer is a block of code that runs only once when an instance is created. Called before the constructor. Please google how to use it. I don't think there are many opportunities to use it.


Field has default value

enum F{A;int i;{for(;++i<101;)System.out.println((i%3>0?"":"Fizz")+(i%5>0?i%3>0?i:"":"Buzz"));}}

The last 1 byte was reduced by using the property that the field has a default value (int is 0) so that you don't have to explicitly assign 0.


Summary

By short coding with FizzBuzz

--Conditional operator --Operator precedence --Increment operator --Static initializer --Instance initializer

I was able to learn the specifications of. Even though it's FizzBuzz, you can't underestimate it! !!


Thank you for your hard work

Recommended Posts

Learn about the spec while shortening FizzBuzz written in Java
FizzBuzz in Java
About the confusion seen in startup Java servers
About the idea of anonymous classes in Java
A story about the JDK in the Java 11 era
Think about the JAVA = JAVAscript problem (needed in the future)
Think about the differences between functions and methods (in Java)
About abstract classes in java
Access the network interface in Java
Guess the character code in Java
About the symbol <%%> in Rails erb
Learn about transaction savepoints (with Java)
Specify the java location in eclipse.ini
How to learn JAVA in 7 days
Unzip the zip file in Java
About the current development environment (Java 8)
Parsing the COTOHA API in Java
Expression used in the fizz_buzz problem
About file copy processing in Java
Call the super method in Java
A story about a Spring Boot project written in Java that supports Kotlin
[Ruby basics] About the role of true and break in the while statement
About the phenomenon that StackOverflowError occurs in processing using Java regular expressions
About returning a reference in a Java Getter
Get the result of POST in Java
Guess about the 2017 Java Persistence Framework (3) Reladomo
Spring Autowired is written in the constructor
Java reference to understand in the figure
Try using the Stream API in Java
Call the Windows Notification API in Java
About the procedure for java to work
[Creating] A memorandum about coding in Java
About the new Java release model @ Seki Java (2018/07/20)
I tried the new era in Java
[Java] Use cryptography in the standard library
Organized memo in the head (Java --Array)
Try calling the CORBA service in Java 11+
About Records preview added in Java JDK 14
What is the main method in Java?
How to get the date in java
Continued Talk about writing Java in Emacs @ 2018
The story of writing Java in Emacs
Console input in Java (understanding the mechanism)
Learn Flyweight patterns and ConcurrentHashMap in Java
Impressions and doubts about using java for the first time in Android Studio
About the meaning of type variables, E, T, etc. used in generics used in Java