I know I’m not going to be able to keep this up forever. Sooner or later my progress is going to stop. For now I hope I’m still making sense with what I’m posting. So let’s not delay and get my day 4 update out.
What Did I Learn Today
Java Variables: Variable is a name associated with a value that can be changed. Specifically, we name the address of where the value is stored in memory, instead of having to remember the complex memory address. When you declare a variable in java you need to specify the data type as well as the variable name, eg: int i = 10;
So declaring a variable data_type variable_name = value;
You can also declare the variable and then assign a value int i; i = 100;
Variable Naming Conventions: Variables names need to adhere to a set of standards during your code and these include.
Variables cannot start with white space
Variables can begin with a special character
Variable names should start with a lowercase and second words should start with a capital letter
Variable names are case sensitive
There are 3 types of Variables in Java:
Static or class variables: they are associated with the class and common for all instances of class. If you create an object from a class, the variable would be the same for each object. A static variable remains constant and cannot be changed. When declaring the variable you use the word static before declaring the variable, eg: public static String variableName="Variable";
Instance Variable: Instance variables are declared inside a class but outside and member, constructor of class. Each object has their own copy of the variable.
Local Variable: Variable declared inside the method of the class and their scope is limited to the method which means you can't change the variable or access them outside the method.
Code For The Day
Below is a sample program illustrating the use of Static, Instance and Local variables:
publicclassVariableExample{// instance variablepublicStringmyVar="instance variable";publicvoidmyMethod(){// local variableStringmyVar="Inside Method";System.out.println(myVar);}publicstaticvoidmain(Stringargs[]){VariableExampleobj=newVariableExample();System.out.println("Calling Method");obj.myMethod();System.out.println(obj.myVar);}}