Friday, November 14, 2014

How Java Differs From C And C++




Although Java was modelled after C and C++ languages, it differs from C and C++ in many ways. Java does not incorportae a number of features available in C and C++. For the benefit  of C and C++ programmers, we point out here a few major differences between C/C++ and Java language
Java and C
Java is not lot like C but the major difference between Java and C is that Java is and object-oriented language and has mechanism to define classes and objects. In an effort to build a simple and safe language, the Java team did not include some of the C features in Java.
  • Java does not include the C unique statement keywords sizeof, and typedef.
  • Java does not contain the data type struct and union.
  • Java does not define the type modifiers keywords auto,extern,register,signed, and unsigned.
  • Java does not support an explicit pointer type.
  • Java does not have a preprocessor and therefore we cannot use # define, # include, and # ifdef statements.
  • Java requires that the functions with no arguments must be declared with empty parenthesis and not with the void keyword as done in C.
  • Java adds new operators such as instanceof and >>>.
  • Java adds labelled break and continue statements.
  • Java adds many features required for object-oriented programming.

Java and C++
Java is a true object-oriented language while C++ is basically C with object-oriented extension. That is what exactly the increment operator ++ indicates. C++ has maintained backward compatibility with C. Is is therefore possible to write an old style C program and run it successfully under C++. Java appears to be similar to C++ when we consider only the “extensions” part of C++. However, some object -oriented features of C++ make the C++ code extremely difficult to follow and maintain.
Listed below are some major C++ features that were intentionally omitted from java or significantly modified.
  • Java does not support operator overloading.
  • Java does not have template classes as in C++.
  • Java does not support multiple inheritance of classes. This is accomplished using a new feature called “Interface”.
  • Java does not support global variables. Every variable and method is declared within classes and forms part of that class.
  • Java does not use pointers.
  • Java has replaced the destructor function with a finalize() function.
  • There are no header  files in Java.
Java also adds some new features. While C++ is a superset of C, Java is neither a superset nor a subset of C or C++. Java may be considered as a first cousin of C++ and a second cousin of C

Thursday, August 21, 2014

Running a Java Program from Command Prompt



  • Create a temporary folder C:\mywork.  Using Notepad or another text editor, create a small Java file HelloWorld.java with the following text:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
  • Run Command Prompt (found under All Programs/Accessories in the Start menu).  Type
C:\> cd \mywork
  • This makes C:\mywork the current directory.
C:\mywork> dir
  • This displays the directory contents.  You should see HelloWorld.java among the files.
C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin
  • This tells the system where to find JDK programs.
C:\mywork> javac HelloWorld.java
  • This runs javac.exe, the compiler.  You should see nothing but the next system prompt...
C:\mywork> dir
  • javac has created the HelloWorld.class file.  You should see HelloWorld.java andHelloWorld.class among the files.
C:\mywork> java HelloWorld
  • This runs the Java interpreter.  You should see the program output:
Hello, World!
  • It is possible to make the path setting permanent but you have to be very careful because your system might crash if you make a mistake. Proceed with extreme caution!
;C:\Program Files\Java\jdk1.5.0_09\bin

  • Save your file as HelloWorld.java in C:\mywork.  To make sure your file name isHeloWorld.java, (not HelloWorld.java.txt), first choose "Save as file type:" All files, then type in the file name HelloWorld.java
  • If the system cannot find javac, check the set path command.  If javac runs but you get errors, check your Java text.  If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command.  Java is case-sensitive! 
  • In Windows XP, go to Control Panel, choose "System," click on the "Advanced" tab, click on the "Environment variables" button. In the lower list, "System variables," click on Path:

    Click "Edit" and at the end append
    (or the path to the appropriate folder where the latest version of JDK is installed).  Do not put spaces before the appended path string.
    Click OK on the path edit box and OK on the Ennvironment Variables box.  The new setting will go into effect next time you run Command Prompt.

Wednesday, July 2, 2014

HelloWorld APP First Project

Introduction

