Menu

Search

Monday, 24 December 2012

Classes and Objects


          Java is an object-oriented language, which means that it has constructs to represent objects from the real world. Each Java program has at least one class that knows how to do certain things or how to represent some type of object. For example, the simplest class, HelloWorld, knows how to greet the world.

        Classes in Java may have methods (or say functions) and fields (or say attributes or properties).

         Let’s create and discuss a class named Car. This class will have methods, describing what this
type of vehicle can do, such as start the engine, shut it down, accelerate, brake, lock the doors,
and so on.
        This class will also have some fields: body color, number of doors, sticker price, and so on.


class Car
{
           String color;
           int numberOfDoors;
           void startEngine
           {
              // Some code goes here
            }
           void stopEngine
           {
              int tempCounter=0;

              // Some code goes here
            }
}


Completing Code Generation


You may have noticed that I also checked off the box asking Eclipse to generate the main method for me.Click Finish, and in a couple of seconds Eclipse will generate for you the initial code for the class HelloWorld, as shown in Figure 1

Figure 1
The generated code is shown in Eclipse’s editor view. It starts with the package statement, and the class declaration with the method name goes next. Type in the line System.out.println(“Hello World”); under the TODO comment (comments are explained in the next section), and save the code by pressing the little diskette image on the toolbar or using the Ctrl+S key combination. As you type in the code, Eclipse displays context-sensitive help suggesting a selection of possible values, minimizing guesswork and typing errors. I made a snapshot, shown in Figure 2 right after entering System.o

Figure 2
By default, saving the code results in an invocation of the compiler. If you didn’t make any syntax errors, Eclipse will create HelloWorld.class in the bin directory of the Hello project. In case of compilation errors, Eclipse puts a little red round bullet in front of problematic lines. Now you can run the program by pressing the round green button on the toolbar. The output of the program will be shown in the Console view panel in the lower part of Eclipse IDE, as in Figure 3

Figure 3









Saturday, 22 December 2012

Java Packages


          Packages in Java are used to better organize multi-file projects and for data protection. It’s not unusual for a project to have several hundreds of Java classes. Keeping them all in one directory is never a good idea. Hence the files will be located in various directories and sub-directories.

          What are the naming conventions for packages? Java developers use so-called reversedomain
name conventions. Let’s say you work on a project called Sales for a company called Acme, which has an Internet site at acme.com. Then every package name will start with the reverse URL ofthe company, followed by the project name: com.acme.sales.


         All Java classes that belong to this package would be stored in the following directory structure:
com/acme/sales.

          If some of the Java classes are specific to domestic sales, while others are used in international
sales, you will create two more sub-directories: com/acme/sales/domestic and com/acme/sales/
international.

           While directory names are separated by a forward slash or backslash, the corresponding Java packages are separated with periods. Java has a special keyword package, and its declaration has to be
the first line of the class (program comments don’t count). For example:

    package com.acme.sales.domestic;

          Let’s assume that you work for a company called Practical Java on project Lesson ; the name of the
package will be com.practicaljava.lesson, which is exactly what I’ve entered in the Package
field shown in Figure:-





Wednesday, 19 December 2012

Creating the HelloWorld Class in Eclipse


Our Hello project will contain one Java class: HelloWorld from Previows Lesson. Select File ➪ New ➪ Class and enter HelloWorld in the Name field in the pop-up window shown in Figure



Creating Hello Project in Eclipse


you simply created the class HelloWorld, but in Eclipse you have to create the project first. Select File ➪ New ➪ Java Project and enter Hello as the name of the project in the pop-up window,
as shown in Figure

You can select the version of the JRE you want to work with. In this lession I’ve installed the JDK and JRE of version 1.6.0_19, but you may have more than one version of JRE, and Eclipse can compile the code that will run in another version of JRE. This is a pretty nice feature of Eclipse IDE — it doesn’t come with its own JRE, but it allows you to pick the version that fits your needs. In some cases you have to compile the code with older versions of JRE if you know that this program will have to run in the older JVMs.
Creating Hello Project in Eclipse

After you click Next, the next window will ask you to specify the folder where compiled Java classes of the Hello project should be created. By default, Eclipse creates a Hello folder for this project with a bin sub-folder for compiled classes and an src sub-folder for the source code. In this lession both HelloWorld  java and HelloWorld.class were sitting in the same folder, which is a bad practice.

         Don’t change the name of the output directory — just click Finish on that window. In Figure  you see a new project, Hello, in the Package Explorer view of Eclipse.
Hello World Program


