Anda di halaman 1dari 31

INTRODUCTION TO JAVA! !

Java
What is a computer program?
A computer program consists of a set of instructions which the computer should follow in order to
perform a specific task. These set of instructions are written by programmers.

The set of instructions can be one of the three forms:

1. machine codes

2. assembly codes

3. high-level language source code

Machine codes

Machine codes are the codes which contain only “0’ and “1”. They run fastest as there is no need of
any conversion since it is the language that the computer “understands”. However, it is very difficult
for programmers to code in machine language due to the following reasons:

1. The codes are machine-specific. That is, for each different machine different machine codes are
needed.

2. The codes are very cryptic so they are very prone to errors.

Assembly codes

These codes contain some mnemonic english words. Compared to machine language, they are less
cryptic and thus less prone to errors. However, they are still hard to understand. A special program
called assembler should be used to convert the assembly codes (which computers do not
understand) to machine codes.

High-level language

This is a language which is closer to people rather than machine. Examples of high level languages
are C, C++, C#, Java, Visual Basic etc...

Since the codes written in a high-level language cannot be understood by a computer, a special
program is needed to convert the source code to machine codes. For High level language, two
special programs exist:

1. Interpreter

2. Compiler

PAGE 1 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Similarity between Interpreter and Compiler


Both Interpreter and Compiler convert high level language codes to machine codes.

Difference between Interpreter and Compiler


The main difference is:

An Interpreter converts the source code to machine codes line by line. In other words, the
Interpreter converts one line of codes and then instructs the computer to execute this line of codes.
It is only after the execution of this line of codes that the Interpreter will convert the next line of
codes. For the case of the Compiler, it will convert (compile) all the lines of source codes to
something called Object codes. It is only after the full compilation that the resulting object codes are
run by the computer.

Advantages of Interpreter over Compiler


1. Using an Interpreter means the code can be platform independent.
2. Since Interpreter executes line by line, the execution will stop at the line which contains an error.

Advantages of Compiler over Interpreter


1. Generally, a compiled codes run faster that codes which needs to be interpreted and then run.

2. Using a compiler means that you do not have to make the source code available which makes it
harder for a competitor to reverse engineer your software.

What is Java?
Java is a high level programming language brought by Sun. Java can be said to belong to the C
family (C, C++, C#) in the sense that all of them share some common features (but they are
not alike). For example, all of them include a semi-colon at the end of every statement.

One among the things that differentiate Java from the others is the fact that Java uses a JVM.

What is JVM?
JVM stands for Java Virtual Machine. Unlike language like C or C++, the compiler of Java does
NOT convert the source code to machine codes but instead to an intermediary codes called
Bytecodes. This is so to increase the portability of Java. However, since all computers understand
only machine code, there is a need for a program to convert the bytecodes to machine code. One of
the functions of JVM is that. However, it also does things like checking the syntax and grammar of
Java statements in the context of a Java program.

PAGE 2 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

JVM and Platform Dependent Interpretation and Compilation


A" virtual" machine" interprets" byte3code" (1" mark),"
which"is"produced"when"a"java"program"is"compiled."
It"differs"from"platform"speciAic"compilation"in"that"a"
dedicated" virtual" machine" must" be" written" for" a"
platform," and"the"bytecode"is" deployed"there"rather"
than"on" the"platform." The"result"of"this" is"that" code"
written"for"one"platform"will"run"(in"most" cases)"on"
any"platform.
Virtual" machines" usually" incorporate" some" form" of"
compilation," so" they" run" faster" than" interpreted"
code.

Context-sensitive Editor - Place where Programmers code!


Though Java codes can be written in a simple editor like Notepad, it is rarely done. This is because
more advanced editor called Context-sensitive Editor exists. The latter offers many features that
help the programmers. For example, while the programmer is writing the codes, there is a syntax
checker which operates at real-time. Other features like Intellisense are also available. Usually, the
context-sensitive editor comes along with many other features and all packed to give what we call an
IDE (Integrated Development Environment).

Below is an non-exhaustive list of some common IDE used by Java Community:

1. Eclipse

2. Netbeans

3. IntelliJ

Advantages of Context-sensitive Editor


