JAVA PROGRAM EXECUTION | ACTUALLY WHAT HAPPENS

JVM, JRE and JDK

Java Virtual Machine is a program that runs precompiled Java programs, which means JVM executes .class files (bytecode) and produces output. The JVM is written for each platform supported by Java. Included in the Java Runtime Environment (JRE). The Oracle JVM is written in the C programming language. There are many JVM implementations developed by different organizations. They may somewhat differ in performance, reliability, speed and so. They can too differ in implementation specially in those features where Java specification does not mention implementation details of the feature. Garbage collection is the nice example which is left on vendor’s choice and Java specification does not provide any implementation details.

JRE is an implementation of the JVM which actually executes Java programs. It includes the JVM , core libraries and other additional components to run applications and applets written in Java. Java Runtime Environment is a must install on machine in order to execute precompiled Java Programs. JRE is smaller than the JDK so it needs less Disk space and it is so, because JRE does not contain java compiler and other software tools needed to develop Java programs.

Java Development Kit is needed for developing java applications. It is a bundle of software that are used to develop Java based applications. It includes the JRE, set of API classes, Java compiler, Webstart and additional files needed to write Java applets and applications.

Inheritence | Downcasting and Upcasting

Just because you’re an Animal doesn’t mean you’re a Cat. You could be a Dog. That’s why it’s illegal to cast an Animal into a Cat.

On the other hand, is every Cat an Animal? The answer is “yes”. That’s why you could write code like this:

Animal animal = new Cat();

or

Cat cat = new Cat();
Animal animal = cat;

Also what’s worth noting is you can do this:

Animal animal = new Cat();
Cat cat = (Cat) animal;

The reason you can do this is that your animal variable is actually referencing a Cat instance. Therefore you’re allowed to cast it back into a variable that references a Cat.

Menu In Android

Creating Menus in Android
This could be done in 2 ways: XML and Java. But the preferred way to do is through XML .Simply, to keep the designing and the logic of the system differently.

Create -> new XML (mymenu.xml) -> Select the Menu (radio button). Through that you make that xml file a menu .On finishing it .We could also see a menu folder has been created in the res folder .

Now to create an item for the menu that is mymenu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu

  xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/item1" android:icon="@android:drawable/ic_menu_compass">
</item>
<item android:id="@+id/item2"  android:icon="@android:drawable/ic_menu_call">
</item>

</menu>

I am thinking, what the hell is ic_menu_compass right?

Well first of all since we want to put an icon with the menu out there we have customized our item tagby adding an attribute to it “android:icon”. And ic_menu_compass is the System icon that is present in the android.jar package.

ICON
ICON2

Keep going unless you get it.

Then, you see a lot of .png files and in that you will see a group of “ic” prefixed image files. There you could find ic_menu_compass. And, we need a reference to that beautiful thing.
Come to your Java file:

package com.menuinflator;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MenuInflatorTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) { //Called everytime menu is being clicked.
		// TODO Auto-generated method stub
		Toast.makeText(getBaseContext(),"Prepared menu so called",4000).show();
		
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) { //used for the initialization purposes. Called once
		// TODO Auto-generated method stub
		Toast.makeText(getBaseContext(),"Menu Creating!",4000).show(); 
		getMenuInflater().inflate(R.menu.mymenu,menu);
		return true;
		
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		
		switch(item.getItemId())
		{
		
		case R.id.item1:
			Toast.makeText(getBaseContext(),"Slected" + featureId, 4000).show();
			break;
		case R.id.item2:
			Toast.makeText(getBaseContext(),"Item2 Selected", 4000).show();
			break;
		}
		return true;
	}
    
}


Click on the #menu on the Emulator. The toast gets printed. And now even if you click on menu again and again it never gets printed.

onCreateOptionsMenu() : This method has been overridden. And, it gets called just for the first time when the options of the menus are going to be created. Then, never in life will they show their faces. Remember it!
And run the program.

public boolean onOptionsItemSelected (MenuItem item)

Added in API level 1
This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item’s Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Derived classes should call through to the base class for it to perform the default menu handling.

Parameters
item The menu item that was selected.
Returns
boolean Return false to allow normal menu processing to proceed, true to consume it here.

public boolean onMenuItemSelected (int featureId, MenuItem item)

Added in API level 1
Default implementation of onMenuItemSelected(int, MenuItem) for activities. This calls through to the new onOptionsItemSelected(MenuItem) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don’t need to deal with feature codes.

Parameters
featureId The panel that the menu is in.
item The menu item that was selected.
Returns boolean

