CodingBison

Introduction

Term: JVM
Description: Java virtual machine, which is available in all the platforms that supports Java, converts the byte code into something that the platform understands. Thus, when we develop an application in Java, we don't have to worry about the platform on which it would be run, as JVM would automatically take care of the platform dependencies.

Term: Java keywords
Description: A "keyword" is something that cannot be the name of a variable/class/method etc. "class" is a keyword, this means you cannot have a variable/method with the name "class". There are quite a few key words defined in Java. class, int, for, while etc are few examples of keywords.

Class and Object

Term: Object
Description: Java objects are based on Java classes. You might say that a class is a blueprint of an object. So, what is an object? Well, an object is an instance of a class. An object stores the states (specific details) of the properties defined in the class.
Example: Here a "person" class is defined with 2 properties "name and ID". An object when instantiated and used, stores the specific properties. for example, "personName = James, personId = 32456", "personName = Wilson, personId = 32457" etc. We can instantiate as many objects as we want.
 class person {
   String  personName;
   double  personId:
 }
Term: Access Specifiers
Description: In order to restrict the scope of the elements, Java provides three types of access specifiers. public, private, protected ( All of these are Java Keywords). There is an other access specifier called as "Default access specifier". This specifier gets applied when none of the above 3 are specified.

Keyword: class
Description: A Java class is a collection of variables (called Properties) and functions (called methods). Properties store the data that is of interest to the class and methods define the function/logic that handles the data. Thus, with a class, you get the complete package;
Example: Here a "person" class is defined with 2 properties, "name and ID".
 class person {
   String  personName;
   double  personId:
   void setPersonName(String name) {
   }
   // Few other methods
 }

Data Types

Term: Primitive Data Types
Description: Like most of the programming language, Java allows us to store data of different types. Java supports a wide range of variable types.
Here is the list of the primitive data types supported by Java. Java Integers type includes int, short, byte, long and they store whole numbers, like 3,234,567. Java Floating type includes float, double and they store decimal numbers like 34.5, 56.7 etc. Java character type include char and it stores characters, symbols. 'c', 'g', '#' etc. Java boolean type is bool, and it stores just 2 values, TRUE or FALSE.

Term: Variable Scope
Description: Java allows us (Unlike, C Programming language which requires all the variables to be declared at the start of the function) to declare a variable as and when you need it. This brings in the concept "Scope of the variable". In general, a variable is visible to only certain block of a program. A variable declared at the start of the function is visible through out that function, but not to other functions. The visibility of a variable can be termed as the "scope" of the variable.
Example: As show in the below code snippet, a variable can be declared any where in the function. For example, variable "z" is declared at the end of the function and variable x is defined inside an if block, whose scope is limited only to that block.

 void function () { 
     int y;
     if (condition) {  // Scope of this blocks starts here. 
                       // What ever defined in this block is visible only to this block.
         int x = 10;  // x is declared inside this "if block".
         y = x;
     } // Scope of the block ends here.
     int z = 5;  // This statement throws an error, because x is not visible to this block of the code.
 }
Term: Type Casting
Description: We can copy a variable of type t1 to a variable of type t2, if t1 and t2 are of same type and t1 and t2 are compatible. However if t2 is larger than t1 and we try to copy, then the compiler may not be happy with that, for such cases you would need to use casting before the copying.
Example: Like shown in the above code snippet, typecasting can be done when the variables are of different types. Sometimes, implicit typecasting and some other times, typecasting needs to be done explicitly.

 int y = 20;
 long x = y; // x and y are of different types and hence typecasting is done here.
 	     // Since int and long are compatible, internal typecasting is performed by the compiler itself.
 long x;
 x = (long) y; // Though typecasting is not required, explicit typecasting "can" be done.
 int x = 20;
 byte y;
 y = x;  // This throws an error, compiler cannot do the implicit conversion because byte and int are not compatible. 
 y = (byte)x; // This requires an explicit conversion.