It provides many features which facilitates the programming process. For example,

1. Provides Intellisense - You just have to type part of the Keyword, the full name appears
for you to sense.

2. Syntax checking - Helps to avoid compilation errors

3. Code Generators - For example, Eclipse provides a feature that can be used to generate
getters and setters automatically from an instance variable defined in a class.

4. Refactor - This feature provides many more other functionalities. The rename function
itself is powerful as it avoids us to have to change all the names of a particular variable. With
PAGE 3 OF 31! ! TOPIC 1
INTRODUCTION TO JAVA! !

this feature, changing only one instance of this variable changes all the instances of the same
variables in the project.

5. Snippets - Some context-sensitive editor does provide something called snippets. For some
routine block of codes (like an if statement or loop statement), the programmer just has to
type a special keyword and then press some key combination and like a magic the block of
codes are generated.

What is an IDE?
An Integrated Development Environment (1 mark) is an application which integrates all the tools
required to develop a piece of software such as a text editor and compiler.

Benefits of an IDE
1. IDEs make the development process easier to manage

2. usually provide additional support that is not available with standalone tools such as debuggers
and packaging.

Java language - Object-oriented Language


Java is a fully object-oriented language. This is because everything is defined as a class. Even the
primitive data types are classes. So, Java is a very prospective language for Object-oriented
development (where the analysis and design is done with the Object-oriented paradigm).

What is a Class?
In Object-oriented context, a class is like a “template” or “blueprint” which contains all the
specifications (attributes and methods) which is used whenever an object of the class has to be
created.

Basic Structure of a Java Class


General Structure:

class-name: Should start with a letter (As a convention, we use a Capital Letter)

PAGE 4 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Difference parts of a typical class


A typical class usually consists of the following:

1. Instance variable Section - It is the place where all instance variables are declared (more on
these later).

2. Constructor

3. Methods

4. inner classes

Constructor
A constructor is a special method which each class has. This method differs from normal methods in
the following ways:

1. It shares the SAME name as the class name.

2. It is implicitly (automatically) called whenever an object is being created from a class.

3. It does NOT have any return value (so even the keyword void should not be included).

4. Even if the user does not define a constructor, the compiler will include one (usually called a
default constructor).

Below are three examples of a class where a constructor is defined.

This one shows that a constructor (just like any other methods) can have parameters.

Constructors are usually used to initialise the instance variables. A class can have more than one
constructor provided that all of them have different signature (combination of return type and
parameters).

PAGE 5 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Using the word “this”

It is very common to find java programmers to use the same


name for instance variables and the variables in the Parameter
list. In such case, the word “this” is used to differentiate
between the instance variable and the parameter.

What is an Object?
Just like a building is an instance of its architectural design, an object is an instance of a class.

The building has been created based on all the specifications present in the architectural design.
Likewise, an object is created based on all the specifications (attributes and methods) present in the
class. Generally, more than one object can be created from a class.

All instance variables (especially those which have accessors defined) in the class become the
attributes of the object and all public methods define the behaviors of the object.

Difference between an object and a class.


A class is a “blueprint” which should be used to create an object. In other words, an object is an
instance of a class.

Creating an object from a class


An object is created from a class by using the keyword “new”. One example is given below.

new Game ( );

This code will create an object from the class Game. Note that Game ( ) is the constructor.

Datatypes
In an Fully Object-Oriented language (like Java), everything is an Object (which is defined by a
class). Just like in our real-world, all objects have types (for example, Car is a type of object).

Moreover, inside of an object there are instance variables which will define the attributes of the
object. In Java, all the variables have a type. Usually, this is called a datatype.

So, a datatype can be defined as follows:

A datatype is an abstraction (is in fact a class) which states which type a variable (can be an instance
variable or an object variable) belongs.

PAGE 6 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

There are different datatypes come along with Java. Some are listed below:

1. Integer - defines whole numbers

2. Boolean - can be true or false

3. Double - represents a number which has a decimal point.

4. User-defined datatypes (classes written by the programmers)

In Java, datatypes can be sub-divided into two distinct categories. They are as follows:

1. Primitive datatypes

2. Reference datatypes

Primitive Datatypes
These are datatypes which come along with java (excluding String and Lists). Primitive data types
are the building blocks of data representation and are provided by the language.

Some examples are:

1. Integer

2. Double

3. Boolean

Reference Datatypes
Reference data types are instances of objects, although some of them are also handled by java
keywords (e.g. String). All user-defined classes are reference datatypes.

Differences between primitive datatypes and reference datatypes


1. All primitive datatypes come along with Java. That is, they are all defined by Java itself. Apart
from String and Lists (ArrayList, LinkedList etc...), all reference types are written by the
programmers.

2. Though primitive datatypes are defined by classes, it is optional to use the word “new” whenever
we need to create an object. Apart from String, the creation of all Objects of reference types use
the “new” keyword.

PAGE 7 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

3. A variable (a container) of a primitive datatype contains the value itself. This is not the case for
variable of reference datatype. The latter contains a reference (the memory address of the
memory cells that contain the value) instead of the value itself. This fact can be depicted as
follows:

One"implication"of"this"is"when"we"copy"one"object"into" another"one,"instead"of"a"copy" of"the"


value" " is" done," the" reference" is" copied." Hence," a" change"brought" to" one"variable"affects" the"
value"of"the"original"variable.
See"the"codes"below:

Java is Strongly-typed Language


High-level languages can be classified into two types when it comes to declaring variables:

1. Loosely-typed

2. Strongly-typed

PAGE 8 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

In a loosely-typed programming language (like PHP), there is no need to mention the datatype
whenever a variable is being declared.

In a strongly-typed language (like C, C++, C# and Java) it is mandatory to mention the datatype
whenever a variable is being declared. Note that if a variable is declared as an integer, it cannot store
any variable other than an integer.

Benefits of Strongly Typed


Benefits include
1. finding errors earlier in the development process
2. the ability of the compiler to generate meaningful errors .

Declaring variables in Java


A variable declaration follows this pattern:

<datatype> variableName;

Examples:

Initialisation of Variables
Usually, after creating a variable, it is wise to store a value inside this variable.

Instantiation of an Object
Instantiation of an object is the process of creating an object from its class. The keyword “new” is
used for this process. During instantiation the constructor is called automatically.

PAGE 9 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Instance Variables
An object has both attributes and behaviours. The attributes of an object are usually defined by the
instance variables in a class.
Instance variables are variables that are declared at the class level. That is, they are declared outside
the methods.

Instance variables and local variables


Unlike an instance variables, a local variable is declared inside a method.

Lifetime of Variables
An instance variable lives as long as the object lives. This is not the case for local variables which are
found in the methods. A local variable lives as long as the method is being executed. Once the
execution is over the variable is more alive.
In other words, a local variable does not retain its value for further execution of the methods.

Methods
While the attributes of an object are defined by instance variables, the behaviors of an object are
defined by the methods present in the class.
A method is a self-contained piece of code that sits dormant until it is called (aka invoked) by the
main method or by another method.
PAGE 10 OF 31! ! TOPIC 1
INTRODUCTION TO JAVA! !

Below are examples of methods:

main method
The main method is the
starting point of a java
program and is the method
that java will look for when
a program is executed
(entry point of a java
program).

PAGE 11 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Why main method is a static method?


Generally to access a method, we should create an object from the class containing the method.
Then, the method is accessed as shown by the example below:

We cannot access the area method without creating a Circle object.

Main method cannot be made a non-static method. This is because in such case, we should have
created an object before accessing the main method. Since the main method should be the first
thing to be executed this is not possible.

By making a method static, we can access the method without having to create the object.

Access Modifiers (aka visibility modifiers)


There are three types of access modifiers:
1. public - it gives access to all the external world.
2. protected - Accessibility is restricted to the class it is present and also all child classes.
3. private - Accessibility is restricted to the class it is present only.

Visibility of Instance Variables and Methods


Visibility refers to the level of access other objects have to methods and attributes. The higher the
visibility, the more objects can make use of the internal code of other objects. Public is the highest
visibility and means the variable or method is fully open and can be made use of by any class,
protected is less open than public and means that objects of the class in which the method or
variable are defined have access, as does any class that extends that class, and private is the lowest

PAGE 12 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

visibility level and means that only objects of the class in which the method or variable are defined
have access.

One of the pillars of Object-oriented is Encapsulation. This concept states that all instance variables
of the class should be encapsulated (kept private) and their values (if the need arises) to be accessed
via accessors (getters and setters).

Generally, methods are given the public access modifier. However, if a method is to be accessed
only by the class it is in, then this method should be kept private (this type of method is usually called
helper method).

Accessors - Getters and Setters


Since we should not allow the external world to access the instance variables of a class, we should
provide Accessors to them.

The two accessors are:


1. Setter - It is a method which is used to set the value of an instance variable. Note that a setter
does not return a value so the keyword “void” should be used.
2. Getter - It is a method which is used to get the value of an instance variable. Getter does not
normally have any parameter.
Generally, getters and setters are given the public visibility modifiers. This is to allow the external
world to access them.

PAGE 13 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Standard classes
Java provides some standard classes. For example, Java provides a Math class. The latter is a
container for mathematically related methods. It is part of the standard Java class and means that
developers do not need to code their own implementations of standard mathematical processes.

Some methods of the math class are listed below:

Method in Math Class Description

static double sqrt(double a) This method returns the correctly rounded positive square
root of a double value.

static double random() This method returns a double value with a positive sign,
greater than or equal to 0.0 and less than 1.0.

static double sin(double a) This method returns the hyperbolic sine of a double value.

static int round(float a) This method returns the closest int to the argument.

static double abs(double a) This method returns the absolute value of a double value.

Inner Classes
If a class B is such that only class A will be using it, it is wiser to write class B inside Class A. So,
Class B is said to be an inner class of Class A. Usually we can give a private access modifier to the
inner class.

PAGE 14 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Packages
Packages allow us to group together classes into a library of our own that we can make available to
other projects. Usually, the classes are grouped according to a logical way. For example, all the
math classes are placed in a math package.

Casting
Casting is a process of converting one object of one type to another object. For example, converting
a double to an integer.
The benefit of casting is that it adds flexibility in coding.

One downside of casting is that they can be loss of information as shown above. Instead of getting a
value of 4, a value of 3 is obtained.
Note that a String cannot be casted to an integer.

In this case, Integer.ParseInt( ) method should be used.

Implicit Conversion
Implicit conversions mean that you don’t have to explicitly convert the data to a different type. To
do this in Java, you simply append a primitive variable of another type onto the end of an empty
string, and Java will convert the variable into a string before concatenating it onto the end of the
existing string. e.g.:
int num = 42;
String numAsString = “”;
numAsString = numAsString + num;

PAGE 15 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Comments in Java
Programmers use to comment their codes for several reasons. For example, to explain the logic
behind the codes.

There are three types of comments in Java. They are listed below:

1. Single-line comment

2. Multiple-line comment

3. Java-doc

Examples of all the three types are given below:

PAGE 16 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Method Overloading
This involves creating a method with the same name but with different signature (meaning that
there is at least one thing - either return type or type of a parameter
For example,

Constructor Overloading
Even though, constructor is a special method, it can also be overloaded. To do so, we have to give
all the constructors different signature. Since a constructor does not have a return type so the latter
does not contribute in the signature. Hence, different signature means different parameter lists.

PAGE 17 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

PAST PAPERS QUESTIONS

! MARCH 2012
Explain what purpose the main method in a Java program serves, and provide the
code for a main method that creates an instance of the class in which it is contained.

[6]

Answer:

The main method is the starting point of a java program (1 mark) and is the method that java
will look for when a program is executed (1 mark).

4 marks for the example which should include the correct method signature of the main method (2
marks) and the correct code for creating an instance of its container class (2 marks)

Explain what is meant by ‘primitive’ data type and ‘reference’ data type, and give an
example of each.

[4]

Answer:

Primitive data types are the building blocks of data representation and are provided by the language
(1 mark). Reference data types are instances of objects, although some of them are also handled by
java keywords (1 mark). An int is a primitive data type (1 mark), while a String is a reference data
type (1 mark).

Define the words ‘Class’ and ‘Object’, and explain the relationship between them.

[4]

Answer:

A class defines the methods and variables for a particular class of object (1 mark) and an object
defines the state of those variables (1 mark). An object is an instantiation of a class (1 mark), and the
class acts as the blueprint for the object (1 mark).
PAGE 18 OF 31! ! TOPIC 1
INTRODUCTION TO JAVA! !

Define what is meant by a strongly typed language and explain what benefits strong
typing provides for software developers.

[4]

Answer:

Strongly typed languages limit how variables of different data types can be intermixed (1 mark),
ensuring that invalid operations are caught as early as possible (1 mark). Benefits include finding
errors earlier in the development process (1 mark), and the ability of the compiler to generate
meaningful errors (1 mark).

Provide code examples of the getter and setter for an integer variable called ‘value’,
and explain why getters and setters are used in OO programming.

[6]

Mark Scheme Remarks:


2 marks each for the getter and the setter. Justifications should include the need for encapsulation (1
mark) and the need for controls to be placed around the manipulation of data elements so as to
ensure consistency (1 mark).

Answer:

Getters and setters are used to access the instance variables which are kept private so that they
cannot be manipulated directly outside the class. This is inline with the encapsulation concept.
Another reason for their existence is due to a control placed around the manipulation of these data
elements so as to ensure consistency.
Explain what is meant by the term ‘visibility’ and give TWO (2) examples of visibility
modifiers in Java.

[4]

Answer:

Visibility refers to how generous a program is with when a variable or method can be invoked (1
mark). The higher the visibility, the more objects can make use of the internal code of other objects
(1 mark). Public is the highest visibility (1 mark), and private the lowest (1 mark).

PAGE 19 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

JUNE 2012
State the difference between an interpreter and a compiler.
[4]

Answer:

An interpreter takes each instruction in turn (1 mark) and tells the underlying system what task must
be performed (1 mark). A compiler takes the whole program (1 mark) and converts it into machine
code (1 mark) which can be executed directly by the computer (1 mark).

Give three examples of primitive data types and give an example as to when each
would be appropriate.

[4]

Answer:

Three examples of primitive data types are:

1. integer

2. boolean

3. double

//Example for integer

int totalClick; //totalClick is a variable which keeps track of how many times a user clicks a button

//Example for boolean

boolean isValid; //isValid is a variable which can take a value of either true or false.

//Example for double

double radius =3.5; //radius takes a number with a decimal point.

Explain what the Math class is for, and give three examples of methods that it makes
available.

[6]

Answer:

The Math class is a container for mathematically related methods (1 mark). It is part of the standard
Java class (1 mark) and means that developers do not need to code their own implementations of
standard mathematical processes (1 mark). 1 mark for each example.

PAGE 20 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Explain what is meant by instantiation, and give a code example of it being done.
[4]

Answer:

Instantiation is the process of creating an object (1 mark) from a class (1 mark). 4 marks for an
example.

Car myCar = new Car (“Toyota”);

Outline the elements that differentiate a constructor method from other methods in
a class.
[4]

Answer:

Constructor methods have no return type (1 mark), cannot be executed except when an object
is instantiated (2 marks), must have the same name as the class in which they are contained (1 mark)

Outline the four parts of the body of a class, and give an example of something from
each.
[4]

Answer:

A class is broken down into four main parts – the attributes (1 mark), the constructor (1 mark), the
methods (1 mark) and inner classes within the main class (1 mark). 1 mark for each example.

Explain the Java concept of a package.

[2]

Answer:

Packages allow us to group together classes (1 mark) into a library of our own that we can make
available to other projects (1 mark).
PAGE 21 OF 31! ! TOPIC 1
INTRODUCTION TO JAVA! !

Explain the difference between casting a string to an integer and using the
Integer.parseInt method.

[5]

Answer:
Casting is used to provide type information (1 mark) where it may otherwise have been lost by java (1
mark), or to get Java to treat primitive data types as other kinds of data type (1 mark), whereas
parseInt will convert a string containing a number to an actual integer (1 mark) which cannot be
done by casting (1 mark).

Explain what is meant by data visibility, and give an example of programming


structures that can be used to provide access to variables with low visibility.

[5]

Answer:

Data visibility is the degree to which other objects can see methods and attributes of an object (1
mark), and it is managed through the visibility modifiers (1 mark). The best way to handle attributes
in a class is to set attributes as private (1 mark) and to provide a getter (1 mark) and setter (1 mark) to
permit manipulation.

SEPTEMBER 2012
Explain what is meant by an ‘IDE’ and what the benefits are of using one.

[4]

Answer:

An Integrated Development Environment (1 mark) is an application which integrates all the tools
required to develop a piece of software such as a text editor and compiler (1 mark). IDEs make the
development process easier to manage (1 mark) and usually provide additional support that is not
available with standalone tools (1 mark) such as debuggers and packaging.

Explain what is meant by the term ‘Virtual Machine’ and how its use differs from
platform-dependent interpretation and compilation.

[6]

Answer:

A virtual machine interprets byte-code (1 mark), which is produced when a java program is compiled
(1 mark). It differs from platform specific compilation in that a dedicated virtual machine must be
written for a platform (1 mark), and the bytecode is deployed there rather than on the platform (1
mark). The result of this is that code written for one platform will run (in most cases) on any
platform (1 mark). Virtual machines usually incorporate some form of compilation, so they run faster
than interpreted code (1 mark)

PAGE 22 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Explain what is meant by the term ‘instantiation’, and what it implies about the
relationship between an object and a class.

[4]

Answer:

Instantiation is the process of making an object from a class (2 marks). This implies that a class acts
as a blueprint (1 mark) and that the object acts as a specific instance of that blueprint (1 mark)

Give an example, using code where appropriate, of a sensible constructor method for
a Student class that contains attributes for name, address and age.

[5]

Answer:

Marking Scheme remark:2 marks for the correct format of the constructor, one mark for
handling each of the parameters.

Explain what is meant by ‘casting’ in Java, and give an example.

[2]

Answer:

Casting involves taking an object of one type and making it another (1 mark). 1 mark for a suitable
example.

Example:

double b =3.8;

int a = (int) b;

Explain what is meant by the term ‘accessor method’, and provide a code example of
accessor methods in use.

[4]

Answer:

An accessor method is the public interface (1 mark) to a variable that has been made private or
protected (1 mark). 2 marks for an example.

PAGE 23 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Describe what is meant by ‘public’ and ‘private’ visibility, and give an example of when
each would be appropriate.

[4]

Answer:

Public visibility means that any code that can get access to the object can access the variable or
method (1 mark), whereas private visibility means that only objects of the class in which the method
or variable is defined can gain access. Private visibility is appropriate for attributes in a class (1
mark), and public visibility is appropriate for accessor methods (1 mark).

DECEMBER 2012
Describe the difference between an interpreter and a compiler and give one benefit of
each.

[6]

Answer:

An interpreter takes each instruction in turn (1 mark) and tells the underlying system what task must
be performed (1 mark). A compiler takes the whole program (1 mark) and converts it into machine
code (1 mark) which can be executed directly by the computer (1 mark). Using an interpreter means
the code can be platform independent (1 mark for any suitable advantage). Using a compiler means
that you do not have to make the source code available which makes it harder for a competitor to
reverse engineer your software (1 mark for any suitable advantage).

PAGE 24 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Describe the difference between primitive and reference data types and give an
example of each.

[4]

Answer:

Primitive data types are the building blocks of data representation and are provided by the language
(1 mark). Reference data types are instances of objects, although some of them are also handled by
java keywords (1 mark). A double is a primitive data type (1 mark for a suitable example), while a
String is a reference data type (1 mark for a suitable example).
Explain what is meant by implicit conversion with regards to converting primitive
data types to Strings in Java, and provide an example of how to do this in Java.

[4]

Answer:

Implicit conversions mean that you don’t have to explicitly convert the data to a different type
(1 mark). To do this in Java, you simply append a primitive variable of another type onto the
end of an empty string, and Java will convert the variable into a string before concatenating it onto
the end of the existing string (1 mark). e.g.:
int num = 42;
String numAsString = “”;

numAsString = numAsString + num; (2 marks for a suitable example)

Define the terms Class and Object, explaining how they are connected.

[4]

Answer:

A class defines the methods and variables for a particular class of object (1 mark) and an object
defines the state of those variables (1 mark). An object is an instantiation of a class (1 mark), and the
class acts as the blueprint for the object (1 mark).

When an object is instantiated, the Constructor method is called. Give an example of


a Constructor method for a Book class which contains the attributes ‘title’ and
‘author’. The Constructor method should take in the values for these attributes.

[4]

Answer:

public Book (String t, String a){


title = t;
author = a;

}
(2 marks for correct format of constructor, 1 mark for handling each of the parameters)
PAGE 25 OF 31! ! TOPIC 1
INTRODUCTION TO JAVA! !

Describe two ways in which Constructor methods differ from other methods.

[2]

Answer:

Constructor methods have no return type (1 mark) and have the same name as the Class (1
mark).

Explain what is meant by the term ‘visibility’, and describe the THREE (3) visibility
modifiers, ranking them in order from highest to lowest level of visibility.

[5]

Answer:

Visibility refers to the level of access other objects have to methods and attributes (1 mark). The
higher the visibility, the more objects can make use of the internal code of other objects (1 mark).
Public is the highest visibility and means the variable or method is fully open and can be made use of
by any class (1 mark), protected is less open than public and means that objects of the class in which
the method or variable are defined have access, as does any class that extends that class (1 mark), and
private is the lowest visibility level and means that only objects of the class in which the method or
variable are defined have access (1 mark).

MARCH 2013
Explain what is meant by the term method.

[2]

Answer:

A method is a self-contained piece of code (1 mark) that sits dormant until it is called (aka invoked)
by the main method (1 mark).

Define the term instantiation, and explain its use in reference to classes and objects.

[4]

Answer:

Instantiation is the process of creating an object (1 mark) from a class (1 mark).The class acts as an
abstract template which contains details of the types of information that should be stored about
objects of that type (e.g. all Employees will have a StaffID, Name, Job Title, etc), and the
behaviours to manipulate that information (1 mark). Objects are instances of the template and
contain values for all the attributes, for example Employee object John Snow has StaffID =
“E800536”, Name = “John Snow”, Job Title = “Network Manager”. An object has a state, which is
the current values of all the attributes of that object (1 mark).

PAGE 26 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Java is a strongly typed language. Explain this term, and explain its relevance in
relation to the technique known as casting.

[4]

Answer:

Strongly typed languages require you to indicate the data type of a variable when you declare it (1
mark) and limit how variables of different data types can be intermixed (1 mark). Sometimes we may
want to change a variable from one data type to another (1 mark). This is done implicitly in weakly
typed languages (1 mark) but requires the use of casting for most data type conversions in strongly
typed languages (1 mark). Casting involves taking an object of one type and explicitly converting it
to another data type (1 mark).

Define the term constructor method and explain its role in relation to method
overloading. Give an example of where you have used this technique.

[6]

Answer:

Constructor methods are called when (and only when) a new object is instantiated (1 mark).
Constructor methods have no return type and must have the same name as the class in which they
are contained (1 mark). It is possible to have multiple Constructor methods for an object using
method overloading (1 mark). This would involve having two or more Constructor methods with
different method signatures (1 mark). For example, one Constructor method that does not take in
any parameters and sets default values for the object’s attributes, and another Constructor method
which takes in a parameter list and uses the parameters to initialise the attributes (1 mark). 1 mark for
a suitable example. A possible suitable example would be constructors for a bank account class. One
takes in no parameters and sets the account balance to 0. The other takes in a value for the account
balance.

public class Account( ){ double balance;


public Account() {

balance = 0.0;
}
public Account (double b) {

balance = b;
}

PAGE 27 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Explain the term visibility and explain what the three main visibility modifiers do.

[6]

Answer:

Visibility refers to how generous a program is with when a variable or method can be invoked (1
mark).Public is the highest visibility and means the variable or method is full open and can be made
use of by any class (1 mark), protected is less open than public and means that objects of the class in
which the method or variable are defined in have access, as does any class that extends that class (1
mark), and private is the lowest visibility level and means that only objects of the class in which the
method or variable are defined have access (1 mark).

Outline what is meant by an accessor method and give a code example of the accessor
methods that would go with a String variable called output.

[6]

Answer:

An accessor method is the public interface (1 mark) to a variable that has been made private or
protected (1 mark). The ‘get’ accessor method enables us to query the current state of the variable (1
mark) and the ‘set’ accessor method enables us to update the value of the variable
(1 mark).
String output;
public String getOutput(){

return output;
} (1 mark)
public void setOutput(String op){

output = op;
} (1 mark)

JUNE 2013
Describe the process by which a compiler converts program instructions into machine
code, and give ONE (1) advantage of compilation.

[4]

Answer:

A compiler takes the whole program (1 mark) and converts it into machine code (1 mark) which can
be executed directly by the computer (1 mark). Using a compiler means that you
do not have to make the source code available which makes it harder for a competitor to reverse
engineer your software (1 mark for any suitable advantage).

PAGE 28 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Java is an interpreted language which runs on the Java Virtual Machine. Explain what
is meant by the term Virtual Machine and how its use differs from platform-
dependent interpretation and compilation.

[6]

Answer:

A virtual machine interprets byte-code (1 mark), which is produced when a Java program is
compiled (1 mark). It differs from platform-specific compilation in that a dedicated virtual machine
must be written for a platform (1 mark), and the bytecode is deployed there rather than on the
platform (1 mark). The result of this is that code written for one platform will run (in most cases) on
any platform (1 mark). Virtual machines usually incorporate some form of compilation, so they run
faster than interpreted code (1 mark)

When an object is instantiated, the constructor method is called. Give an example of


a constructor method for an Employee class which contains these attributes: empID,
name, jobTitle and salary. The constructor method should take in the values for these
attributes.

[6]

Answer:

public Employee (String id, String n, String j, double s){


empID =id;

name = n;

jobTitle = j;
salary = s;

}
(2 marks for correct format of constructor, 1 mark for handling each of the parameters)

SEPTEMBER 2013
Explain the difference between an interpreter and a compiler.
[4]
Answer:
An interpreter takes each instruction in turn (1 mark) and tells the underlying system what task must
be performed (1 mark). A compiler takes the whole program (1 mark) and converts it into machine
code (1 mark) which can be executed directly by the computer (1 mark). Maximum 4 marks.

PAGE 29 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Give THREE (3) primitive data types and give an example as to when each would be
appropriate.
[6]
Answer:
Primitive data types include:
! integers: example of use: to store an exam mark between 0 and 100 where no half
marks are awarded
!  doubles: example of use: to store the value of Pi as accurately as possible
!  chars: to store a single character e.g. ‘F’ or ‘M’ for gender
!  floats: example of use: to store the height of a person in metres.
!  boolean: example of use: to store the result of a yes/no user choice.
One mark for each data type up to a maximum of 3.
One mark for each suitable example, up to a maximum of 3.

Describe the purpose of the main method in a Java program, and provide the code for
a main method that creates an instance of the Engine class in which it is contained.
[6]
Answer:
The main method is the starting point of a java program (1 mark) and is the method that java will
look for when a program is executed (1 mark).
public static void main (String[] args){
Engine myEngine;
myEngine = new Engine();
}
4 marks for the example which should include the correct method signature of the main method (2
marks) and the correct code for creating an instance of its container class (2 marks)
Write a Constructor method for a Car class that contains attributes for make, model
and price.
[5]
Answer:
public Car (String make, String model, double price) {

this.make = make;

this.model = model;

this.price = price;

2 marks for the correct format of the constructor, one mark for handling each of the parameters

PAGE 30 OF 31! ! TOPIC 1


INTRODUCTION TO JAVA! !

Explain the term typing in relation to Java programs, and outline how Java employs
the concept.

[5]

Answer:

Typing is the process of assigning a data type (1 mark) to a variable (1 mark). Java is a strongly typed
language (1 mark) that differentiates between primitive data types (1 mark) and reference data types
(1 mark).

PAGE 31 OF 31! ! TOPIC 1

Anda mungkin juga menyukai