Sunday, August 18, 2013

Introduction to Java


Topics - This slide will cover

·         Java - What is Java?
·         Java Creation: problems & solutions
·         Why OOP? Why not C?
·         Benefits of Java over C++
·         Java Magic: The Byte Code
·         JVM, JRE & its working.
·         Evolution of Java (Version)
·         Evolution of Java (Edition)
·         Class & Object - Definition
·         Flavors of Variables in Java
·         Types of variables acc to Scope
·         Concepts of OOP
·         Abstraction
·         Encapsulation
·         Inheritance
·         Polymorphism
·         Constructors
·         Pointers (this & super)
·         Final
·         Abstract
·         Interface
·         Overloading
·         Overriding
·         Aggregation vs. Inheritance




What is Java

·         Java is Object Oriented Programming Language originally developed by James Gosling at Sun Microsystems (which is now subsidiary of Oracle Corporation) & released in 1995
·         Java programs are compiled to byte code that can run on any virtual machine irrespective of any operating system.


Java Creation: Problems

·         The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target. C / C++ compilers are not platform independent.
·         The programs written (in C / C++) for embedded devices require large memory. But the devices available at that time were not capable enough with large memory.

Java Creation: Solution

·         Java programs are written once and can be run anywhere. They compile java programs (byte codes) require JVM to be executed. JVM is platform dependent but Java is platform independent.
·         The original impetus for Java was not the Internet! Instead, motivation was the need for a platform-independent language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens. Java programs written for embedded devices require less memory compared to that require by C / C++.


Why OOP? Why not C

·         Although C is one of the world’s great programming languages, there is a limit to its ability to handle complexity.  Once  a  program  exceeds  somewhere between 25,000  and 100,000  lines  of  code,  it becomes so complex that it is difficult to grasp as a totality. C++ allows this barrier to be broken, and helps  the  programmer  comprehend  and  manage larger programs.
·         Real world problems can be easily mapped into software to get the solution.

Benefits of Java over C++

·         Simple: Programming syntax is simple, inspired by C / C++ syntax. Some of the more confusing concepts from C++ are either left out of Java or implemented in a cleaner, more approachable manner.
·         Platform independent: Java is platform independent. Ex: Variables (primitive or reference) are of fixed size. The size doesn’t vary from one OS to another. Programs once compiled can be run on any of the OS.
Features of Java
·         Distributed: Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. Java allows objects on two different computers to execute procedures remotely.
·         RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.

Features of Java - Secured

Java is Secured because:
• No explicit pointer
• Programs run inside virtual machine sandbox.


Features of Java

·         Multithreading: Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. 

·         Automatic Garbage Collection: Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many potential bugs and headaches. 

·         Exception Handling: Java provides an exception handling mechanism for systematically dealing with some unwanted error conditions.
·         Exception handling allows developers to detect errors easily without writing special code to test return values.
·         Even better, it lets us keep exception-handling code cleanly separated from the exception-generating code.



Java - The Architecture

Oracle/Sun: The two principal products in the Java SE platform are: Java Development Kit (JDK) and Java SE Runtime Environment (JRE)
·         JDK: is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.
·         The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. 


Java's architecture arises out of four distinct but interrelated technologies:
·         The Java programming language
·         The Java class file format
·         The Java Application Programming Interface
·         The Java virtual machine
The Java Virtual Machine 

·          
      Together, the Java virtual machine and Java API form a "platform" for which all Java programs are compiled.
·         In addition to being called the Java runtime system, the combination of the Java virtual machine and Java API is called the Java Platform.
·         At the heart of Java's network-orientation is the Java virtual machine, which supports all three prongs of Java's network-oriented architecture:
-          platform independence, security, and network-mobility.
·         A Java virtual machine's main job is to load class files and execute the bytecodes they contain.
The Java virtual machine contains a
A)     Class Loader: which loads class files from both the program and the Java API. Only those class files from the Java API that are actually needed by a running program are loaded into the virtual machine. This way less memory is required in running java program as compared to C / C++.
B)      Execution Engine: Where The bytecodes are executed in.

