Wednesday 30 September 2015

Java Variables

Variables

A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

You must declare all variables before they can be used. The basic form of a variable declaration is shown here:

                   data type variable [ = value][, variable [= value] ...] ;

It can be classified into three types:
  1. Local variables
  2. Instance variables
  3. Static variables
Local Variables:


  • Local variables are declared in methods, constructors, or blocks.

  • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.

  • Access modifiers cannot be used for local variables.

  • Local variables are visible only within the declared method, constructor or block.

  • Local variables are implemented at stack level internally.There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
Example Source code:
public class Test{

   public void pupAge(){

      int age = 0;

      age = age + 7;

      System.out.println("Puppy age is : " + age);

   }  

   public static void main(String args[]){

      Test test = new Test();

      test.pupAge();

   }



Output:
Puppy age is 7.

Instance Variables: 

  • Instance variables are declared in a class, but outside a method, constructor or any block. 

  • When a space is allocated for an object in the heap, a slot for each instance variable value is created.

  • when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.

  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.

  • Instance variables can be declared in class level before or after use.

  • The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However visibility for subclasses can be given for these variables with the use of access modifiers.

  • Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
Static Variable: 
  • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. 

  • There would only be one copy of each class variable per class,regardless of how many objects are created from it.

  • Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.

  • Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.

  • Static variables are created when the program starts and destroyed when the program stops.

  • Visibility is similar to instance variables. However, most static variables  are declared public since they must be available for users of the class.

  • Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null.Values can be assigned during the declaration or within the constructor. Additionally values can be assigned in special static initializer blocks.

  • Static variables can be accessed by calling with the class nameClassName.VariableName.

  • When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.
Example program for Instance and Static Variables:
package Variables;

public class Car {

int size;

float height;

static String carname;

public void drive(){

}

public void stop(){

int driver=5;

System.out.println("driver");

int i=8;

int a=9;

if(i<=5){

}

else{

System.out.println(a+"");

}

}

}

package Variables;

public class Maincar {

public static void main(String args[]){

System.out.println(i+"");

Car.carname="adi";

Car c1=new Car();

Car c2=new Car();

System.out.println(c1.carname);

System.out.println(c2.carname);

System.out.println(Car.carname);

c1.drive();

c1.stop();

c2.drive();

c2.stop();

c1.height=3;{

System.out.println(c1.height);

}

c1.size=7;{

System.out.println(c1.size);

}

c2.height=6;{

System.out.println(c2.height);

}

c2.size=9;{

System.out.println(c2.size);

}

}

}

output:

adi

adi

adi

driver

9

driver

9

3.0

7

6.0

9
 


Activity Life Cycle

Activity Life Cycle

Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.

An activity has essentially four states:  

  • If an activity in the foreground of the screen (at the top of the stack), it is active or running.
  • If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  • If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
  • If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. 

The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.


 There are three key loops you may be interested in monitoring within your activity: 

  • The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().

  • The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.

  • The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight. 

The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods.
Example :

public class Activity extends ApplicationContext {

     protected void onCreate(Bundle savedInstanceState);

     protected void onStart();

     protected void onRestart();

     protected void onResume();

     protected void onPause();

     protected void onStop();

     protected void onDestroy();
 }


In general the movement through an activity's lifecycle looks like this: 

OnCreate:

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.Always followed by onStart().

OnStart:

Called when the activity is becoming visible to the user.Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

OnResume: 

Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by onPause().

OnPause:

Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. 

OnStop: 

Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

OnDestroy: 
 The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method

OnRestart :


Called after your activity has been stopped, prior to it being started again.
Always followed by onStart()






Starting Another Activity


To start an activity from one activity we need Intent object and startActivity() method.

Intent:
  • An Intent provides a facility for performing late runtime binding between the code in different applications
  • Its most significant use is in the launching of activities, where it can be thought of as the glue between activities
  • It is basically a passive data structure holding an abstract description of an action to be performed.


Example :

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);

startActivity() ­ Method:

Launch a new activity:

Parameter

  Intent         The description of the activity to start.

This method throws ActivityNotFoundException if there was no Activity found to run the given Intent

Example :

Intent intent = new Intent (FirstActivity.this,SecondActivity.class);
startActivity(intent);


Finish() ­ Method:

Call this when your activity is done and should be closed.
  • If this method called from oncreate method then onDestroy method called immediately.
  • If this method called from onStart method then onStop wil be called and then it will go to onDestroy.



Tuesday 29 September 2015

Introduction to android

Introduction to android
  •     Android provides a rich application framework that allows you to build    innovative apps and games for mobile devices in a Java language environment.
  •     One of the most widely used mobile OS these days is ANDROID.
  •     Android is a software bunch comprising not only operating system but also middleware and key applications.
  •     Android Inc was founded in Palo Alto of California, U.S. by Andy Rubin in 2003.
  •     Later Android Inc. was acquired by Google in 2005.