Term: Variable Operators
Description: Besides simple operators to do addition and multiplication, Java provides additional arithmetic operators as well: subtraction using "-", division using "/", modulo using "%" etc. We should note that the modulo operator has an important constraint: both of the variables should be integral (integer, short, char) and not float or double.
Java also provides a set of operators that operate the value of a variable. For example, if we were to increase the value of "var1" by 10, we could do "var1 = var1 + 10" or more crisply, "var1 += 10". Likewise, if we were to multiply the value of "var1" by 10, we could do "var1 = var1 * 10" or "var1 *= 10". Same rule applies to several other operators like subtraction "-"), division ("/"), modulo ("%"), bit-shifts ("<<" or ">>"), logical and ("&"), logical or ("|"), etc.
Another set of handy operators are the unary operators: "++" and "--", these operators increment and decrement an integer variable by 1 respectively. Thus, "var1 = var1 + 1" is same as "var1++". Likewise, "var1 = var1 -1" is same as "var1--".
However, we should note that the above unary operations can be applied either before or after a variable and accordingly, it can have different meanings. For example, "var1++" means that we use the variable first and then increment it, where as, "++var1" means we increment the variable first and then use it. Thus, "var2 = ++var1" and "var2 = var1++" mean different assignments to var2. It is a bad idea to have complicated expressions involving these operators; overzealous usage of these operators can create confusing statements that will reduce code-readability!

Term: Arrays
Description: Imagine if you want to declare a large number of variables of the same type ( Let us say N ), it is tedious to declare variables like var1, var2, var3 ......varN. Arrays will help you in avoiding the tedious effort of declaring N variables.
Array is a collection of similar variables. Size of the array can be defined, declaring an array of size N is equal to declaring N variables. Each array element is identified using an index. For an array with N values, the first element has an index of 0, the second element has the next index value of 1, and in the end, the last element has an index of (N-1). We can easily navigate, and update the integer values stored in this array.
Example: The following code has an example usage/syntax of an array in Java.


 Syntax for declaring an array .
 <array_type>  <array_variable_name>[] = new (special operator) <
 int arrayVar[];    // Declaring an array.
 arrayVar = new int[5]; // Allocating memory for (5 entries) an Array.
 /* The below statement can replace the above 2 statements */
 /* Single statement can be used to declare and allocate the space for an array*/
 int arrayVar[] = new int[5]; // This is how you declare and allocate space for an array.
 arrayVar[0] = 237;
 arrayVar[2] = 101;
Term: MultiDimensional-Arrays
Description: The arrays we have seen so far are single dimensional arrays. An array can also be a multi dimensional array. A multidimensional array is simply an array of arrays. Let us see how a multi dimensional array looks like.
Example: The following code has an example usage/syntax of a Multidimensional array in Java.


 Declaring an array .
 <array_type>  <array_variable_name>[][] = new (special operator) <
 Notice, mentioning the size of 2nd dimension is optional.
 Array type could be any basic data type, example int, double, float etc.
 int arrayVar[][] = new int[5][];
 double arrayVar[][] = new double[3][];
 This how a variable 2 dimensional array (like shown in the above figure) is declared.
 arrayVar[0] = new int[10] // Size of the 2nd dimension declared here is 10.
 arrayVar[1] = new int[4]  // Size of the 2nd dimension declared here is 4.
 arrayVar[2] = new int[6]
Term: Variable MultiDimensional-Arrays
Description: A multi dimensional array need not be as show in the below figure, we may want to have more flexibility with a multi dimensional array. Java's flexibility happily meets our demand, we can also have a multi-dimensional array, where each array is of different depth. Let us see another 2-dimensional array but this time with variable length.
Example: The following code has an example usage/syntax of a Variable-Multidimensional array in Java.


 Declaring an array .
 <array_type>  <array_variable_name>[][] = new (special operator) <
 Notice, mentioning the size of 2nd dimension is optional.
 Array type could be any basic data type, example int, double, float etc.
 int arrayVar[][] = new int[5][];
 double arrayVar[][] = new double[3][];
 This how a variable 2 dimensional array (like shown in the above figure) is declared.
 arrayVar[0] = new int[10] // Size of the 2nd dimension declared here is 10.
 arrayVar[1] = new int[4]  // Size of the 2nd dimension declared here is 4.
 arrayVar[2] = new int[6]