Java Magic: The Bytecode
        The key that allows Java to solve both the security and the portability problems is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for bytecode.
        Translating a Java program into bytecode helps makes it much easier to run a program in a wide variety of environments. The reason is straightforward: only the JVM needs to be implemented for each platform. Although the details of the JVM will differ from platform to platform, all interpret the same Java bytecode.
        The fact that a Java program is interpreted also helps to make it secure. Because the execution of every Java program is under the control of the JVM, the JVM can contain the program and prevent it from generating side effects outside of the system.


        Native methods are the connection between a Java program and an underlying host operating system.
        When a running Java program calls a native method, the virtual machine loads the dynamic library that contains the native method and invokes it.
        You can use native methods to give your Java programs direct access to the resources of the underlying operating system. Their use, however, will render your program platform specific, because the dynamic libraries containing the native methods are platform specific.



Evolution of Java
Evolution of Java (Version)
Version
Release Date
Code Name
JDK 1.0
1996-01-23
Oak
JDK 1.1
1997-02-18
Sparkler
J2SE 1.2
1998-12-04
Playground
J2SE 1.3
2000-05-08
Kestrel
J2SE 1.4.0
2002-02-13
Merlin
J2SE 1.5.0 / 5.0
2004-09-29
Tiger
Java SE 6
2006-12-11
Mustang
Java SE 7
2011-07-28
Dolphin

Evolution of Java (Edition)
        Java SE (Standard Edition): For general-purpose use on desktop PCs, servers and similar devices.
        Java EE (Enterprise Edition):  Java SE plus various APIs useful for multi-tier client-server enterprise applications.
        Java ME (Micro Edition): Specifies several different sets of libraries (known as profiles) for devices with limited storage, display, and power capacities. 

      Directory Structure of JDK




Class & Object – Definition

Classes reflect concepts, objects reflect instances that embody those concepts

        A class captures the common properties of the objects instantiated from it
        A class characterizes the common behavior of all the objects that are its instances

Objects as instances of Classes
        The world conceptually consists of objects many objects can be said to be of the same type or class
ü  My bank account, your bank account, Bill Gates’ bank account …
        Object is always created on Heap.
Instantiation: How an Object is instantiated from a Class
BankAccount myAccount;
 Reference variable of type BankAccount created
myAccount = new BankAccount;  A brand new object of BankAccount is created in Heap.  Reference variable myAccount holds the address of new object in Heap.



Flavors of Variables in Java
        Primitive variables
        Reference variables

Primitive variables

Variable
Type
Size (Byte)
byte
Integer
1
short
Integer
2
int
Integer
4
long
Integer
8
float
Floating point
4
double
Floating point
8
char
Character
2
boolean
Boolean
true / false

Reference variable
• Reference variables are variables of User Defined (Data) Type or System Type.
• They are of fixed size irrespective of the type they belong to. The size is dependent on the JVM.



Types of Variables according to scope
        Static Variable
        Non Static Variable
        Local Variable

Static variable (Class variable)
ü  Declared as static.
ü  Declared directly inside a class (outside any block / method)
ü  Single copy for a class.
ü  Shared among all object of that class
ü  Get default value if not initialized.


Non Static variable (Instance variable)
ü  Declared directly inside class (outside any block / method).
ü  Not declared as static.
ü  They have separate copy for each instance of the class, so not shared.
ü  Get default value if not initialized.
ü  Created & stored on Heap as they are part of instance.

Local (Automatic/Stack/Method) Variable
ü  Declared inside a block or method. Not declared directly inside the class. Cannot be declared static.
ü  There scope is the block in which they are declared.
ü  Just as the local variable starts its life inside the method, it's also destroyed when the method has completed.
ü  Method / block parameters are also local variables, local to that method.
ü  Stored on the run time stack (for that thread) & not on Heap.
ü  Don’t get the default value if not initialized. Need to be initialized before being used.

Variable Example

Test Your Skills
Flavor =>
Scope

Primitive
Reference
Static


Non Static


Local