This tutorial is a starting point for developing Android apps. It will explain the very basics of the Android SDK (Software Development Kit) and how to use it with Eclipse. To understand this tutorial, you don't need to have any knowledge about programming in Java, but it might be helpful for further programming to understand the basics of object orientated programming. This tutorial explains Android beginners how to create an Android Project in Eclipse, work with resources, and create some first code.

Setup Eclipse and the Android SDK

If you don't already have a running environment to develop Android apps, follow the instructions at this link.
Hint: PATH means the Path Environment Variable. In Windows, you will find it under "Control Panel/System/Advanced System Settings/Environment Variables" in the lower list box. You can check what version of Java is installed, by going in the command line and typing java -version.

Let's Get Started

Now we want to create our first application, which is (as always) a Hello World application. First of all, start Eclipse. Then select "File/New/Project". In the "New Project" dialog, select "Android/Android Project" and click "Next".
New_Project_empty.jpg
Here you can set up the project. First of all, we need to give the project a name, so type "Hello World" in the name box. Next you have to select the Android version you want to use. Here we choose version 2.2. As we see in the last column, we need the API Version 8 for this Android version, so we type an "8" in the Min SDK Version box. Also, the project requires an application name. (Notice that this name is also used in code, so the name should have no whitespaces). Usually, you use the project name and delete all whitespaces (e.g., "helloworld" for this project). Next, you have to define the package of the project. We will use "com.test.helloworld" here (a package can group multiple classes; for more information, see here). At least, you need a name for the activity (one App might have multiple Activities; they are like a single part/screen of the app). In this example, we simply use "HelloWorldApp".
New_Project.jpg
Before we can finally start our first project, we need to create a configuration. This configuration specifies under which circumstances the app will be started. E.g., you can control the network speed the emulator/app can use. Also, you can choose different emulators to test the app with different versions of Android or in different screen sizes. To create the configuration, go to "Run/Run Configurations". Now click the "Android Application" tab at the side and then the New button above the tabs. Call the new configuration "HelloWorldConfig" and select our project over the Browse button. Now move on to the target tab. Here you can select the network speed and which emulator will be used.
Run_Config_Screen.jpg
Since we haven't created an emulator till now, we need to do that first. Click the automatic control to enable the buttons at the side and then click on the manager-button. Here, click the new button to the right to create a new emulator. In the following screen, you can enter a name for the emulator (I have used "DefaultAndroidEmulator") and specify the details (like Android version, SD card size, and much more). You can control every little detail of the emulator over the hardware section.
Create_Emulator_.jpg
Once you are done with that, click "Create AVD" and close the manager window. Now we have successfully created the run configurations. Click "Apply" and close the configurations. At least run your first Android project.
Notice: It may take the emulator some time to get started, so be patient! Also, I have cropped the image so that you can't see the keyboard or the D-pad.
Congratulations! You just created your first App!
First_App_.jpg

Coding is Fun

After we have set up everything, it's (finally) time to actually getting started with the code, because we all know: Coding is fun!
But before we can actually jump into the Java code, we need to understand the structure of an Android Application. Go to your Package Explorer and enlarge the "Hello World" project. You will see five folders and two files. Let's get started with the one of these two files, the AndroidManifest file. This file contains all the information about your project, like the icon, the name of the author. To open it, make a right click on it and choose "Open With/Android Manifest Editor". In the upcoming tab, you can specify the package name and the version of your project. At the bottom, you will find additional tabs. I think most of the settings you will find are pretty much self-explanatory. Note the @ in front of some attributes. This shows that the following string is a reference to a resource. You can find the resources in the "res" folder of your project. If you enlarge it, you will notice that it has some subfolders. To be specific, the res folder can have seven types of subfolders: values, drawable, layout, animations, xml, styles, and raw.
Let's focus on the values folder first. Here you can store all kinds of simple resources (like strings, colors, numbers, dimensions, arrays, etc.). By default, you will find the strings.xml file in there. When you open it (with right click, "Open with/Android Layout Editor"), you will see that it contains two values. The first is the message you see when you run your project, and the second is the name of your app. You can add new values if you want to use them later on in code (or in the Manifest or Layout files). You can also create specific resources using quantifiers. If you add a - to the folder's name, you can add a quantifier to the name. E.g., you can rename the values folder to values-en which means that the content of the folder is only used by Android phones with English language activated. If you do not add a quantifier, the resources are default. The default resources are used if no specific resources for the current system are found. If the project is started, all resources will be compiled as efficiently as possible and added to the package. Also, a reference will be created (called R) which allows you to access the resources in code. Since this is only a tutorial, I will not focus on all the types of resources here. You can find more information on resources and quantifiers here.
At last, it is time to start coding! Go to the "src" folder. In the folder, you will find the package folder, open the HelloWorld.java file. You will see the default code for an Android Activity:
package com.test.helloworld; //the package we are working in