Term: Strings
Description: String is one of the widely used data types in any programming language. A string is basically a collection of characters. If you are familiar with "C" programming language, you would know how difficult it is manage string in C. In fact C programming language does not support string data type, a string in C is nothing but a character array. By comparison hand Java provides a much better support for Strings.
String is not a primitive data type in Java; it is actually a Class. When ever a string variable is created using "String <string-name>" we are actually creating an object of the class "String". String class in Java provides wide range of constructors and methods that can be used to manipulate the strings. Let us look at a sample program that helps in understanding the concept of String.

Example: The following example program demonstrates the usage of some of the utility methods provided by Java's String class that helps in manipulating the strings.

 public class StringExample {
     public static void main(String[] args) {
         String stringVar;
         stringVar =  "This is a String";
         String stringVar2 = " variable";
         // Declaration and assignment in the same line.
         // String string_var = "This is a String variable";
         System.out.println("String: " + stringVar + ", Length: " + stringVar.length());
         System.out.println("String: " + stringVar + ", Concatenated String: " + stringVar.concat(stringVar2));
         // Returns -ve number if the stringVar2 is lesser than stringVar, else  return +ve number.
         System.out.println("String: " + stringVar + ", Compare Strings: " + stringVar.compareTo(stringVar2));
         // Return the index of first occurrence of the character.
         System.out.println("String: " + stringVar + ", index of " + stringVar.indexOf('s'));
         System.out.println("String: " + stringVar + ", index of " + stringVar.lastIndexOf('s'));
     }
 }

Conditionals

Term: Conditional Operator
Description: conditional operator is an alternate way for "if-else" clause: "if (condition) ? do_this_1 : do_this2". If the "condition" is True, then Java runs "do_this_1", else, it runs "do_this_2".
Example: The below code snippet shows the syntax/usage of conditional operator.
 if (condition) ? do_this_1 : do_this2;
Keyword: if and if-else
Description: If the condition evaluates to True, then the program executes task pertaining to that condition otherwise it executes other task. NOTE: There could be an if condition alone with out an else part. "if and else" are 2 different keywords.
Example: The below code snippet shows the syntax/usage of if, if-else condition.
 // Usage of "if" condition.
 if (condVar > 5) {
    printf(" condVar is greater than 5");
 }
 // Usage if if-else condition.
 if (condVar > 5) {
   printf(" condVar is greater than 5");
 } else {
   printf(" condVar is lesser than or equal to 5");
 }
Keyword: if-elseif-else
Description: If the condition evaluates to True, then the program executes task pertaining to that condition otherwise it checks for the condition in the next if condition and it goes on until the condition is true. NOTE: If none of the conditions are true, the final else part is executed. If final else part is not available, then the control just goes out of the "if conditions" with out executing any statement. "if and else" are the 2 different keywords (They are the only 2 keywords), there is no such key word called "elseif". Please take a look at the below example.
Example: The below code snippet shows the syntax/usage of if-elseif-else condition.
 // Usage if if-elseif-else condition.
 if (condVar > 0 && condVar < 10) {
   printf(" condVar is between 0 and 10");
 } else if (condVar >=10 && condVar < 100) {
   printf(" condVar is between 10 and 100");
 } else if (condVar >= 100 && condVar < 200) {
   printf(" condVar is between 100 and 200");
 } else { 
   printf(" condVar is not in the range 0 to 200");
 }
Keyword: Switch Case
Description: Switch-case is an alternate way of using if-else-if. Switch statement is faster than if-else-if, as the control directly jumps to the appropriate "case" statement. Every "case" block should end with a "break" statement. "Default" is a catch all condition, if condVar does not match any of the case blocks; default block gets executed.
NOTE: switch, case, break, default are all keywords. condVar should be either an integer value or a character.
Example: The below code snippet shows the syntax/usage of switch-case.
 switch (condVar) {
 case 10:
   printf(" condVar value 10");
   break;
 case 20:
   printf(" condVar value 20");
   break;
 default:
   printf(" Default condition hit ");
 }

Loops

