100 likes | 348 Views
Constant Variables. Although the name may sound contradictory, (how can something be a variable and be constant?), you can make variables constant by putting the reserved word final in front of them.
E N D
Constant Variables • Although the name may sound contradictory, (how can something be a variable and be constant?), you can make variables constant by putting the reserved word final in front of them. • When you have constants in your program, the convention is to use all caps for the variable identifier, so it is easy to see it is a constant
Constant (Final) Variables • A constant must be declared and initialized before it can be used, and you cannot change the constant value once it is declared. • final double PI = 3.14159; • final int LUCKYNUMBER = 7;
Speaking of Coding Conventions... • Class names are typically written with the first letter capitalized • Non-constant variables are typically written in lower case • If your variable name is more than one word, capitalize the second word, like: int myName; • Variables should be named something that indicates what they will be used for...integer1, integer2, sum, and mean instead of w, x, y, z. • Whenever you have a curly brace (around the class, and around the main method), you should indent everything inside the braces, to show where it belongs
Shortcut Operators • Many times when you are writing code, you will take a variable, modify it, and reassign the results back to the same variable • Because of this, we have shortcut operatorsthat help make the code easier to write (but harder to read): i = i + 1; i++; x = x + 3; x+=3
Shortcut Operators Operator Example Equivalent += i+=8; i= i + 8; -= i-=8; i= i - 8; *= i*=8; i= i * 8; /= i/=8; i= i / 8; %= i%=8; i= i % 8;
Prefix & Postfix Operators • ++ and -- are two unique shortcut operators because, depending how they are used, have different operator precedence • i++ is the same as i = i + 1, and it is the LAST thing performed in the operation.It is called a postfix operator. • ++i is same thing as i = i + 1, but it is the FIRST thing performed in the operation.It is called a prefix operator.
Prefix & Suffix Operators • What is the difference? int x = 2; System.out.println(x++); //prints out 2, then //changes x = x+1; int y = 2; System.out.println(++y); //changes y = y+1, // then prints out 3;