Tuesday, 19 April 2011

Beginning Java Programming Chapter-1

Beginning Java Programming Chapter-1

Writing and Executing a Java Program

In high-level programming languages such as C and C++, you write a program in a human-readable format, and a program called a compiler translates it to a binary format called executable code that the computer can understand and execute. The executable code depends upon the computer machine that you use to execute your program; it is machine dependent. In Java, this process from writing to executing a program is very similar but with one important difference that allows you to write Java programs that are machine independent. To understand that difference, pay attention to the term Java virtual machine (JVM). Writing a Java Program
A Java program that you write contains a set of instructions in text format written according to the rules of the Java programming language. These instructions are called source code . The file that contains these instructions is called the source file and has the file extension .java . You can use a text editor such as Notepad or other's Tools and IDE as like JCreator, NetBeans, Eclipse, JBoss, JDeveloper, JBuilder to create and edit Java source files.
As an exercise, open a new text document (for example, using Notepad on your Windows machine), type the code presented in below and save the document as test.java
public class test {
public static void main(String[] args) {
int a = 10;
int b = 50;
int c = 83;
int d = 54;
int total = a + b+c+d;
System.out.println("The Total = "+total);
}
}
Note: It will be easy  for you If  you  test it in  JCreator  After Instilling JDK
Compiling a Java Program
As you know by now, computers cannot understand the source code that you write. Before a CPU of a computer can execute the instructions written by you, the instructions need to be translated into a machine language —that is, into a binary format. In most of the programming languages, such as C and C++, a compiler compiles the source code into the machine language, and this compiled
code is called executable code . However, in Java, the compiler compiles the code into bytecode , which is not executable code. Bytecode is somewhere in the middle of source code and executable code. For example, to create the bytecode files from the source file test.java , ou run the Java compiler by issuing the following command: javac test.java
The compiler converts the text instructions into bytecode form and places them in files with the .class extension: test .class . You will learn what a class is later in this Tutorial

Elements of a Java Program

A Java program is composed of classes, and a class consists of methods and variables. This section introduces these elements of a Java program. The underlying philosophy of any object-oriented language is to adapt computing to the problem that it will solve rather than to adapt the problem to the computing, which you end up doing if you are using a procedural language such as C or Pascal. Any real-world problem contains objects (entities), so the first step in designing a Java program is to recognize the objects in the problem that your program will solve. Your running program will contain the Java objects corresponding to the objects in the problem, and the classes in a Java program are the blueprints for those objects.
Classes and Objects Objects, which represent the entities in the real-world problem that the program is trying to solve, form the building blocks of any Java program. A class is a template (or a blueprint) from which objects are created (yes, you can create more than one objects from the ame class). So, in your source code, you do not write an object, you write a class, and the code to create objects from the class. When a program is running, the objects are created and do the job for which you created them. Writing a class is called implementing a class, and the implementation of a class has two components: the class declaration and the class body. The class declaration contains the name of the class and some other attributes, There are other modifiers or keywords that you can use in a class declaration to declare other properties of the class, such as that the class is being derived from another class, that the class cannot be used to derive another class, or that the class cannot be used to create an object. The class body follows the class declaration and is contained within curly braces: { to begin the body and } to end the body. The class body contains methods, variables, and the program logic.
To sum up, a class is a template that you write, and an object is created from the class. In technical terms, you say that an object is instantiated from a class, and the process is called instantiation . For this reason, the objects of a class are also called the instances of that class. As said earlier, these object s in a Java program represent the objects in a real-world problem that the program is trying to solve. The real world (and hence its problems) is full of objects: cars, books, students, courses, donuts, pizzas, beer, and so on. For example, all cars can be represented by a class called Car , and then specific cars (your car, my car, Michael Jackson's car) can be represented by the objects of this class. Each object has a state , that is, a set of characteristics, such as my car is black and its price is $20,000, Michael Jackson's car is blue and its price is $200,000, and so on. The characteristics are represented by data that is managed by using variables. For example, price could be a variable that holds the value 20000 corresponding to $20,000. Each object also has a behavior , such as my car is parked, or it's running, and so on. While the state is represented by the values of its data items, represented by variables, the behavior is represented by what are called methods . Accordingly, a class consists of methods and variables. A computer program, written in any programming language, is basically made of three elements: data, operations on data, and the logic that determines the operations. In Java, the data held by variables determines the state of an object, and the operations on data and the logic for the operation are held inside a method that determines the behavior of an object. The structure of a method is very similar to that of a class: it has a declaration and a body. The declaration contains some attributes that define the name of the method and some attributes that indicate some properties of the method such as the accessibility, the type of values returned by the method, and so on. You execute a method by specifying the method name (and the name of the class to which the method belongs, if it's not obvious) in a code statement, just as you specify the class name in the java command to execute a Java program. Executing a method is also called calling or invoking the method. The declaration of a method can also contain a number of variables declared inside the brackets, ( ) , immediately following the name of the method. These variables in the declaration are traditionally called method parameters , and the values for these parameters, called arguments , can be passed as input when the method is invoked (called). These days, both the parameters and the passed-in values are often referred to as arguments . The static attribute of the main(…) method indicates that the method can be invoked without referring to a particular object—that is, without instantiating the class. This capability is needed to start a program, because objects are created when a program is running, and when you have just started a program, there is no object. So, the JVM invokes the main(…) method in the class that you named in the run ( java ) command. This is why the main(…) method has to be static . A method consists of variables to hold data and the application logic to operate on the data in order to determine the behavior of an object.