Keyword: while
Description: The looping happens as long as the specified condition is true and we quit the loop when the condition becomes false. Naturally, after every round, we need to update the loop state (or the condition variable) so that we can re-check if the condition has become true; In the below example,
Example: The while loop in the below example loops 5 times. Note - "while" is a keyword.
 condVar = 0;  // While loop condition - Initialization
 while ( condVar < 5 ) { // While loop condition - Check
     // Do something
     condVar++;  // While loop condition - Update.
 }
Keyword: for
Description: For loop has all the 3 phases of looping in one expression: initialization, conditional-check, and update conditional variable The first part of the for loop is the initialization (e.g., "counter=0"), the second part is the loop-termination (e.g., "counter < 3"), and the last part is updating the conditional variable (e.g., "counter++"). Note that both initialization and updating the loop state is done automatically by the for-loop. We just need to specify it in the for-expression.
Example: The for loop in the below example loops 5 times. Note - "for" is a keyword.
 for ( condVar = 0; condVar < 5; condVar++ ) {
     // Do something
 }
Keyword: do-while
Description: The do-while loop has a similar format to that of a "while" loop, except that the while clause sits at the very end of the loop block. The distinctive feature of this variant is that the looping block would get executed at least once. This happens because even if the condition is false, the program must run starting from "do" till the point where it reaches the "while" condition. For cases, where we need to run the loop for the first round, whether condition is met or not, we should consider deploying "do-while" method
Example: The for loop in the below example loops 5 times. Note - "do", "while" are keywords.
 condVar = 0;  // While loop condition - Initialization
 do {
     // Do something
     condVar++;  // While loop condition - Update.
 } while ( condVar < 5 ); // Do-While loop condition - Check
Keyword: continue
Description: Java provides methods for an application to be more selective when running inside a loop. There are two specific tasks that an application might wish to do when present in a loop: skip some of the records and break out of the loop. Java provides a keyword, "continue" that allows a program to skip a record.
NOTE: This keyword could be used in any of the loops (for, while, do-while).
Example: The below example illustrate the usage of the keyword "continue" with a for loop. The keyword "continue", does not impact the number of times the loop is executed, loop would still complete the full execution. In the below example, the statement above "continue" statement is executed all the time, and the statement below "continue" is executed only when the "condVar is an odd number". Thus, continue allows a program to skip a record/records.
 for ( condVar = 0; condVar < 5; condVar++ ) {
     System.out.println(" All numbers : " + condVar);
     // Skip all the even numbers.
     if (conVar%2 == 0)
 	continue;
     System.out.println(" Odd Numbers only : " + condVar);
 }
Keyword: break
Description: Java provides methods for an application to be more selective when running inside a loop. There are two specific tasks that an application might wish to do when present in a loop: skip some of the records and break out of the loop. Java provides a keyword, "break" that allows you to break out of the loop.
NOTE: This keyword could be used in any of the loops (for, while, do-while).
Example: The below example illustrate the usage of the keyword "break" with a for loop. The keyword "break", impacts the number of times the loop is executed, loop execution would end the moment a break statement is encountered. In the below example, the loop ends (control breaks out of the loop) as soon as the condition (condVar == 3) is hit.
 for ( condVar = 0; condVar < 5; condVar++ ) {
     System.out.println(" Only till 3 is executed : " + condVar);
     if (conVar == 3) {
 	System.out.println (" Break the loop when condVar is 3 ");
 	break;
     }
     System.out.println(" Nothing after 2 is printed : " + condVar);
 }

OOP Concepts

Term: Encapsulation
Description: Encapsulation is a process of binding data and the code that acts on the data. Class and object forms the core of the concept "Encapsulation". All the variables (Data) defined in the class can only be accessed by using the methods (Methods has the code/logic that acts on the data) defined in that class. So, a class binds data and the methods together which is precisely Encapsulation. "Object" which is an instance of a class helps in accessing the data using the methods defined in that class.

Term: Inheritance
Description: Inheritance is one of the core concepts of object oriented programming. Inheritance, as the name says, means inheriting some of the properties from parents or grand parents. Java has the concept of sub-class and super-class, sub-class can inherit some of the properties (not all properties) of its super-class. A sub-class can also define its own specific properties, thus a sub-class has the inherited properties plus its own sub-class properties. If we were to compare inheritance with a real life example, a child inherits some of the features from his/her parents at the same time has some features specific to him.

