Monday, 24 October 2016

RunTime Memory Utilization in Java

How to find How much memory is consumed in Program ->
Refer below link to make blog.
http://www.javaworld.com/article/2150208/java-language/a-case-for-keeping-primitives-in-java.html

Primitives and Wrapper Classes


Not everything in Java is an object. There is a special group of data types (also known as primitive types) that will be used quite often in your programming. For performance reasons, the designers of the Java language decided to include these primitive types.
The primitive data types are not objects; they do not belong to any class; they are defined in the language itself.

Why Java use primitives?
Creating an object using new isn’t very efficient because new will place objects on the heap. This approach would be very costly for small and simple variables. Instead of create variables using new, Java can use primitive types to create automatic variables that are not references. The variables hold the value, and it’s place on the stack so its much more efficient.
               Java determines the size of each primitive type. These sizes do not change from one machine architecture to another (as do in most other languages). This is one of the key features of the language that makes Java so portable.
Take note that all numeric types are signed. (No unsigned types).
Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas Wrapper classes are stores information about complete class.

See Below examples -
The first Println will print true whereas the second one will print false. The problem is when comparing two wrapper class objects we cant use == operator. It will compare the reference of object and not its actual value.
Also if you are using a wrapper class object then never forget to initialize it to a default value. As by default all wrapper class objects are initialized to null.
The above code will give a NullPointerException as it tries to box the values before comparing with true and as its null.

 Now, why Java use Wrapper Classes? 
            As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type.
             It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
Practical Usage -
1.To convert simple data types into objects
2.To convert numeric strings into numeric values

Advantage of primitives over wrapper classes -
1. Primitives uses less memory than wrapper classes.  
 Memory utilization
A double in Java always occupies 64 bits in memory, but the size of a reference depends on the Java virtual machine (JVM). My computer runs the 64-bit version of Windows 7 and a 64-bit JVM, and therefore a reference on my computer occupies 64 bits. Based on the diagram in Figure 1 I would expect a single double such as n1 to occupy 8 bytes (64 bits), and I would expect a single Double such as n2 to occupy 24 bytes — 8 for the reference to the object, 8 for the double value stored in the object, and 8 for the reference to the class object for Double. Plus, Java uses extra memory to support garbage collection for objects types but not for primitive types. Let's check it out.
   
2. Primitives are faster in performance than Objects.
Means,Operations with primitives takes less time than operations with wrapper classes.

Imp Link ->
http://www.javaworld.com/article/2150208/java-language/a-case-for-keeping-primitives-in-java.html


Saturday, 22 October 2016

Array

Array -
It is container Object that holds fixed no of elements of single type.

//Declaration
int[] arr = new int[10]
or
int[] arr ={1,2,3,4,5,6,7,8,9,10}
In declaration we can place [] whenever we want.
int[] arr
int arr[]
int []arr

All are valid cases.
//coping Array 
System.copyArray (copyFrom,2,copyTo,0,7) 
will copy Array From  copyFrom[] 3rd element onwards to copyTo
Algorithm to search data in array 

1. Linear Search Algorithm -
It starts searching the data at index 0 and continues examining successive elements until data is found or no more elements remain to examine.

Pseudocode  -














Actual Code -

DataStructures And Algorithms

Data-structures and Algorithms are the 2 very important topics in Computer Science.
Both affect the memory usage(for data-structure) and CPU Time (algorithm that interacts with data-structure)
                 Sometimes we discover inverse relationship between memory usage and CPU Time.
Eg. Array and Doubly Linked List
Greater the memory used by Doubly Linked List faster is searching and deletion algorithm.
And opposite is true in case of Array.
  
What is Data-structure ? 
         It is a Container class that provides storage of data items and capabilities for storing and retrieving data items.
Eg.Array, Linked List, Stack. Queue etc.

What is Algorithm ?
It is a sequence of instructions that accomplishes a task in finite time frame.
         It receives zero or more input but produces at least one output.