What is Android?
    It most commonly comes installed on a variety of smartphones and tablets from a host of manufacturers  offering users access to Google’s own services like Search, YouTube, Maps, Gmail and more.
What can an Android phone do?


    Android phones are highly customisable and as such can be altered to suit your tastes and needs with wallpapers, themes and launchers which completely change the look of your device's interface.


    You can download applications to do all sorts of things like check your Facebook and Twitter feeds, manage your bank account, order pizza and play games. You can plan events on from your phone's calendar and see them on your computer or browse websites on your desktop and pick them up on your phone.


What apps can I get on an Android phone?

  •     There are hundreds of thousands of apps and games available to download from the Google Play store (formerly the Android Market).
  •     There are camera apps that allow you to take pictures with artistic effects and filters on them and music players which allow you to stream music from the web or create playlists.
  •     You can customise the appearance of your Android handset with a number of wallpapers based on pictures you’ve taken yourself or downloaded from the internet too.

Android Updates

  •     Google is constantly working on new versions of the Android software. These releases are infrequent; at the moment they normally come out every six months or so, but Google is looking to slow this down to once a year.
  •     Versions usually come with a numerical code and a name that’s so far been themed after sweets and desserts, running in alphabetical order.
    Android 1.5 Cupcake - APR 2009

    Android 1.6 Donut - SEP 2009


    Android 2.1 Eclair - OCT 2009


    Android 2.2 Froyo - MAY 2010


    Android 2.3 Gingerbread - DEC 2010


    Android 3.2 Honeycomb - MAY 2011 - The first OS design specifically for a tablets, launching on the Motorola Xoom


    Android 4.0 Ice Cream Sandwich- OCT 2011 - The first OS to run on      smartphones and tablets, ending the 2.X naming convention


   Android 4.1 Jelly Bean- DEC 2011 - Launched on the Google Nexus 7 tablet by Asus

    Android 4.2 Jelly Bean: Arrived on the LG Nexus 4


    Android 4.3 Jelly Bean


    Android 4.4 KitKat  - OCT 2013 - Launched on the LG Nexus 5


    Android 5.0 Lollipop - NOV 2014 -  Launched on the Motorola Nexus 6 and HTC Nexus 9\


    Android 6.0 Marshmallow - AUG 2015 - DEV PREVIEW


Monday 28 September 2015

JVM

Java Virtual Machine

History

Basics

Data Types

JVM Runtimes


History:

  •     Java platform was initially developed to address the problem of building s/w for n/w consumer devices.
  •     To meet requirements , compiled code has to transport across the networks ,works on any client and assure that the client that it was safe to run.
  •     WWW got popularized , but web HTML format was too limited . So the answer is extensibility in the way of HOTJAVA BROWSER.


  •     Hot Java Browser implements the java language and platform embedded into HTML webpages.Like HTML pages , compiled programs are n/w and host independent. The programs works the same way regardless of what machine they run on and where they come from.   

Basics-JVM:

  •     Cornerstone of the Java platform.
  •     is an abstract computing machine . It has its own instruction set and manipulates memory at runtime.
  •     Component of technology responsible for its h/w and os independence , a small class file of compiled code and ability to protect users from malicious programs
  •     Knows nothing of Java programming language only a binary format ie.., class file format. Class file format consists of
    JVM instructions (Byte code )

    Symbol table (key - value pair)

    Ancillary informations(Support info)

  •     Class file format is H/w and Os independent binary format   

Data Types:        

  •     VM operates on 2 kinds of Data Types
     1.Primitive types 2. Reference Types (class types , array types & interface types).
  •     These are the values actually that can be stored in a variable , passed as an argument and a value returned by methods.
  •     Jvm expects all type checking is done prior to the runtime , typically by a compiler .
  •     Explicit support for objects. An object is either dynamically allocated class instance or an array.
  •      reference to an object is considered to have a JVM reference types.
  •     Values of type references can be thought of as a pointer to objects. More than one pointers for an object can exist. Objects are operated via type references.

JVM Runime Areas:




 


PC Register:

  •     Each Jvm Thread has its own PC register
  •     Contains current executing method    
  •     Pc register holds any one of the follwing values
                   if method is not native , PC holds address of JVM instruction

                     if method is native , PC hold either undefined or return addresses(pointer to OPCODES of jvm)

JVM Stacks:

  •     Per thread
  •     Stores frames(data , partial results , dynamic linking,return method values , dispatch exceptions)
  •     Contains local variables , partial results and plays part in method invocation and return  

Heap:

  •     Common for all java threads
  •     Memory for all class instances and arrays are allocated
  •     Created on JVM startup
  •     Heap storage for objects is reclaimed by automatic management system(gc) , objects are never explicitly deallocated
  •     If your computation requires more memory than heap , then OUTOFMEMORYERROR

Method Area:

  •     Common to all Threads
  •     Contains per-class structures , runtime constant pool , field , method data , code for constructors & methods , instances and interface initialization
  •     Logically is a part of heap
  •     VM doesnot mandate location of method area or policies used to manage compiled code  