Term: Polymorphism
Description: The literal form of polymorphism is "Many forms". Java supports the concept of "Overloading", which lets us define one or more methods with the same name provided their signature is different. Overriding is another form of polymorphism where a super-class and sub-class can define the exact same method (including the signature).
Java also supports another behavior called run-time polymorphism, which means decision on which action to choose is taken at the run time.

Term: Abstraction
Description: Abstraction is a process of exposing only the required/essential features and hiding the internal implementation details. The term abstraction is very loosely defined and the boundaries are not as clear. The concept of abstraction is used in most of the OOP concepts, for instance when we define a class, it hides a lot of details and only expose few methods/properties. Java supports features like "interface and abstract class", where the concept of abstraction is more clearly visible.

Term: Constructor
Description: A constructor in Java has the same name as that of a class; notice the name "Movie" in the below example. The main purpose of a constructor is to initialize the objects, an object initialization is done as soon as they are created.
Example: In the below example, notice the name of the "constructor" same as that of class.
 class Movie {
      String name;
      int yearOfRelease;
      // Constructor
      Movie() {
          System.out.println(" Inside the constructor ");
          name = "Jame Bond Movie";
          yearOfRelease = 0000;
      }
      /*
       * There will be other things in the class.
       */
 }
Term: Default Constructor
Description: A constructor in Java has the same name as that of a class; notice the name "Movie" in the below example. The main purpose of a constructor is to initialize the objects, an object initialization is done as soon as they are created. A default constructor is one that takes no arguments, it initializes all the objects with the same default values.
Example: In the below example, notice the name of the "constructor" same as that of class.
 class Movie {
      String name;
      int yearOfRelease;
      // Default Constructor, initializes the object with default values.
      Movie() {
          System.out.println(" Inside the default constructor ");
          name = "Jame Bond Movie";
          yearOfRelease = 0000;
      }
      /*
       * There will be other things in the class.
       */
 }
Term: Parameterized Constructor
Description: A constructor in Java has the same name as that of a class; notice the name "Movie" in the below example. The main purpose of a constructor is to initialize the objects, an object initialization is done as soon as they are created. A parameterized constructor takes the arguments and initializes the object with the values passed (at the time of object creation) as arguments to the constructor.
Example: In the below example, notice the name of the "constructor" same as that of class.
 class Movie {
     String name;
     int yearOfRelease;
     // Parameterized constructor, initializes the objects with the parameters passed to it. 
     Movie(String name, int yearOfRelease) {
          System.out.println(" Inside the parameterized constructor,"
                          + " initializing the object, Movie Name: " + name);
          this.name = name;
          this.yearOfRelease = yearOfRelease;
      }
      /*
       * There will be other things in the class.
       */
 }
Keyword: this
Description: The main purpose of "this" key word is to reference the current object. When the names of the parameters passed to the constructor and the local variables used inside are same, the local variables corresponds to the "current" object, "this" key word references the current object and thus helps in differentiating the variable that has the same name.
Example:
 Class movie {
   String name;
   int yearOfRelease;
   movie(String name, int yearOfRelease) {
        System.out.println(" Inside the parameterized constructor,"
                            + " initializing the object, Movie Name: " + name);
        this.name = name;
        this.yearOfRelease = yearOfRelease;
   }
 }

Polymorphism

Term: Overloading (Method Overloading)
Description: This concept of having the same name for more than one method is called "overloading". If you are coming from "C programming" back ground, this sounds little crazy. But, yes Java supports "overloading" Thus, with overloading, 2 methods in Java can have the same name but their "signatures" (Signature is nothing but, methods return type, argument list, argument type) are different. One of the ways of achieving Polymorphism (which means "many forms") in Java, is through overloading.
NOTE:We could overload a method as many times as we want, method with 1 argument, method with 2 args and so on.
Example: In the below example, the method "add" has been overloaded.
 class overloading {
     void add (int x, int y, int z) {
       int sum = x + y + z;
       System.out.println (" Integer Sum : " + sum);
     }
     double add (double x, double y) {
        return x + y;
     }
 }
