|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: Variables and Literals |
| 4 | +--- |
| 5 | + |
| 6 | +Variables can be broadly classified in to 2 types in Java: |
| 7 | + |
| 8 | +1. __Instance__ variables (declared in a class). |
| 9 | +2. __Local__ variables (declared inside a method). |
| 10 | + |
| 11 | +Instance variables and objects reside in heap whereas local variables reside in stack. Consider the below program: |
| 12 | + |
| 13 | +{% highlight java linenos %} |
| 14 | +class Collar { |
| 15 | +} |
| 16 | + |
| 17 | +class Dog { |
| 18 | + Collar c; // instance variable |
| 19 | + String name; // instance variable |
| 20 | + |
| 21 | + public static void main(String[] args) { |
| 22 | + Dog d; // local variable: d |
| 23 | + d = new Dog(); |
| 24 | + d.go(d); |
| 25 | + } |
| 26 | + |
| 27 | + void go(Dog dog) { // local variable: dog |
| 28 | + c = new Collar(); |
| 29 | + dog.setName("Aiko"); |
| 30 | + } |
| 31 | + |
| 32 | + void setName(String dogName) { // local var: dogName |
| 33 | + name = dogName; |
| 34 | + // do more stuff |
| 35 | + } |
| 36 | +} |
| 37 | +{% endhighlight %} |
| 38 | + |
| 39 | +For the above program, the instance variables, objects and local variables will be stored in memory as shown in the |
| 40 | +figure below: |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +### Literal Values for All Primitive Types |
| 45 | + |
| 46 | +A __primitive literal__ is merely a source code representation of the primitive data types—in other words, an integer, |
| 47 | +floating-point number, boolean, or character that you type in while writing code. The following are examples of |
| 48 | +primitive literals: |
| 49 | + |
| 50 | +{% highlight java %} |
| 51 | +'b' // char literal |
| 52 | +42 // int literal |
| 53 | +false // boolean literal |
| 54 | +2546789.343 // double literal |
| 55 | +{% endhighlight %} |
| 56 | + |
| 57 | +**Integer Literal** |
| 58 | + |
| 59 | +There are four ways to represent integer numbers in the Java language: decimal (base 10), octal (base 8), |
| 60 | +hexadecimal (base 16), and from Java 7, binary (base 2). |
| 61 | + |
| 62 | +One more new feature introduced in Java 7 was __numeric literals with underscores (_) characters__. This was introduced |
| 63 | +to increase readability. See below: |
| 64 | + |
| 65 | +{% highlight java %} |
| 66 | +int pre7 = 1000000; // pre Java 7 – we hope it's a million |
| 67 | +int with7 = 1_000_000; // much clearer! |
| 68 | +{% endhighlight %} |
| 69 | + |
| 70 | +But you must keep in mind the below gotchas: |
| 71 | +{% highlight java %} |
| 72 | +int i1 = _1_000_000; // illegal, can't begin with an "_" |
| 73 | +int i2 = 10_0000_0; // legal, but confusing |
| 74 | +{% endhighlight %} |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | + |
0 commit comments