Run Time Constant Pool:

  •     Per Class/per Interface representation in .Class file
  •     Contains constants , ranging from numeric literals known at compile time to method/fields resolved at runtime
  •     Simillar to symbol table
  •     Allocated from the method area
  •     Pool for class/interface is constructed when class/interface is created by JVM

Native Method Stacks:

  •     Thread based not JVM based
  •     Stacks which assists in interpreting the language other than Java
  •     JVM cannot load native method stacks

                                                        


   





   





   

   

   

    







   

       

        

   





   

   

Introduction to Java

Introduction to Java Programming

Java is a powerful object-oriented programming language introduced by Sun Micro systems in 1995, which has built-in support to create programs with a graphical user interface (GUI), utilize the Internet, create client-server solutions, and much more. Programs written in Java can run, without change, on any of the common computer operating systems Windows 95/NT, Macintosh, and Unix. A variant of Java programs called applets can be embedded inside a web page and execute on the computer that is viewing the page, automatically and in a secure environment.

As a language, Java is closely related to C++, which is also object-oriented but retains a lot of idiosyncrasies inherited from its predecessor language C. Java has removed the inconsistent elements from C++, is exclusively object-oriented, and can be considered a modern version of C++ Because of its logical structure Java has quickly become a popular choice as a teaching language, and because of its extensive Internet support and the promise of writing programs once and using them on every operating system Java is becoming more and more accepted in industry.


Basic Java Programming Guidelines

Every Java program must follow these guidelines:

    Java is case sensitive, i.e. the word Program is different from program.
    Curly brackets { and } are used to group statements together.
    An executable Java program must contain at least the following lines as a framework:

    package com.sample;

    public class MainClass {

    public static void main(String args[]){

     }

    }


           Every statement whose next statement is not a separate group must end in a semicolon.
    A Java program containing the above framework must be saved using the file name MainClass.java, where MainClass (including correct upper and lower cases) is the word that follows the keywords public class and the file extension is .java.



Source Code

A Java source code file is a text file that contains programming code written according to the Java language specifications, resembling a mixture of mathematical language and English. A computer cannot execute source code, but humans can read and understand it.

Java source code files should be saved as Name.java, where Name is the name that appears in the first line of the program: public class Name. That Name is referred to as the name of the class, or program. By convention its first letter is capitalized.


      package com.sample;

      public class Test {

           public static void main(String args[]) {

           System.out.println("Hi this is my first program");
       
    }

}

Output:

Hi this is my first program


This program, or class, is called Test and must be saved under the file name Test.java.


Compiling a Java Program or Class

A source code file, which is more or less readable in plain English, needs to be transformed into another format before the computer can act upon it. That translation process is called compiling and is accomplished using the Java compiler javac from the Java Developer's Kit (JDK), which could be invoked by an IDE such as BlueJ.

Definition For Compiling

Compiling is the process of transforming the source code file into a format that the computer can understand and process. The resulting file is called the byte-code, or class, file. The name of the class file is the same as the name of the program plus the extension .class. The program javac from the Java Developer's Kit is used to transform a source code file into a class file.

If a source code contains any errors, they are flagged by the compiler. You need to fix them and re-compile until there are no further errors.

Tip: In case of an error, the javac compiler shows the line number and position of where it thinks the error occurred in your source code.

    If the compiler points out an error, then there is an error at or before the indicated position.
    If the compiler reports a certain number of errors, than this is the least amount of errors.
    If one error is fixed, other errors may automatically disappear or new ones may appear.


Executing a Java Program or Class

The Java compiler does not produce an executable file, so Java programs can not execute under the operating system of your machine. Instead they execute inside a Java Virtual Machine, which is invoked using the java program of the JDK.

Definition For Executing a Class File

To execute a Java program the Java Developer's Kit provides a program called java. When executing that program with your class file as parameter the following happens:

    the Java Virtual Machine (JVM) is created inside your computer
    the JVM locates and reads your class files
    the JVM inspects your class file for any security violations
    the JVM executes, or interprets, your class file according to its instructions if possible


Default Program Entry Point

The default program entry point is that part of a class (or program) where execution begins. For every Java class (or program), the standard program entry point consists of the line:

   public static void main(String args[])


If that line is not present in your source code, the JVM can not execute your program and displays an error message.

At this point, we need to explain what the Java Virtual Machine is and how it relates to the operating system and to Java class files.


Java Virtual Machine (JVM)

The Java Virtual Machine (JVM) is a platform-independent engine used to run Java applets and applications. The JVM knows nothing of the Java programming language, but it does understand the particular file format of the platform and implementation independent class file produced by a Java compiler. Therefore, class files produced by a Java compiler on one system can execute without change on any system that can invoke a Java Virtual Machine.

When invoked with a particular class file, the JVM loads the file, goes through a verification process to ensure system security, and executes the instructions in that class file.