Term: Constructor Overloading
Description: Constructors follow the same semantics of a method, 2 or more methods can have the same name provided their signature changes. In the below example, we have overloaded the constructor, default constructor has zero arguments while the parameterized constructor has 2 arguments. This concept of having the same name for the constructors is called "Constructor overloading". We could overload constructor as many times as we want, constructor with 1 argument, constructor with 2 args and so on.
Example: In the below example, notice the name of the "constructor" same as that of class.
 class Movie {
     String name;
     int yearOfRelease;
     // Default Constructor, initializes the object with default values.
      Movie() {
          System.out.println(" Inside the default constructor ");
          name = "Jame Bond Movie";
          yearOfRelease = 0000;
      }
     // Parameterized constructor, initializes the objects with the parameters passed to it. 
     Movie(String name, int yearOfRelease) {
          System.out.println(" Inside the parameterized constructor,"
                          + " initializing the object, Movie Name: " + name);
          this.name = name;
          this.yearOfRelease = yearOfRelease;
      }
      /*
       * There will be other things in the class.
       */
 }

Inheritance

Term: Java Inheritance
Description: Inheritance is one of the key concepts of object oriented programming. Inheritance defines the hierarchical relationships between various classes. With inheritance, a generic class (aka super-class) can be defined with a set of generic properties. This generic class can then be inherited by any other class (sub-class). Sub-class can define its own specific properties, along with the ones that are inherited from its super-class. Thus a sub-class can pick and choose from its parent (or ancestor) class and also define its own.
NOTE: Inheritance in Java is achieved using the keyword "extends".

Term: Multilevel-Inheritance
Description: If needed, a sub-class can become a parent itself. This is called multilevel inheritance. Java allows inheritance at multiple levels. For example, we can have a sub- class sb3 inherit the properties of sb2, which in turn inherit the properties of sb1 and su1.
su1 -- sb1 -- sb2 -- sb3.
NOTE: Inheritance in Java is achieved using the keyword "extends".

Term: Multiple-Inheritance
Description: There is also yet another concept called multiple inheritance. In this method, a sub-class inherits properties from more than one super-classes. While multiple inheritance can be useful in some cases, Java "does not" support it because of the complexity it brings in. In order to gain the advantages of multiple inheritance, Java supports a concept called "Interface".
NOTE: Inheritance in Java is achieved using the keyword "extends".

Term: Overriding
Description: Overriding refers to a concept where, a method in the sub-class/sub-classes has the same name and same signature, as that of a method in its super class. Overriding unlike overloading allows us to have 2 or more methods with the same name and also the signature.
NOTE: Super keyword is used to access the super classes methods.
Example: In the below example, the method "method1" has been overridden.
 class movie {
    int method1(int var) {
    }
 }
 class jamesBondMovies extends movie {
    int method1(int var) {
    }
 }
Term: Runtime Polymorphism
Description: Run time polymorphism is a concept where, the decision to call the correct version (When the methods are overridden), of methods is determined at the run time based on the object type.
Example: Please take a look at Method overriding section on codingtree.com/java for an example.
 class movie {
    int method1(int var) {
    }
 }
 class jamesBondMovies extends movie {
    int method1(int var) {
    }
 }
Term: Abstract Class
Description: An abstract class, as the name says it is just declaration and, it does not have a concrete implementation. There would be many scenarios where a super-class is not aware of the content that goes into the methods, and only the sub-class that inherits it, would have that info. Accordingly, we can use the abstract class to mandate that every sub-class must define their own implementation of the abstract class.
NOTE: "abstract" is a keyword
Example: Notice the keyword "abstract" in-front of class name and also in-front of the abstract method.
 abstract class movie {
     String name;
     int    length;
     String director;
      /*
       * There will be other things in the class.
       */
      /* This is an abstract method, and the sub-classes will
       * have to implement it.
       */
      abstract void fillThePlotSummary(String summary);
 }
Keyword: extends
Description: The keyword "Extends" is used by a sub-class to inherit the properties from a super-class.
Example: In the below example, "movie" is a super class and "jamesBondMovies" is a sub-class. sub-classes will inherit the common properties from its super-class and also have their own set of specialized properties.
 class movie {
     String name;
     int    length;
     /*
      * There will be other things in the class.
      */
 }
 class jamesBondMovies extends movie {
    /* jamesBondMovies class inherits the properties
     * from its super class.
     */
 }