Return true to finish processing of selection, or false to perform the normal menu handling (calling its Runnable or sending a Message to its target Handler).

Android Introduction

 

android

Android is a complete operating environment based upon the Linux® V2.6 kernel. Initially, the deployment target for Android was the mobile-phone arena, including smart phones and lower-cost flip-phone devices. However, Android’s full range of computing services and rich functional support have the potential to extend beyond the mobile-phone market. Android can be useful for other platforms and applications. In this article, get an introduction to the Android platform and learn how to code a basic Android application.Introduction

The BlackBerry and iPhone, which have appealing and high-volume mobile platforms, are addressing opposite ends of a spectrum. The BlackBerry is rock-solid for the enterprise business user. For a consumer device, it’s hard to compete with the iPhone for ease of use and the “cool factor.” Android, a young and yet-unproven platform, has the potential to play at both ends of the mobile-phone spectrum and perhaps even bridge the gulf between work and play.

Today, many network-based or network-capable appliances run a flavor of the Linux kernel. It’s a solid platform: cost-effective to deploy and support and readily accepted as a good design approach for deployment. The UI for such devices is often HTML-based and viewable with a PC or Mac browser. But not every appliance needs to be controlled by a general computing device. Consider a conventional appliance, such as a stove, microwave or bread maker. What if your household appliances were controlled by Android and boasted a color touch screen? With an Android UI on the stove-top, the author might even be able to cook something.

In this article, learn about the Android platform and how it can be used for mobile and nonmobile applications. Install the Android SDK and build a simple application. Download the source code for the example application in this article.

A brief history of Android

The Android platform is the product of the Open Handset Alliance, a group of organizations collaborating to build a better mobile phone. The group, led by Google, includes mobile operators, device handset manufacturers, component manufacturers, software solution and platform providers, and marketing companies. From a software development standpoint, Android sits smack in the middle of the open source world.

The first Android-capable handset on the market was the G1 device manufactured by HTC and provisioned on T-Mobile. The device became available after almost a year of speculation, where the only software development tools available were some incrementally improving SDK releases. As the G1 release date neared, the Android team released SDK V1.0 and applications began surfacing for the new platform.

To spur innovation, Google sponsored two rounds of “Android Developer Challenges,” where millions of dollars were given to top contest submissions. A few months after the G1, the Android Market was released, allowing users to browse and download applications directly to their phones. Over about 18 months, a new mobile platform entered the public arena.

Back to top

The Android platform

With Android’s breadth of capabilities, it would be easy to confuse it with a desktop operating system. Android is a layered environment built upon a foundation of the Linux kernel, and it includes rich functions. The UI subsystem includes:

  • Windows
  • Views
  • Widgets for displaying common elements such as edit boxes, lists, and drop-down lists

Android includes an embeddable browser built upon WebKit, the same open source browser engine powering the iPhone’s Mobile Safari browser.

Android boasts a healthy array of connectivity options, including WiFi, Bluetooth, and wireless data over a cellular connection (for example, GPRS, EDGE, and 3G). A popular technique in Android applications is to link to Google Maps to display an address directly within an application. Support for location-based services (such as GPS) and accelerometers is also available in the Android software stack, though not all Android devices are equipped with the required hardware. There is also camera support.

Historically, two areas where mobile applications have struggled to keep pace with their desktop counterparts are graphics/media, and data storage methods. Android addresses the graphics challenge with built-in support for 2-D and 3-D graphics, including the OpenGL library. The data-storage burden is eased because the Android platform includes the popular open source SQLite database. Figure 1 shows a simplified view of the Android software layers.

Constructors

class B
{
	B()
	{
		System.out.println("Ha ha ha. I am always called first");
	}
}

class A extends B
{
	A()
	{
	
		this("Samarth");
	}
	A(String s)
	{
		System.out.println("Hi this is "+s+" I am in Constructor A that has been called by this");
	}
}

class TestCons
{
	public static void main(String args[])	
	{
		A a=new A();		
	}
}

Why Abstract Classes have Constructors?

 
Many of you would always have a question on your mind that if we can’t instantiate the abstract classes then why do we have constructors of the same. Well, obviously.

But actually what happens. A constructor in Java doesn’t actually “build” the object, it is used to initialize fields.Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created.

So you create a constructor and initialize these fields.Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don’t do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.


Copy the code given below, run it. And then see what the output is.

abstract class A1
{
	A1()
	{
		System.out.println("Hi I am in abstract class");
	}

}
class  A extends A1
{
	A()
	{
                //super(); implicitly called. Remove the comments and check
		System.out.println("Hi! I am called!" );
	}
	public void show(){
		System.out.println("Hello!");
	}
}