Problem Description – An Example
“ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and transfer money between accounts

Procedural Approach
bool MakeDeposit(int accountNum,float amount);
float Withdraw(int accountNum,float amount);

struct Account {
                char *name;
                int accountNum;
                float balance;
                char accountType;
};

 
 







ü  Focus is on procedures
ü  All data is shared: no protection
ü  More difficult to modify
ü  Hard to manage complexity
Procedural vs. Object-Oriented


Object Oriented Model
Mapping the world to software
ü  Objects in the problem domain are mapped to objects in software


        Real World problem mapping with Software
        Re-usable
        Flexible
        Secured

Concepts of OOPs
        Abstraction & Encapsulation
        Inheritance
        Polymorphism








Abstraction
        Hiding of non essential data is called abstraction
        Exposing only essential data through methods.
        Ex: balance of an Account class must be hidden
        from outside world. Whereas account type can be public.
        Achieved by declaring the resource (property / behavior) as private.
        Benefit: Security.

Fields
class Account {
private float balance;
private float name;
private float accNum;
);
        The Private access modifier ensures that field can’t be updated from logic outside the class.
        We provide getter & setter to read & write these fields.




Encapsulation
        Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.
        The word encapsulation is originated from capsule which wraps the mixture of medicine powder in a single unit.
        We keep data (properties) and code (method / behavior) in a single unit called class.

Data Encapsulation
class Account {
- private float balance;                                   // Data
- public float withdraw();                              // Code
- public void deposit(float amount);        // Code
}

        Both data & code are (encapsulated) in class

Advantages of Encapsulation
        Protection
        Consistency
        Allows changes









Read-Only Properties
public int getName() {
return this.name;
}


Read-Write Properties
public int getName() {
return this.name;
}
public void setName(String localName) {
 this.name = localName;
}

Methods
        Behaviors, Operations, Responsibilities
ü  If objects are NOUNS
ü  Methods are VERBS
        Generally, they are public, so that some operations can be performed on objects.

Overloading Methods
        Can have many versions of a method
        Must have different signatures
        Signature includes method name & parameter list
        Return type can vary




Example: Class, Field, Method
public class Customer {
// Fields
private String fullName;

// Methods
public int addContact(String name, String dob) { // Business logic comes here
fullName = name;
return fullName.length();
}
public int editContact(String name, String dob) { // Business logic comes here
fullName = name;
return fullName.length();
}
}
 
 












Inheritance
        Inheritance is the process by which one object acquires the properties & behavior of another object.
        Ex: a Dog object can acquire properties (color, age) and behavior (run, sleep) from an Animal object.
        Benefit: Re-usability, Maintenance

Classification


Polymorphism
        Polymorphism (many forms) is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation.
        Ex: a vehicle move when there is green signal.
        It moves slowly in case of yellow signal.
        It stops when there is red signal.
        Benefit: Flexible and friendly for End-User.







Constructor
ü  Constructor is used to initialize a newly created object.
ü  Defines minimal data required to initialize object in a valid state
ü  It is a special method whose name is same as class name & which doesn’t return anything, not even void.
ü  Constructors cannot be inherited or overridden.
ü  They can be overloaded, but only in the same class.
ü  If not written, compiler provides the default implementation of a constructor.
ü  Default constructor (provided by compiler) has the same access identifier as of the class.
ü  Default implementation of constructor is:
[class-access-identifier] [class-name] () {
super();                                // calling super class constructor
}

Ex: public MyClass() {
Super();
}