Keyword: super
Description: The keyword "super" has two use-cases. First, in the case of inheritance "super" keyword is used to call the super-class's constructor and second, it is used to access super-class's members.
Example: Please take a look at Inheritance section on codingtree.com/java for an example.

Keyword: final
Description: The keyword "final" has 3 use-cases. First, a class that has a "final" keyword in front of it cannot be extended, in other words final stops inheritance of a class. Second, The other power full concept of object oriented programming "overriding", can also be stopped by using the keyword "final". A method cannot be overridden if it has the keyword "final" in-front of it. Third, "final" keyword is used to "declare constant values". Thus a variable with the "final" keyword in-front of it cannot be assigned any other values. So, a final variable will have to be initialized.
Example: The below example declares a constant using the keyword "final".
 public class finalExample {
     public static void main(String[] args) {
         final int finalVar = 100;
         System.out.println(" Final variable value " + finalVar);
         // This is not allowed, this throws a compilation error.
         //finalVar = 200;
     }
 }
Keyword: static
Description: A variable declared static is instantiated only once and hence it is shared across all the object. A method that declared static has few restrictions, first, they can only call static variables inside its body. Second, they can only call other static methods and third, they cannot use the keywords "super" or "this".
NOTE: We don't need an object to invoke the static members of a class. All the static members can be directly invoked with the help of its class name, eg..staticClass.method1();.

Exception Handling

Term: Exception Handling
Description: An exception is an error condition that occurs at the run time. The reason for the runtime error/Exception could be many, like code error, system resources, invalid input etc. Some of the programming languages like C do not provide support for exception handling mechanisms, but Java has an effective way of handling exceptions.
A program with exception handling mechanism, will allow the program to continue execution even after an error in the program. With exception handling, the program is not terminated abruptly and it also give a better control on the program flow. Another advantage of exception handling is that, it gives the program a chance to rectify itself.
Java provides 2 keywords "try" and "catch" to deal with the exceptions in the code.

Term: Checked Exceptions
Description: The Exception class in Java, itself has 2 types (Runtime exceptions and IO exceptions) of subclasses under it. All the IO exceptions are called checked exceptions because compile throws an error if there are not handled. It is must that a program handles IO exceptions aka checked exceptions (Compiler checks if they are handled or not).
"File Not Found" exception is an example of checked exceptions.

Term: Unchecked Exceptions
Description: The Exception class in Java, itself has 2 types (Runtime exceptions and IO exceptions) of subclasses under it. Runtime exception also called unchecked exceptions are handled by the compiler during the runtime. Compiler does not catch these hence does not throw any compile time errors.
"Arithmetic exception" is an example of Un-checked exceptions.

Keyword: try/catch
Description: Java provides 2 keywords "try" and "catch" to deal with the exceptions in the code. Try/Catch block, all the code that needs to be protected from exceptions would be in the "try block" and the exceptions in the try block are caught in the "catch block".
NOTE: A try block can have multiple catch blocks, which indicates multiple types of exceptions could arise from the try block. It is also possible to have nested try/catch blocks.
Example:
 try {
    //Code that may cause an exception.
    } catch (Exception e1) {
       // Exceptions are caught in the catch block.
       System.out.println(" Catch Block, Generic Exception");
    }
 }
Keyword: throw
Description: Java run-time system handles all the standard exceptions. However, there would be some scenarios, where the statements are perfectly valid from Java run-time systems perspective, but the application would sill want to handle those scenarios as "exceptions". Thus, an application can trigger a new exception using the keyword "throw". This exception is treated just like any other runtime exceptions.
Example:
 try {
    //Code that may cause an exception.
    if (exception_condition) {
        throw new ArithmeticException(" Application's exception ");
    } catch(ArithmeticException e1)  {
        System.out.println(" Try Block-1:Catch Block, Arithmetic Exception " + e1);
    } catch (Exception e2) {
       // Exceptions are caught in the catch block.
       System.out.println(" Catch Block, Generic Exception");
    }
 }