Eg. Linear Search,Bubble Sort,Stack push and pop ,Queue push and delete 

Algorithm representation -
Algorithms are represented by java source code.
         Flowchart is a visual representation of algorithm.





Tuesday, 18 October 2016

File Paths

File path is computer programming is always relative to your current directory.
Relative Directory - from where you are accessing data.

Absolute Path -
1 ..\abc.txt  - (2 dots) Parent dir of your current directory
2..\abc.txt  (1 dot) Current dir
3...\..\abc.txt - (2-2dots) Parent of Parent of current dir

Thursday, 13 October 2016

Core Java Basics

Java Basics Best Tutorials - Javapoint Tutorials .(www.javapoint.com)

1.Single Line  -  // This is comment
2.Multiple Line - /* This is comment.*/
3.Document Comment -/** This is document details */

Variable Types -
1.Instance - In the class, outside method.
Called so because it gets memory at runtime. (When instance of class is created) 
Belong to each instance.
2.Static -with static keyword,outside method
Belong to class
\It gets memory once at the time of class loading.
Stored in Class Area of memory.
3. Local - inside method.

Keywords -
Break - To jump out of current loop.
Continue - To skip current flow of loop

this - Refers object of current class
super - Refers to object of Parent Class

Eg. this.variable , this.method(),this(); (for variable,method and constructor respectively.)

      super.variable, super.method(),super();

Compiling Java Code -
1.Save file as name.java
   If Class defined has public visibility - file name must be as same as class name.
   If Class defined has default visibility -  file name and class name can be different.
2. javac fileName.java (Note *- javac filename will give runtime error. It must have ".java" suffix)
  This makes .class file from .java
  No.of class files = no. of classes in java file.
3.java fileName  (Note* -  java fileName.class will give runtime error.Do No add .class suffix)

Summary -  Step 2 and Step 3 are exact opposite.

JVM -
It has below components -
1.Classloader - to load the classes 
2.Memory Area
             2.1 Heap - where All Objects are stored. (new keyword.) - at JVM instance creation
             2.2 Class Area - store Field , Method Data , Code for class method and constructors -  at   JVM instance Creation
             2.3 Stack- store frames which hold local variable, partial results and return values - created by Thread 
            2.4 Native Method Stack - helps to execute on native methods for JVM support (non-java methods) - created by Thread
            2.5 PC(Program Counter) Register - It has the address of the executing instruction of current thread - created by Thread
3.Execution Engine - Like JavaScript Engine (V8 Chrome Engine)
It has sub components.
             3.1 Interpreter - reads bytecode and send instructions to CPU
             3.2 JIT Compiler - compiles byte code in class file to machine code  and let CPU execute it.

Note* - JVM on the spot decides whether to use Interpreter or JIT based on performance needed.

Now what is the difference between javac and JIT compiler ? 
 javac - compiles java code to byte code. Byte code is understood by JVM.
            This is used in compilation of .java File to .class File
JIT compiler - compiles byte code to machine code.Byte Code is understood by CPU.
                        This is used in the java execution of byte code.

Arithmetic  Exception -
It is Runtime Exception thrown when when an "Integer is divided by 0" .
It is only thrown for Integer Class.
Eg.
100/0 - Arithmetic Exception (Int/Int)
0/0     -Arithmetic Exception  (Int/Int)
0/0.0 or 0.0/0 -NaN (Because Both are not Int)  -Only In Case on Both zero but not Int
100/0.0 - Infinity
1.0/0.0 - Infinity 

OOPS Concept -
1.Polymorphism -
2.Inheritance - IS-A Relationship (Part Of  Relationships)
3.Abstraction
4.Encapsulation