//some android packages we need to import
import android.app.Activity;
import android.os.Bundle;

//our activity class (extendes the default activity class)
public class HelloWorldApp extends Activity {
    /** Called when the activity is first created. */
    @Override
    //the function called when activity is created
    public void onCreate(Bundle savedInstanceState) {
        //call the create fct. Of the base class
        super.onCreate(savedInstanceState);
        //load the layout specified in the layout.xml
        setContentView(R.layout.main);
    }
}
As you can see, we create a new activity by extending the default Android activity class. Then we override the default onCreate function, which is called when the project is created. In there, we load our own layout from the resources and also call the onCreate function of the base class. Now let's take a closer look at the layout file. You find it in the layout folder under resources. When you open it, it should look like this:
<linearlayout android:layout_height="fill_parent" 
    android:layout_width="fill_parent" android:orientation="vertical" 
    xmlns:android="http://schemas.android.com/apk/res/android" />
      <textview android:layout_height="wrap_content" 
        android:layout_width="fill_parent" android:text="@string/hello" />
</linearlayout />
You see the root node is called LinearLayout. As you you might already have figured out, there are different types of layouts:
  • FrameLayout: All controls (children) are placed in the upper left corner.
  • LinearLayout: All children are positioned in vertical/horizontal order.
  • RelativeLayout: The positions of the children are specified in relation to the other children.
  • TableLayout: The child elements are placed with a grid.
  • AbsoluteLayout: The child elements are positioned based on absolute coordinates (in pixel).
Once you have chosen a layout type, you can add child elements. In the code given, there is already a TextView, which is used to display text on the screen. The current content is a reference to a resource defined in the values.xml file. As you will see, it uses the whole width of the screen, but is only as long as it needs to, to display the content. We might start with some small changes. Let's change the text color of the TextView to green:
<textview android:layout_height="wrap_content" 
    android:layout_width="fill_parent" android:text="@string/hello" 
    android:textcolor="#FF00FF00" />
Now, launch the project and see the changes. Next, let's add a new control called EditText:
<linearlayout android:layout_height="fill_parent" 
     android:layout_width="fill_parent" android:orientation="vertical" 
     xmlns:android="http://schemas.android.com/apk/res/android" />
        <edittext android:layout_height="wrap_content" 
             android:layout_width="fill_parent" android:textcolor="#FF0000FF"
             android:id="@+id/et_Text" />
<textview android:layout_height="wrap_content" android:layout_width="fill_parent"
    android:textcolor="#FF00FF00" android:id="@+id/lv_View" />