Keyword: throws
Description: Unchecked exceptions are handled in 2 ways. First, using a try catch block. Second, using the keyword "Throws". Let us say, we do not want to handle the unchecked exception using the try/catch block and wanted others ( the caller of the method/code block where the exception is) to handle it, the keyword throws is used. The keyword "throws" indicates the callers/calling method to expect an exception and handle it.
Example:

Keyword: finally
Description: All the statements inside the finally block will be executed at the end of a try/catch block. Also, the statements inside finally block will be always executed (either way exception is hit or not). The "finally" code is used when an application want to close some sockets, file descriptor(fd), free some memory etc. A "finally" is optional, a catch block could be replaced by a finally block; try/finally or try/catch or try/catch/finally.

Packages

Term: No Access Specifier
Description: A class can have either "public or no access specifier". Variables, constructors, methods are allowed to have any access specifiers. The scope of the member/elements that does not have any specifiers is same as that of "protected".

Keyword: package
Description: When a Java application grows big, it would be difficult to maintain all the class/Java files that are present in the project. Accordingly, it would be nice to have a logical separation of classes depending on the module. This logical separation of name space is called a package. A package in Java is created with help of a keyword "package".
NOTE: "package" is a keyword.

Keyword: public
Description: A class can have either "public or no access specifier". Variables, constructors, methods are allowed to have any access specifiers. A member/element declared public is visible through out the application and this is the highest level of visibility that any Java element could get.
NOTE: "public" is a keyword.

Keyword: private
Description: Access specifier "private" is not allowed in-front of the key word "class". Variables, constructors, methods are allowed to have any access specifiers. A member/element declared private is not visible to anyone outside the class in which it is defined.
NOTE: "private" is a keyword.

Keyword: protected
Description: Access specifier "protected" is not allowed in-front of the key word "class". Variables, constructors, methods are allowed to have any access specifiers. A member/element declared protected is not visible to anyone outside the package in which it is defined.
NOTE: "protected" is a keyword.

Interface

Keyword: interface (Specifying Methods)
Description: The concept of "interface" is similar to that of an abstract class. The main difference between an interface and an abstract class is that, an abstract class will have 1 or 2 methods (not all methods in a class) that are defined as "abstract". Where as, with interface, we can achieve complete abstraction of a class. Interface will have all the methods declared, there would be no method definitions (Method body/logic). Its up to a class that "implements" an interface to implement all the methods present in the interface.
NOTE: interface, implements are keywords. Also, note that "interface" can be extended and all the concepts of inheritance that applicable to a class are also applicable to an interface.
Example:
 interface movieInterface {
     void fillThePlotSummary(String summary);
     // This interface could have many more methods.
 }
 // The class that implements the interface will have to implement the methods
 // defined in interface. In this example the method "fillThePlotSummary".
 class casinoRoyal implements movieInterface {
     String plotSummary;
     public void fillThePlotSummary(String summary) {
         this.plotSummary = summary;
     }
 }
Keyword: interface (Defining constants)
Description: An interface can also be used to define constants, variables etc. If you are familiar with "C" programming, this is similar to the way "#define" or constant are used. Example usage of interface for defining constants.
NOTE: interface, implements are keywords.
Example:
 File Name: sharedConstants.java
 -------------------------------
 public interface sharedConstants {
     String FIRST_PLACE = "Gold";
     String SECOND_PLACE = "Silver";
     String THIRD_PLACE = "Bronze";
 }

Garbage Collection

Term: Garbage Collection
Description: It is the responsibility of the application to release the memory (Dynamically allocated memory) back to the system at the end of its execution. If the memory used up by the application is not released, it leads to memory leaks and eventually the application will run out of memory. This concept of releasing/deallocating the memory back to the system is called Garbage collection. Java application does not have to worry about "freeing the memory/memory leaks" as Java runtime systems takes care of garbage collection internally.

Term: finalize method
Description: Java runtime system will not be able to free a non-java resource, as a part of garbage collection concept. File descriptors, sockets etc are some of the examples of non-java resources. Application will have to take up that responsibility with the help "finalize" method. Application has to define a method "protected void finalize()" and the logic to free up the non-java resources will be in this method. Java run time system invokes this method just before the garbage collector kicks in to free up the memory.





comments powered by Disqus