1.Association - HAS-A Relationship (One Class owns another.) 
Classified as -
         1.Composition - If Owner is destroyed, No existence of components
            Eg. Car Class with Components such as  Engine Class , Tyre Class, Steering Wheel Class
                   If Car is destroyed no Meaning of Engine,Tyre,Wheel etc.
                   UML Representation - Filled Diamond
         2.Aggregation  - If Owner is destroyed, Still components exist.
            Eg. School Class with Component such as Teachers or Students
                  If School is destroyed Still Meaning to Teachers and Students.     
                  UML Representation - Empty Diamond
Summary -
Association is used for code reusability.

2.Polymorphism -
            1.Method Overloading - Static Polymorphism (Compile Time)
              1.Change in method Return type can not create overloading.
              Because compiler gets ambiguity while calling  methods (compile Time error )
              2.Type Promotion happens when method is not found by Interpreter.
            2.Method Overriding   - Dynamic Polymorphism (Run Time)
               1.Overriding method must have equal or lesser restrictive access modifier.
               2.Exception Handling-
                          2.1 If Parent class method does not declare Exception. --> Then Child method class cannot declare    Checked Exception but can declare Unchecked Exception(Runtime.)
                          2.2 If Parent class method declare Exception -->The Child Class method can declare same,subclass of Parent class Exception or no Exception.
                              But It can not declare Parent Exception of Parent Class Exception.
              

 Here Static binding means Object Type is determined at Compile Time by JVM.
          Dynamic binding means Object Type is determined at Run Time by JVM.

class Parent(){
public void m(){syso("Parent")}
}

class Child(){
public void m(){syso("Child")}
public String m(String str){syso("abc"+str)}

Child c = new Child(); //Child reference -Child Object 
Parent p = new Parent();//Parent reference -Child Object
Parent pc = new Child //Parent reference -Child Objcet

c.anyMethod(). //invokes all methods from Child
p.anyMethod().//invokes all methods from Parent

pc.m("Hello") //Compilation error.

Because Parent reference cannot access Child class methods.(unless overridden)


3.Abstraction -
         It is process of hiding the implementation and showing only functionality.
How to Achieve ?
1.Abstract Class - 0 to 100 %
2.Interference - 100% 
       Both cannot be instantiated.
       
Access Modifier -

4.Encapsulation -
It is process of wrapping code and data together in a single unit.
Eg. Java Bean Class - example of 100 % Encapsulation.
why ?
1. To make class read only or write only.
2. To provide control over data.





Object Class -
hashCode() -gives hashCode of object
equals()      -compares given Object to this object
toString()   - gives String representation of object
notify()      - wakes up single thread ,waiting on object's Monitor
notifyAll() -wakes up all call waiting on object's Monitor
finalize()    -invoked by gc before garbage collection
clone()        - returns exact copy of Object -

Cloning ->
Implement Cloneable Interface ,and override Clone() method.
This is shallow Cloning.
Test t2 =t1.clone();     //Here making copy of t1.
Need of Cloning?
It is created same copy as original.
It saves time while processing as compared to new keyword.

Equality Test with cloning.  
t1 == t2 //false  Because both are diffrent objects
t1.equals(t2)   //false   Since equals override it internally checks ==

Difference between Shallow Copy and Deep Copy
In Deep copy , Component Of Copied Class is also copied.
In Shallow copy, Component Of Copied Class is not copied but shared.
Link ->http://javaconceptoftheday.com/difference-between-shallow-copy-vs-deep-copy-in-java/
Eg. Science Class is Component of Student Class.



 

Tuesday, 11 October 2016

Concept of HashCode and equals in Java

hashcode() and equals() are method of Object Class in Java.
Both methods represent identity of an object.

Now,what is the use of these methods ?
hashcode() -
Whenever an object is created ,an hashcode is assigned to it by java.
Hashcode is an integer value and it is returned by hashcode().

Hashtables and Hashmaps use this hashcode to store Objects in it.
equals() -
This method uses Object references to check equality of two objects.

Note**-
If one of this method is overridden then other must also be overridden.

Contract between hashcode() and equals()-

1.Whenever hashcode() is invoked more than once during execution of method,hashcode()
   must give same value ,provided equals method is not modified during this method.
             Means, if you place a object in hashmap and you want to get the same object passing key
 then you cannot change  the key of the same object in between put() and get() operation.

2. If 2 objects are equal then their hashvalues must be equal.
3. If 2 objects are not equal doesn't mean that 2 objects have different hashvalues.
  Means 2 different objects can have equal hashcode.

Why do we need to override hashcode()? 
Consider key in Hashmap of Integer class,which does not override hashcode().
 Hashmap map = new Hashmap();