This project has an empty folder, src — youcan save the source code of HelloWorld.javathere when ready. The JRE folder contains all required libraries supporting the JVM where HelloWorld will run.

      These library files have .jar in their names. Java SDK comes with a jar utility that allows you to create a file archive that contains one or more compiled classes. While the JRE folder contains classes created by developers of the JRE itself, most real-world applications consist of groups of files (packages) located in
one or more jars.
      It doesn’t make much sense to put the only HelloWorld class inside the jar, but as your sample applications grow, you’ll see how to group and compress files in jars.





Downloading and Installing Eclipse


Downloading and Installing Eclipse


At work, I use Eclipse IDE for Java EE Developers. Each version of Eclipse IDE has a name. At the time of this writing, the current version is called Helios. In Windows OS, my first download window looks as shown in Figure  (note jee in the file name).



 The installation of Eclipse IDE comes down to a simple unzipping of the downloaded file into a disk drive of your choice. You’ll find the file eclipse.exe in the Eclipse folder — just run this program. You’ll immediately see a pop-up window asking you to select a workspace, which is a directory on your hard disk where one or more of your projects is going to be stored.If you want to create an application in Eclipse, you start with creating a project. In the real world, the source code of a decent-size application can consist of several Eclipse projects.For this book I selected the following workspace directory: c:\PracticalJava\workspace.Eclipse Java EE IDE starts with a Welcome panel — just close it by clicking the little x on theWelcome tab. Figure  is a snapshot of the freshly installed IDE with an empty workspace.

To be precise, you are looking at Java EE perspective (note the Java EE tab at the top), which is a
collection of views. On the left you see a Project Explorer view. The area in the middle is reserved
for the code editor view — you start using it as soon as you create your first Java class. The Outline
view is on the right — you’ll see the names of your classes, methods, and variables there when they are available.

There are many other views that you can open and close by yourself by selecting Window ➪ Show
View. These include Console, Search, Servers and others.

Since you are just starting to learn the language, there is no need to work in the Java EE perspective
— you can get by in the Java perspective. Click the little icon with the plus sign by the Java EE tab and select “Java perspective.” You’ll see a slightly different set of views with the Package Explorer and Hierarchy views on the left, Task List on the right, and Problems, Javadoc and Declaration tabs at the bottom.



ECLIPSE IDE


Sunday, 9 December 2012

Your First Java Program: Hello World


To start writing a Java program you could use any plain text editor — I’ll use Notepad. The file that
contains Java code must be saved in a file with its name ending in .java. Enter the following code in the text editor.


public class HelloWorld
{
        public static void main(String[] args)
        {
          System.out.println(“Hello World”);
        }
}

     Create a directory, c:\PracticalJava\Lesson1, and save the program you just created in the file HelloWorld.java (if you use Notepad, select All Files in the Save as Type drop-down to avoid auto attachment of the .txt suffix).

    Keep in mind that Java is a case-sensitive language, which means that if you named the program HelloWorld with a capital H and a capital W, you should not try to start the program helloworld. Your first dozen syntax errors will be caused by improper capitalization.


   Our first program contains a class, HelloWorld. Give the Java class and its file the same name. (There could be exceptions to this rule, but not in this simple program.) While writing Java programs you create classes, which often represent objects from real life. You’ll learn more about classes in coming time.


   The class HelloWorld contains a method, main(). Methods in Java classes represent functions (actions) that a class could perform. A Java class may have several methods, but if one of them is called main() and is declared (if it has a method signature), as in our class, this makes this Java class executable. If a class doesn’t have a method main(), it can be used from other classes, but you can’t run it as a program.


   The method main() calls the method println() to display the text “Hello World” on the screen. Here is the method signature (similar to a title) of the method main():
                        public static void main(String[] args)



This method signature includes the access level (public), instructions on usage (static), return value type (void), name of the method (main), and argument list (String[] args).

➤➤ The keyword public means that the method main() can be accessed by any other Java class.

➤➤ The keyword static means that you don’t have to create an instance of this class to use this  method.

➤➤ The keyword void means that the method main() doesn’t return any value to the calling program.

➤➤ The keyword String[] args tells us that this method will receive an array of characters as  the argument         (you can pass external data to this method from a command line).







Friday, 7 December 2012

Java Introduction

Today Java is one of the most popular programming languages for everything from programming
games to creating mission-critical applications such as those for trading on Wall Street or controlling 
Mars rovers. In this lesson you are introduced to some of the very basic Java terms, and you
will download and install the Java Development Kit (JDK) and compile your fi rst program.