public class B
{
	public static void main(String args[])
	{
		A a1=new A();
		a1.show();
	}
}

Output
Hi! I am in abstract class
Hi! I am called!
Hello!

Simply, it may not be getting accessed directly but indirectly through it’s subclasses. There is just not the only thing you see is happening. There are other ways of implementation that has to be worked upon to keep the way the Java Programming language works.

How to start it in your PC

To write your first program, you’ll need:

  1. The Java SE Development Kit 7 (JDK 7)You can download the Windows version now. (Make sure you download the JDKnot the JRE.) Consult the installation instructions.
  2. A text editorIn this example, we’ll use Notepad, a simple editor included with the Windows platforms. You can easily adapt these instructions if you use a different text editor.

These two items are all you’ll need to write your first application.

Creating Your First Application

Your first application, HelloWorldApp, will simply display the greeting “Hello world!”. To create this program, you will:

  • Create a source fileA source file contains code, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files.
  • Compile the source file into a .class fileThe Java programming language compiler (javac) takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes.
  • Run the programThe Java application launcher tool (java) uses the Java virtual machine to run your application.

Create a Source File

To create a source file, you have two options:

First, start your editor. You can launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad. In a new document, type in the following code:

/**
 * The HelloWorldApp class implements an application that
 * simply prints "Hello World!" to standard output.
 */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose the File > Save As menu item. Then, in the Save As dialog box:

  1. Using the Save in combo box, specify the folder (directory) where you’ll save your file. In this example, the directory is java on the C drive.
  2. In the File name text field, type "HelloWorldApp.java", including the quotation marks.
  3. From the Save as type combo box, choose Text Documents (*.txt).
  4. In the Encoding combo box, leave the encoding as ANSI.

When you’re finished, the dialog box should look like this.

TEXT The Save As dialog, as described in the text. 

The Save As dialog just before you click Save.

Now click Save, and exit Notepad.

Compile the Source File into a .class File

Bring up a shell, or “command,” window. You can do this from the Start menu by choosing Command Prompt (Windows XP), or by choosing Run… and then entering cmd. The shell window should look similar to the following figure.

a window where you can enter DOS commands 

A shell window.

The prompt shows your current directory. When you bring up the prompt, your current directory is usually your home directory for Windows XP (as shown in the preceding figure.

To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is java on the C drive, type the following command at the prompt and press Enter:

cd C:\java

Now the prompt should change to C:\java>.


Note: To change to a directory on a different drive, you must type an extra command: the name of the drive. For example, to change to the java directory on the Ddrive, you must enter D:, as shown in the following figure.Changing directory on an alternate drive 

Changing directory on an alternate drive.


If you enter dir at the prompt, you should see your source file, as the following figure shows.

Directory listing showing the .java source file. 

Directory listing showing the .java source file.

Now you are ready to compile. At the prompt, type the following command and press Enter.

javac HelloWorldApp.java

The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type dir to see the new file that was generated, as shown in the following figure.

Directory listing, showing the generated .class file 

Directory listing, showing the generated .class file

Now that you have a .class file, you can run your program.

If you encounter problems with the instructions in this step, consult the Common Problems (and Their Solutions).

Run the Program

In the same directory, enter the following command at the prompt:

java HelloWorldApp

The next figure shows what you should now see:

The program prints Hello World! to the screen. 

The program prints “Hello World!” to the screen.

Congratulations! Your program works!

Introduction to Java

images

So, you are here to learn Java hmm?Do you even know why?Do you know what forced everyone to come up with an idea to have a programming language like java. We already had a hell lot of them. So, why came Java?

Java is an object-oriented programming language with a built-in application programming interface (API)(If you don’t understand what an API is. Assume it as a THING. A THING that has got stuff to help us code. A way ,a process through which we can code. )

Much of the syntax of Java is the same as C and C++. One major difference is that Java does not have pointers(Good for you).

In Java we distinguish between applications, which are programs that perform the same functions as those written in other programming languages, and applets, which are programs that can be embedded in a Web page and accessed over the Internet. Our initial focus will be on writing applications. When a program is compiled, a byte code is produced that can be read and executed by any platform that can run Java.

And recently, Oracle bought it from Sun Microsystems. So, don’t even think it’s going to loose it’s scope. You can find Java everywhere. Mobiles, PDA’s, MicroOvens and where not. So learn java and do something great.
While learning, always think that it’s just a language. Just like the other languages you use while talking. But, the difference here is, in this case, you talk to a MACHINE.

At the end, want to tell you just one thing #Welcome to the world of Java

Related articles