title: Will this cause undefined behavior in Java?
body: <p>I'm working on a Java project and we have to implement a Caesar Cipher. I have all the code working, but I'm using this trick and I want to make sure that it's not going to result in undefined behavior. My understanding of Java's scope is that if I declare the <code>byte key</code> inside the function, then all references to it without using the keyword <strong>this</strong> will reference the local variable and using the keyword will reference the class field. I've tested the program and it works fine, but my experience with weird tricks is that they can cause undefined behavior and not work all the time.</p>
  
  <pre><code>Class Cipher {
      byte key = -1;
  
  ...
  
  String encrypt(String plaintext) {
      byte key = this.key;
      if(this.key == -1) {
            System.out.print("Please enter a key: ");
            key = input.nextByte();
      }
      ...
      }
  }
  </code></pre>
  
  <p><strong>Update:</strong> I forgot to give some context. When you construct the class, you have the option to specify a key or not specify a key, and when you don't specify a key it will prompt for one every time you call encrypt() or decrypt(). The variable key is then used inside the function to perform the ROT shift.</p>