WHY Learn Java?
The Java programming language was originally created in 1995 by James Gosling from Sun
Microsystems (currently a subsidiary of Oracle Corporation). The goal was to provide a simpler
and platform-independent alternative to C++. You’ll see what platform independence
means a little later, in the section “The Life Cycle of a Java Program.” For now, let’s look at
some of the reasons why Java can be your language of choice.
Java is a general-purpose programming language that’s used in all industries for almost any
type of application. If you master it, your chances of getting employed as a software developer
will be higher than if you specialize in some domain-specifi c programming languages.
There are around six million professional Java developers in the world and the majority of
them are ready to share their knowledge by posting blogs and articles or simply answering
technical questions online. If you get stuck solving some problem in Java, the chances are very
high that you’ll fi nd the solution on the Internet.
Since the pool of Java developers is huge, project managers of large and small corporations like
to use Java for the development of new projects — if you decide to leave the project for whatever
reason, it’s not diffi cult to fi nd another Java programmer to replace you. At this point
you may ask, “Does that also mean that my Java skills will be easily replaceable?” To improve
your value and employability you need to master not only the syntax of the language, but also
the right set of Java-related technologies that are in demand (you’ll learn them in this book).
Not only is Java open-source, but there are millions of open-source projects being developed
in Java. Joining one of these projects is the best way to get familiar with the process
of project development and secure your very fi rst job without having any prior real-world
experience as a programmer.

Thursday, 6 December 2012

Downloading and installing JDK in windows

Download the JDK from the web URL:-


Since you’ll be learning how to develop Java programs, download JDK from the following website:
http://www.oracle.com/technetwork/java/javase/downloads/index.html


After selecting the Windows platform and clicking the Download button you’ll see a Login for Download
screen, which is optional: You can skip this step.




After the file is saved, start this executablen and the installation wizard will lead you through the process. Read and accept the license agreement and click the button Next. Note the item at the bottom of the left box
in Figure— it is an open-source database management system (DBMS) called Java DB. You’ll need JavaDB for comming time. A couple of minutes into the installation process you’ll see a pop-up window asking you where to install JRE. I’ll assume that you’ve accepted the default directory (c:\Program Files\Java\jre6), but you can select a different one. Shortly, you should see a message telling you that installation was successful. Click Finish. At the end of the installation process you’ll see a website suggesting you register the install. This step is optional.If you have previous versions of JDK installed on your computer, each of them will be sitting in its own directory, e.g., c:\Program Files\Java\jdk1.6.0_019. But for a sanity check, I always open a command line window and enter java –version at the command prompt. Figure 1-3 shows the confirmation that I really have JRE 1.6.0_19 (Java 6 is also referred to as Java 1.6).




Congratulations! Your JDK and JRE are installed.


The Life Cycle of a Java Program


There are different types of programming languages. In some of them you write the text of the
program (aka the source code) and can execute this program right away. These are interpreted languages
(e.g., JavaScript).
But Java requires the source code of your program to be compiled first. It gets converted to either
machine-specific code or a bytecode that is understood by some run-time engine or a virtual machine.
Not only will the program be checked for syntax errors by a Java compiler, but some other libraries of
Java code can be added (linked) to your program after the compilation is complete (deployment stage).
In this lesson you write a very basic Java program that will output the words “Hello World” on your
computer’s screen.
Technically you can write the source code of your Java program in any plain text editor that you
prefer (Notepad, TextEdit, vi, etc.), but to compile your program you’ll need additional tools and
code libraries that are included in the Java Development Kit (JDK).



JDK and JRE
If you are planning to use a specific computer to develop Java programs, you’ll need to download
and install JDK. If you are planning to use this computer only to run Java programs that were compiled
somewhere else, you just need the Java Runtime Environment (JRE).If you have JDK installed on your machine, it includes JRE.Java’s platform independence comes from the fact that your Java program doesn’t know under which operating system (OS) or on which hardware it’s being executed. It operates inside the preinstalled JRE that is pretty much the same on every platform.Since you’ll be learning how to develop Java programs, download JDK from the following website:
http://www.oracle.com/technetwork/java/javase/downloads/jdk6-jsp-136632.html.




Java SE and EE
But before rushing to the downloading process, you need to get familiar with two more terms: Java
SE (Standard Edition) and Java EE (Enterprise Edition). The latter includes the server-side tools and
libraries that you’ll get familiar with starting in Lesson 26.
For now, just download the latest version of the JDK SE Development Kit. (The letter U followed by
a number represents the update number of Java 6.)
Select the platform (Windows, Linux, Solaris) on which you are planning to develop Java programs
and continue the download process.