    Imp Link-->
    http://howtodoinjava.com/core-java/basics/working-with-hashcode-and-equals-methods-in-java/
    

 
 
    

Thursday, 6 October 2016

How to create simple javaScript Project for NodeJS Server

A. Creating Simple JavaScript Project using NodeJs Framework -

1. Open command Prompt and cd to New Folder

2. Run npm init
It will create package.json.
This file is main configuration file of nodeJs project.

New Folder is root directory.

3.Now install npm modules(JavaScript Libraries) using --> npm install
It will create npm_modules folder with js files defined in package.json

4.Create server.js file to create HTTP server.

Then hit http://localhost:8080/abc.

sample code -

var http = require("http");
http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
--------------------------------------->
Connection Issue - ECONNREFUSED;
Solution -
npm config set proxy  http://your_proxy_name:port

npm config set https-proxy https://your_proxy_name:port
npm config set proxy http://rilproxy2.rolta.com:8080 
npm config set https-proxy http://rilproxy2.rolta.com:8080


B. Creating Simple JavaScript Project using ExpressJS Framework -
This is as same as the above project creation.Only difference is that it gives us direct API to develop web app.
For ex.
In NodeJS Framework we have web  app after importing 'http' nodeJS API.
to create server, whereas in case of Express it gives same functionality with lesser code.We just need to import 'express' module to create server to handle http requests.

var express = require('express');
var app = express();

app.listen(3000,function(){
console.log("Express Framework is up and live at port 3000");
})

app.get('/',function(req,res){
res.send('Hello Express...');
})

C. Creating Simple JavaScript Project Skeleton using Express Generator -
 It helps to create full standard web application skeleton.

Wednesday, 5 October 2016

JavScript CallBacks

JavaScript callbacks are asynchronous.
This means that they will run when required, not necessarily in the order in which they appear in your code.

Tuesday, 4 October 2016

JSON Basics

JSON - JavaScript Object Notation

Often JSON is confused with JavaScript Object

It is JavaScript based approach to data exchange.
It is an alternative for xml.

Advantages -
1.Lighter and more Flexible than xml.
2.Language Independent 
It can transfer data from one language to another without modification (serialization). 

JavaScript Object Literal -
It is JavaScript object with key value pair .
Eg. var name = {"fname":"Tushar","lname":"Patil"};

Conditions -
1.Key must be a String.
2.Key does not need double quotes unless it is JavaScript reserved word.
Value can be anything such as Object ,function, Array, Nested Objects etc.

How to access properties of JavaScript Object Literals?
1. dot notation - (Refer above example)
   name.fname
   name.lname

2.braces -
  name['fname'];
  name['lname']; 

How JSON is Different from JavaScript Object Literal ?
Since JSON is supported throughout almost all languages, it has different set of conditions to be met.
Conditions -
1. All  keys and strings must have double quotes.
2. Functions are not a supported data type.

Data Types in JSON-
As same as JavaScript data Types  except Functions.







Variable Hoisting Problem in JavaScript

JavaScript by default, hoist all the variable at the top of scope.
This may create unexpected results.

Always declare variable at top of scope in JavaScript.

Check below example.


How to assign local variable value to global variable in JavaScript?

I often face this problem while using callback functions.
I want to store local variable value to global variable value  OR
I want to fetch value got in callback function outside the function scope.

Finally I found a Solution.

Use String to append the object  in callback function and extract global variable outside the scope of function.

Refer below image: