Getting started

From Wikibooks, open books for an open world
< Java Programming
Jump to: navigation, search

The Java Platform Java Programming
Getting started
Language Fundamentals

[edit] Understanding systems

We conceptualize the world around us in terms of systems. A system is a web of interconnected objects working together in tandem. In the systems theory, a system is set out as a single entity within a world surrounded by an environment. A system interacts with its surrounding environment using messages of two distinct types:

  • inputs: messages received from the surrounding environment; and,
  • outputs: messages given back to the surrounding environment.


Figure 1: A simple system interacting with its environment using input and output messages.
Understanding Systems.svg


Life is a complicated mess of interconnected objects sending signals and messages. See the illustration below in figure 2 demonstrating a complex system for an economic ecosphere for a single company. Imagine what this system diagram would be like if you were to add a few more companies and their sub-systems. Computer software systems in general are a complex web of further interconnected sub-systems – where each sub-systems may or may not be divided into further sub-systems. Each sub-system communicates with others using feedback messages – that is, inputs and outputs.


Figure 2: Example of a complex system with multiple sub-systems and interactions
Complex System.svg


[edit] The process of abstraction

Programming is essentially thinking of solutions to problems in real life as a system. With any programming language, you need to know how to address real-life problems into something that could be accurately represented within a computer system. In order to begin programming with the Java programming language (or in fact, with any programming language), a programmer must first understand the basics of abstraction.

Abstraction is the process of representing real-life problems and object into your programs.

Suppose a novelist, a painter and a programmer were asked to abstract (i.e., represent) a real-life object in their work. Suppose, the real-life object that needs to be abstracted is an animal. Abstraction for a novelist would include writing the description of the animal whilst the painter would draw a picture of the animal – but what about a computer programmer?

The Java programming language uses a programming paradigm called object-oriented programming (OOP), which shows you exactly what a programmer needs to be doing. According to OOP, every object or problem in real-life can be translated into a virtual object within your computer system.

[edit] Thinking in objects

In OOP, every abstraction of a real-life object is simply called an object within your code. An object is essentially the most basic representation of a real-life object as part of a computer system. With Java being an object-oriented language, everything within Java is represented as an object. To demonstrate this effect, if you were to define an abstraction of an animal in your code, you would write the following lines of code (as you would for any other abstraction):


Computer code
class Animal { }


The code above creates a space within your code where you can start defining an object; this space is called a class (or type) definition. All objects need to be defined using a class definition in order for them to be used in your program. Notice the curly brackets – anything you write within these brackets would serve as a definition or specification for your object. In the case of the example above, we created a class definition called Animal for objects that could serve as an abstract representation of any animal in real-life. The way that a Java environment evaluates this code to be a class definition is by looking at the prefix word we used to begin our class definition (i.e., class). Such predefined words in the Java language are known as keywords and make up the grammar for the language (known as programming syntax).

Note:
Class definitions have different names in different languages. They are sometimes called type definitions, object specifications or templates as well

[edit] Understanding class definitions and types

Aristotle was perhaps the first person to think of abstract types or typologies of objects. He started calling them classes – e.g., classes of birds, classes of mammals. Class definitions therefore serve the purpose well in defining the common characteristics or types of objects you would be creating. Upon declaring a class definition, you can create objects based on that definition. In order to do so however, you need to write a special syntax that goes like this:

Computer code
Animal dog = new Animal();


The code above effectively creates an object called dog based on the class definition for Animal. In non-programmer parlance, the code above would translate into something akin to saying, "Create a new object dog of type Animal." A single class definition enables you to create multiple objects as the code below indicates:

Computer code
Animal dog = new Animal();
Animal cat = new Animal();
Animal camel = new Animal();


Basically, you just have to write the code for your class or type definition once, and then use it to create countless numbers of objects based on that specification. Although you might not grasp the importance of doing so, but this little exercise saves you a lot of time (a luxury that was not readily available to programmers in the pre-Java days).

[edit] Expanding your class definitions

Although, each object you create from a class definition is essentially the same, there has to be a way of differentiating those objects in your code. Object properties (or simply properties) are what makes your objects unique from other objects. Let's take our present abstraction for instance. An animal could be a dog, cat, camel or a duck but since this abstraction is of a very generic kind, you need to define properties that are common to all of these animals and yet makes the animals stand apart. For instance, you can have two properties: name (a common name given to any one of these animals) and legs (the number of limbs any one of these animals would require to walk). As you start defining your objects, they start to look like this:


Computer code
class Animal {

  String name;
  int legs;
}


In the code above you defined two object properties:

  • a property called name of type String; and,
  • a property called legs of type int.

These special pre-defined types are called data types. The String data type is used for properties that can hold textual values like names, while the int (integer) data type is used for properties that can hold numeric values

Note:
Properties are called different things in different languages. They may be called state identifiers, fields or member variables in other programming language syntax. Java uses the words properties and fields in different contexts, as would be understood from upcoming sections.

Figure 3: In order to denote the Animal object as a system within the Java Environment,
you present it as such. Note how properties are presented.
Object in Java Environment.svg


In order to demonstrate how properties work, we will go ahead and create objects from this amended version of our class definition as such:

Computer code
Animal animal1 = new Animal();
Animal animal2 = new Animal();

animal1.name = "dog";
animal1.legs = 4;

animal2.name = "duck";
animal2.legs = 2;


You can access the properties of your created objects by using the . (dot) or membership operator. In the example above, we created two objects: animal1 and animal2 of type Animal. And since, we had established that each Animal has two properties namely name and legs, we accessed and modified these properties for each of our objects using the membership operator to set the two apart. By declaring different values for different objects, we can manipulate their current state. So, for instance:

  • the animal1 object is a "dog" with 4 legs to walk with; while,
  • the animal2 object is a "duck" with 2 legs to walk with.

What sets the two objects apart is their current state. Both the objects have different states and thus stand out as two different objects even though they were created from the same template or class definition.

[edit] Adding behavior to objects

At this point, your objects do nothing more than declare a bunch of properties. Being a system, your objects should have the ability to interact with its environment and other systems as well. To add this capability for interaction, you need to add interactive behavior to your object class definitions as well. Such behavior is added to class definitions using a programming construct called method.

In the case of the Animal, you require your virtual representation of an animal to be able to move through its environment. Let's say, as an analogy, you want your Animal object to be able to walk in its environment. Thus, you need to add a method named walk to our object. To do so, we need to write the following code:


Computer code
class Animal {

  String name;
  int legs;

  void walk() { }
}


As you write this code, one thing becomes immediately apparent. Just like the class description, a method has curly brackets as well. Generally, curly brackets are used to define an area (or scope) within your object. So the first set of curly brackets defined a scope for your class definition called the class-level scope. This new set of curly brackets alongside a method defines a scope for the further definition of your method called the method-level scope.

In this instance, the name of our method is walk. Notice however that the name of our method also features a set of round brackets as well. More than just being visual identifiers for methods, these round brackets are used to provide our methods with additional input information called arguments.

A method therefore enables an object to:

  1. Accept input: Receive some argument(s);
  2. Process information: work on the received argument(s) within its curly brackets; and,
  3. Generate ouput: occasionally, return something back.

In essence, methods are what makes an object behave more like a system.

Notice the keyword void before the name of the method – this tells us that the method walk returns nothing. You can set a method to return any data type – it can be a String or an int as well.

Note:
Methods are known by different names in different programming language. They might be called functions, procedures, routines or behaviors.

Figure 4: The Animal object can now be denoted as having an interaction behavior within the Java Environment
as illustrated here. Note the difference between the presentation of properties and behaviors.
Object Behavior in Java Environment.svg


[edit] The process of encapsulation

By now, we thoroughly understand that any object can interact with its environment and in turn be influenced by it. In our example, the Animal object exposed certain properties – name and legs, and a method – walk() to be used by the environment to manipulate the object. This form of exposure is implicit. Using the Java programming language, a programmer has the power to define the level of access other objects and the environment has on a certain object.

[edit] Using access modifiers

Alongside declaring and defining objects, their properties and methods, a programmer also has the ability to define the levels of access on those elements. This is done using keywords known as access modifiers.

Let's modify our example to demonstrate this effect:

Computer code
class Animal {

  public String name;
  public int legs;

  public void walk() { }
}


By declaring all properties and methods public, we have ensured that they can be used outside the scope of the Animal class. This means that any other object (other than Animal) has access to these member elements. However, to restrict access to certain member elements of a class, we can always use the private access modifier (as demonstrated below).

Computer code
class Animal {

  private String name;
  private int legs;

  public void walk() { }
}


In this example, the properties name and legs can only be accessed within the scope of the Animal class. No object outside the scope of this class can access these two properties. However, since the walk() method still has public access, it can be manipulated by actors and objects outside the scope of this class. Access modifiers are not just limited to properties or methods, they can be used for class definitions as well (as is demonstrated below).

Computer code
public class Animal {

  private String name;
  private int legs;

  public void walk() { }
}


The following list of keywords show the valid access modifiers that can be used with a Java program:

keyword description
public Opens access to a certain property or method to be used outside the scope of the class.
private Restricts access to a certain property or method to only be used within the scope of the class.
protected Access to certain property or methods is reserved for classes that inherit the current class.
More on this would be discussed in the section on inheritance.

[edit] Exercise 1: Writing your first Java program

In order to write your first Java program, follow the instructions below:

1. Proceed only if you have successfully installed and configured your system for Java.
Read our guide on installing the Java platform.
2. Open your preferred text editor – this is the editor you set while installing the Java platform.
For example, Notepad or Notepad++ on Windows; Gedit, Kate or SciTE on Linux; or, XCode on Mac OS, etc.
3. Write the following lines of code in a new text document:
Computer code
public class FirstProgram {

  public static void main(String[] args) {
    System.out.println("Hello World!");
  }
}
4. Save the file as FirstProgram.java – the name of your file should be the same as the name of your class definition and followed by the .java extension. This name is case-sensitive, which means you need to capitalize the precise letters that were capitalized in the name for the class definition.
5. Next, open your preferred command-line application.
For example, Command Prompt on Windows; and, Terminal on Linux and Mac OS.
6. In your command-line application, navigate to the directory where you just created your file. If you do not know how to do this, consider reading through our crash courses for command-line applications.
7. Compile the Java source file using the following command which you can copy and paste in if you want:
javac FirstProgram.java
8. Once the compiler returns back to the prompt, run the application using the following command:
java FirstProgram
9. The above command should result in your command-line application displaying the following result:
Hello World!

[edit] Did the program execute correctly?

Ask for help if the program did not execute properly in the Discussion page for this chapter.

If the program does not work as you expect, check the following common problems:

  • Are you sure all words are spelled correctly and with the exact case as shown?
  • Are there semicolons and brackets in the appropriate spot?
  • Are you missing a quote? Usually, modern IDEs would try coloring the entire source as a quote in this case.
  • Are you launching the javac or java programs correctly?
  • Did you navigate to the program's location in the command prompt using the CD (Change Directory) function?

[edit] Analysis of your first Java program

In the code for your first Java program, you created a class called FirstProgram which serves as a virtual abstraction model for our program. You could have named this anything but we chose the name FirstProgram in order to highlight the fact that this abstraction serves as the very first program we create in Java.

Computer code
public class FirstProgram { }


Notice how we placed the public access modifier next to the name for the class definition. This tells us that the class is accessible by the Java environment it exists within. In our case, this environment is the Java Runtime Environment (JRE) itself, which would have direct access to the FirstProgram class and all its public member properties, fields and methods.

Computer code
public class FirstProgram {

  public static void main(String[] args) { }
}


Therefore, when we declare the main(...) method, we make sure that this method is accessible to the JRE using the public access modifier. This particular method has some interesting features associated with it. We can see that the method itself returns nothing (as is indicated by the void keyword) but the method accepts arguments args of type String[]. The square brackets [ and ] tells us that this the args argument is a list of type String, therefore instead of just one String, this variable can hold several String elements. Such variables are called arrays.

Note:
Main methods are a part of your code that identify your code as being executable. If you have a main method in your code, you can run that code; if you don't have a main method in your code, you cannot run it. In Java, declaring a main method means exposing your class as a candidate for execution using the java command of your Java Runtime Environment (JRE).

Learn more about main methods in similar programming languages

Main methods in similar programming languages

Main methods or functions are a prominent feature of programming languages that are similar to the Java programming language. This is the primary function or method that enables a program written in those languages to be executable.

For a complete list of main methods for various other languages, see the Wikipedia article on main functions.

C#

In C# (just as in Java), a main method is the first method that a virtual machine searches for within a program in order to execute it. Thus, the main method is sometimes also called the main entry point in the .NET C# parlance.

static void Main()
static void Main(string[] args)
static int Main()
static int Main(string[] args)

C and C++

int main(void)
int main(int argc, char *argv[])
int main()

Finally, within the body of the main method, we have written a single line of code:

Computer code
System.out.println("Hello World!");


This command is called a print statement and is used to print out or display stuff on the command-line application interface. It's a slightly complicated routine to write the whole statement but you get used to writing it in your programs. We will be explaining this line and other System commands in a later chapter.

The Java Platform Java Programming
Getting started
Language Fundamentals
Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export