Features of Java

TheWorld Wide Web and Java grew up together during the same time, and thus Java implemented most of the Internet programming requirements. As a result, you can develop an enterprise web application end to end (from client to server) in one language: Java. So, the Java language has a multitude of features. However, the scope of the topics covered in this page demands that you understand only the two defining features of the Java language: it is a platform-independent language, and it supports object-oriented programming

Platform Independence

When people say that Java is platform independent, they usually refer to the well-celebrated Java phrase, “write once, run anywhere.” As described earlier in this chapter, this platform independence is made possible by introducing the JVM. The Java compiler compiles the code into bytecode , which can be interpreted by a suitable JVM on any platform chosen from a wide variety of platforms. Because bytecode is executed under the control of the JVM, the JVM can prevent the code from generating side effects outside the system. his helps make a Java program secure. There is a price that you pay for the platform independence in terms of performance. The interpreted programs run slower than the fully compiled programs. However, the JIT (Just-In-Time) compilers (which cache the interpretations) offer the solution to this problem. You must have heard the phrase “ everything in Java is an object .” Well, this is just another way of saying that Java supports object-oriented programming.

Object-Oriented Programming

Object-oriented programming (OOP) is a way of solving problems with computers. The OOP philosophy is to adapt the computer to the problem instead of molding the problem into something that is familiar to the computer. In OOP, you identify the entities (objects) in the problem and their relationship with each other independent of the issues of how they will be computed. These entities will be represented by objects in a computer program. The goal is to have one-to-one correspondence between the entities in the problem and the objects in the program. Some salient features of OOP implemented in Java are described in this section, including encapsulation, inheritance, and polymorphism.

Encapsulation

Two of the three important elements of a computer program are data and operations on data, the third being the logic that determines the operation. Accordingly, a class in Java is made of data variables (that hold data) and methods (that hold the logic for operations and perform operations on the data). This approach of combining an object's data with its methods is called encapsulation . The user can retrieve, store, or change the data by invoking methods on the object. Therefore, the user of an object can view the object as a black box that provides services. You, the programmer, can change, add, or delete the instance variables (the variables of the object) and methods in the class, but as long as the services provided by the object remain the same, the client code that uses the services offered by the object can continue to use it without being rewritten. Encapsulation is also called data abstraction or data hiding . So, a class in Java can be looked upon as a basic unit of encapsulation. A variable outside of a method is called a class variable or an instance variable . These variables and the methods of a class are called members of the class. Encapsulation helps make the code more robust and makes tracking bugs easier. Encapsulation in a Java program reflects reality in a typical real-world problem to the extent that an entity in the real world has characteristics and a behavior. Another reality of real-world problems is that the entities in a problem are related to each other in a hierarchical fashion. For example, a cow is an animal, and an animal is a living being.

Inheritance

An object is an instance of a class, which is a blueprint to create objects. You can create multiple objects from the same class. However, instead of programming from scratch, you can derive a class from another class. If you do so, your class, called a subclass , inherits the state (variables) and the behavior (methods) of the class from which it is derived. The class from which you derive your class is called the superclass . The property of inheriting the state and behavior of the superclass is called inheritance . In your subclass, you can override the inherited methods, and also write new methods and declare new variables. Furthermore, you are not limited to just one layer of inheritance. You can create a whole tree of inheritance, called a c lass hierarchy , as deep as needed. The methods and variables are inherited down through the levels. The rule of thumb for building the class hierarchy is: the farther down in the hierarchy a class appears, the more specialized its behavior is. There are some built-in classes in the Java language organized into a hierarchy tree, and the Object class is at the top of this class hierarchy. Also, each class that you write automatically becomes a subclass of the Object class even if you do not explicitly derive it from the Object class. The Object class provides some methods representing the Behaviors that are common to all the objects created from different classes.

The main advantages of inheritance are described here:

Code reusability : Inheritance automates the process of reusing the code of the superclasses in the subclasses. With inheritance, an object can inherit its more general properties from its parent object, and that saves the redundancy in programming. • Code maintenance : In any discipline, knowledge is made more manageable by hierarchical classification. Organizing code into hierarchical classes makes its maintenance and management easier.
Implementing OOP : Inheritance helps to implement the basic OOP philosophy to adapt computing to the problem and not the other way around, because entities (objects) in the real world are often organized into a hierarchy. For example, in addition to their own specifics, all different specific students in your class share the properties of what is called a student, all the different specific employees at your workplace share the properties of what is called an employee, and so on.

Polymorphism

Polymorphism refers to a feature of Java that allows an object of a superclass to refer to an object of any subclass. This is possible because all objects of a base class are also objects of its superclass. For example, assume that all circles are represented by a class called Circle , which is a subclass of the class Shape (which thus is the superclass of Circle ). Further assume that Triangle is another subclass of Shape . Now assume that Shape has a method draw() . You can implement these classes in such a way that when you invoke the draw() method on a Shape variable (referring to an object of Triangle ), it draws a triangle, and when you invoke the same method on the same Shape variable (which now is referring to an object of Circle ), it draws a circle. It is the same method of the Shape class with different implementations in the subclasses. So, polymorphism helps to prevent the code from becoming more complex and cumbersome, by allowing you to make different implementations of related functionalities (behaviors) under one name: object or method. The object-oriented feature encapsulation allows you to control the accessibility to the elements contained by the class: variables and methods. For example, going back to Listing 1-1, line 10 accesses the nargs variable from the same class in which this variable exists. In lines 11 through 13, the Robot class and its methods are being accessed from a class other than the class in which they are defined. Let's briefly explore the access issue.

Accessing the Classes and Class Members

The variables (including reference variables) and methods in a class are called class members . A class can also have other classes, called nested classes , as members of the class. A class that is not a nested class is called the top-level class . In this book, “class” refers to the top-level class unless mentioned otherwise. The access to the class members can be controlled by using access modifiers specified in the member definition, for example: public void myMethod(); In this example, public is an access modifier. Some access modifiers can also be specified for classes. The following list defines the four access modifiers supported by Java:
public : A class member declared public can be accessed by any code from any class in your application. An application declares its main(…) method to be public so that it can be invoked from any JVM. This modifier makes a class or a class member most accessible.
protected : A member declared protected is accessible to all classes in the same package in which the class that declares the member exists. A package is a set of classes grouped together. The protected member can also be accessed from a subclass of the class that contains the member even if the subclass is in a different package. You cannot declare a class protected . The protected modifier provides less accessibility than the public modifier.
default : If you do not specify any access modifier while declaring a class or a class member, the default access is assumed. A class or a class member with default access (that is, no access modifier specified) can be accessed by any class in the same package as the class in question. Unlike a protected member, a member with default access cannot be accessed by a subclass that is in a different package from that of the class that contains the member. So, the default modifier provides less accessibility than the protected modifier.
private : A member declared private is only accessible to objects of the class in which the member is declared. A top-level class cannot be declared private . This modifier makes a member least accessible. When the program is executing, the elements of the program need to be stored in the memory temporarily.
Living on the Stack The following elements of a Java program live on the stack:
Local variables : The variables of primitive types defined inside a method or as method parameters.
Local reference variables : The variables that refer to an object and are defined inside a method or as a method parameter. Remember that an object that a local variable refers to lives on the heap and not on the stack.
Method invocations : When you invoke (call) a method, the method is pushed onto the stack (that is, placed on top of the stack). Local variables live inside a method, and the scope of a local variable is the execution of the method. When the method execution is complete, the local variables inside the method are gone. But the objects, to which some of these local variables may be referring, are still alive and well on the heap.

Living on the Heap

The following elements of a Java program live on the heap:
Instance variables : The variables of primitive types defined inside a class but outside of all its methods.
Instance reference variables : The variables that refer to an object and are defined inside a class but outside of all its methods.
Objects : Represent the entities in the real-world problem that the Java program is trying to solve. All the objects live on the heap, always.
Remembering whether a particular element lives on the stack or on the heap is easy: a local variable (primitive or reference) belongs to a method and lives with it on the stack, while an instance variable belongs to an object and lives with it on a heap. However, also note that a local reference variable on a stack points to an object on the heap, and the object will not die with the local reference variable. The objects on the heap that are no longer in use are eventually collected by a program called a garbage collector to free up the memory used by them. For this reason, the heaps are also called garbage-collectible heaps. So far in this chapter, you have learned how to write, compile, and execute a Java program, and where in the memory the different elements of a program are stored. The next issue that you need to consider is that a program that you have written may have problems that will cause errors.

Beginning Java Programming Chapter 2

No comments:

Post a Comment