</linearlayout />
When we want to access the controls in code, they need to have an ID. Next we create some code for the controls. Go to the helloworld.java file.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //loading the layout over the resource reference
    setContentView(R.layout.main);
        
    //get the two controls we created earlier, also with the resource reference and the id
    final TextView tv_View = (TextView)findViewById(R.id.tv_View);
    final EditText et_Text = (EditText)findViewById(R.id.et_Text);
        
    //add new KeyListener Callback (to record key input)
    et_Text.setOnKeyListener(new OnKeyListener()
    {
        //function to invoke when a key is pressed
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            //check if there is 
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                //check if the right key was pressed
                if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
                {
                                    //add the text to the textview
                    tv_View.setText(tv_View.getText() + ", " + 
                                     et_Text.getText());
                                    //and clear the EditText control
                    et_Text.setText("");
                    return true;
                }
            }
            return false;
        }
    });
}
We will analyze the code line by line. First of all, as before, we load the layout. Then we create a TextView and a EditText variable and load our interface objects in them (that's what we need the ID for). Finally, we add a new OnKeyListener to the EditText control. In this OnKeyListener, we create the method onKey, which is called when a key is pressed, when the control is active. In the method, we perform two checks: the first to be sure that a key is pressed down (and not released), and the second to specify the key (in this case, the center key of the D-pad). If both checks are passed, we add the text of the EditText control to the TextView, and finally the text of the EditText control is deleted. Run and test the application. Great, you created your first real Android app.
Final_App_.jpg

Android App Design

As with every platform, Android has its own design challenges. Always keep in mind that you are developing for a mobile platform with limited memory, disk space, and processing power. Therefore, Android automatically kills processes (each app runs in its own process) to keep the system responsive. Processes are sorted after importance. The most important is the currently active process, followed by visible and stated service processes. The bottommost types of processes in hierarchy are background and empty processes. Keep that in mind when you design your application, because you don't want its process to be killed in the middle of something. Also, you can use whatever hardware is built into the Android phone. But notice that not all phones might have this hardware, and so not all might be able to run your app.
That's it for this tutorial. Hopefully, you understood the basics of Android development. Since this is my first article on CodeProject, I would really appreciate feedback!

Android, the world's most popular mobile platform

Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast—every day another million users power up their Android devices for the first time and start looking for apps, games, and other digital content.
Android gives you a world-class platform for creating apps and games for Android users everywhere, as well as an open marketplace for distributing to them instantly.
Android growth in device activations

Global partnerships and large installed base

Building on the contributions of the open-source Linux community and more than 300 hardware, software, and carrier partners, Android has rapidly become the fastest-growing mobile OS.
Every day more than 1 million new Android devices are activated worldwide.
Android’s openness has made it a favorite for consumers and developers alike, driving strong growth in app consumption. Android users download more than 1.5 billion apps and games from Google Play each month.
With its partners, Android is continuously pushing the boundaries of hardware and software forward to bring new capabilities to users and developers. For developers, Android innovation lets you build powerful, differentiated applications that use the latest mobile technologies.

Powerful development framework

Easily optimize a single binary for phones, tablets, and other devices.
Android gives you everything you need to build best-in-class app experiences. It gives you a single application model that lets you deploy your apps broadly to hundreds of millions of users across a wide range of devices—from phones to tablets and beyond.
Android also gives you tools for creating apps that look great and take advantage of the hardware capabilities available on each device. It automatically adapts your UI to look its best on each device, while giving you as much control as you want over your UI on different device types.
For example, you can create a single app binary that's optimized for both phone and tablet form factors. You declare your UI in lightweight sets of XML resources, one set for parts of the UI that are common to all form factors and other sets for optimzations specific to phones or tablets. At runtime, Android applies the correct resource sets based on its screen size, density, locale, and so on.
To help you develop efficiently, the Android Developer Tools offer a full Java IDE with advanced features for developing, debugging, and packaging Android apps. Using the IDE, you can develop on any available Android device or create virtual devices that emulate any hardware configuration.
1.5 billion downloads a month and growing. Get your apps in front of millions of users at Google's scale.

Open marketplace for distributing your apps

Google Play is the premier marketplace for selling and distributing Android apps. When you publish an app on Google Play, you reach the huge installed base of Android.
As an open marketplace, Google Play puts you in control of how you sell your products. You can publish whenever you want, as often as you want, and to the customers you want. You can distribute broadly to all markets and devices or focus on specific segments, devices, or ranges of hardware capabilities.
You can monetize in the way that works best for your business—priced or free, with in-app products or subscriptions—for highest engagement and revenues. You also have complete control of the pricing for your apps and in-app products and can set or change prices in any supported currency at any time.

Beyond growing your customer base, Google Play helps you build visibility and engagement across your apps and brand. As your apps rise in popularity, Google Play gives them higher placement in weekly "top" charts and rankings, and for the best apps promotional slots in curated collections.
Preinstalled on hundreds of millions of Android devices around the world, Google Play can be a growth engine for your business.