ü  One constructor can call another overloaded constructor of the same class by using this().
ü  The this() call invokes the constructor with the corresponding parameter list.
ü  Java requires that any this() call must occur as the first statement in a constructor.
ü  The super() construct is used in a subclass constructor to invoke a constructor in the immediate superclass.
ü  This allows the subclass to influence the initialization of its inherited state when an object of the subclass is created.
ü  A super() call in the constructor of a subclass will result in the execution of the relevant constructor from the superclass, based on the signature of the call.
ü  A constructor in a subclass can access the class's inherited members directly (i.e., by their simple name).
ü  The keyword super can also be used in a subclass constructor to access inherited members via its superclass.
ü  if used, the super() call must occur as the first statement in a constructor, and it can only be used in a constructor declaration.
ü  This implies that this() and super() calls cannot both occur in the same constructor.
ü  Note that the body of the constructors is executed in the reverse order to the call order, as super() can only occur as the first statement in a constructor.
ü  This ensures that the constructor from the Object class is completed first, followed by the constructors in the other classes down to the class being instantiated in the inheritance hierarchy.
ü  If a constructor at the end of a this()-chain (which may not be a chain at all if no this() call is invoked) does not have an explicit call to super(), then the call super() (without the parameters) is implicitly inserted to invoke the default constructor of the immediate super class.
ü  In other words, if a constructor has neither a this() nor a super() call as its first statement, then a super() call to the default constructor in the super class is inserted.
ü  If a class only defines non-default constructors (i.e., only constructors           with parameters), then its subclasses cannot rely on the implicit super() call being inserted.
ü  This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments.



ü   
Pointers
ü  Pointers are not there in Java - fallacy.
ü  Java provides two pointers: this & super.
ü  The use of pointers in java is restricted.
ü  They can’t be modified. They behave as they are read only.
ü  They are available in non static context only.
ü  If not used, the pointers are implicitly used by compiler in non static context.
ü  Understand difference between this & this()




Final
        Used with:
ü  Variable
ü  Method
ü  Class
        Final means final. The resource cannot be modified anymore. So stop here if u want to modify the resource.
        Ex: final static int num = 3;

Final variable
        A final variable is a constant, despite being called a variable.
        Its value cannot be changed once it has been initialized.
        This applies to instance, static and local variables, including parameters that are declared final.
ü  A final variable of a primitive data type cannot change its value once it has been initialized.
ü  A final variable of a reference type cannot change its reference value once it has been initialized, but the state of the object it denotes can still be changed.
Final method
        When we do not want the behavior of a method be changed (by overriding in a subclass), declare the method as final.
        Ex: wait(), notify(), notifyAll() in Object are final.
        Final variables ensure that values cannot be changed, and final methods ensure that behavior cannot be changed.
Final class
        When we do not want our class be inherited or any of its method be overridden, declare the class as final. Ex: Math class is declared final.
        A final class cannot be extended. This implies that one cannot override any methods declared in such a class.
        Classes, cannot be both final and abstract at the same time.





Abstract
• When we do not want our class to be instantiated, declare the class as abstract.
• Abstract class means some of its behavior are known while some are unknown. So declare the methods with unknown behavior as abstract.
• If a class has (directly or inherited) one or more abstract method, class is also declared as abstract.
• It is the responsibility of sub class to provide implementation of that abstract method. Otherwise be itself declared as abstract.
• Abstract class may not have abstract method.
• Abstract class may have both abstract & concrete methods.
• Abstract class cannot be final. Why?
• Though abstract class cannot be instantiated, they may have constructor. Why?





Interface
• An interface defines a contract by specifying a set of method prototypes, but no implementation.
• The methods in an interface are all implicitly abstract and public by virtue of their definition.
• Interface is 100% abstract class with no concrete method.
• We write interface when the behavior of non of the method is known.
• It is the responsibility of implementing class to provide the definition of each method declared in the interface, otherwise be declared as abstract.

Classes versus Interfaces
• Classes are used to represent something that has attributes (variables, fields) and capabilities /responsibilities (methods, functions).
• Interfaces are only about capabilities.
• For example, you are a human because you have the attributes of a human (class).
• You are a plumber because you have the ability of a plumber (interface). You can also be an electrician (interface). You can implement many interfaces, but be only one class.





Bibliography
        Inside JVM by Bill Venners
        GC by Bill Venners
        Java 2 Complete Reference
        Programmer's Guide to Java™ Certification by Khalid Mughal
        SCJP Sun Certified Programmer for Java 5 Study Guide by Kathy Sierra and Bert Bates
        Wrox - Ivor Horton - Professional Java