An Introduction to Java, Lab Reports of Mobile Computing

An introduction to the java programming language, covering its background, the imperative programming style, data types, declarations, selection statements, methods and method calls, dynamic and static memory allocation, defining classes, inheritance, and the java api. It covers key concepts such as objects, classes, interfaces, and inheritance, as well as the syntax and structure of java programs. Intended to serve as a comprehensive overview of the fundamental aspects of java for students or learners new to the language.

Typology: Lab Reports

2022/2023

Uploaded on 05/09/2023

just-thumbs-up
just-thumbs-up 🇿🇦

1 document

1 / 38

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
An Introduction to Java
Notes by Scott Hazelhurst
Lectured by Pravesh Ranchod
2013
1Background
Java developed in the 1990s by Sun Microsystems:
Basic philosophy: model world as objects
Organise the world into classes of objects;
Objects can communicate using methods
Underlying model of computation imperative.
Some of the goals are:
use of libraries, promote reuse of code, portable
Provides facilities for: web programming, network programming, mul-
tithreading, GUI.
Progression from existing languages: C-like in syntax.
Note that we are going to use Java 5 or later. Although most of what
we shall study here applies to earlier versions of Java too, the following
features denitely will not work in earlier versions of Java:
Enumerated classes
Extended for statments
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26

Partial preview of the text

Download An Introduction to Java and more Lab Reports Mobile Computing in PDF only on Docsity!

An Introduction to Java

Notes by Scott Hazelhurst

Lectured by Pravesh Ranchod

1 Background

Java developed in the 1990s by Sun Microsystems:

  • Basic philosophy: model world as objects
    • Organise the world into classes of objects;
    • Objects can communicate using methods
  • Underlying model of computation imperative.
  • Some of the goals are:
    • use of libraries, promote reuse of code, portable
  • Provides facilities for: web programming, network programming, mul- tithreading, GUI.
  • Progression from existing languages: C-like in syntax.

Note that we are going to use Java 5 or later. Although most of what we shall study here applies to earlier versions of Java too, the following features denitely will not work in earlier versions of Java:

  • Enumerated classes
  • Extended for statments
  • Generic classes

Some Java-Python differences!

  • Java has distinct compile and run-time phases Python only does very simple syntactic checking.
  • Java is explicitly typed.
    • Types checked at compile and run time
  • Rules of scope are different (i.e. what’s local, what’s global)
  • Java has much more syntactic overhead.
  • Lots of minor differences.

2 Object-orientation and programming-in-the-large

Software crisis Cost of software typically by far most expensive part of any system Complexity grows Complexity of program superlinear in size of pro- gram:

  • Mythical Man-Month

Modularity and Code re-use seen as possible solutions Program is made up of a number of units called classes. Good programmers need to:

  • Be able to use classes already dened
  • Extend existing classes
  • Build new classes
    • Clean interface to outside world
    • Correct, efcient functionality

3 Basic Components of a Java Program

A Java program must contain one public class.

  • instance variables (either Java primitive types or using other class denitions).
  • methods (procedures/functions)
  • A method is a named, separately callable sequence of code.
  • One method called main must be dened.

When the program starts to run, the main methods starts executing. It can call other methods. Slightly different rules apply to applets. Our rst example

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

  • The keyword public indicates that the class and method can be ac- cessed outside of the current environment — more detail later.
  • Note that we use a method in the System class for outputting.
  • If we compile and run the program, then the main method executes.

4 The imperative style

The underlying model of computation of Java is the imperative program- ming style:

  • We have a set of variables or objects that store data or state.
  • Statements are executed in order, changing the values of variables or objects.

int i, j; float f; .. .. i = i+10; j = Math.abs(j-2*i); i = Math.ceil(f)+i; .. ..

5 Variables

  • In Java, all variables must be declared before being used.
  • All variables have a type which describes which values they can take on.
  • Variables can either be:
    • primitive Java types
    • complex or reference types, objects of any class (actually refer- ences to these)

The type of the variable not only describes the values the variable can take, but operations that can be performed. Need to be type-consistent.

int a, apple; int j33, banana; int cherry = 3, data = 0, k;

a = 3; apple = 2; banana = 1; a = a + 1; apple = apple + a;

int i, j; char j, answer; long rainfall; float radius, r3;

By convention, variable declarations given rst:

  • Makes the variables in a function clear;
  • But, can give variable declarations anywhere, and sometimes there are good reasons for doing so;
  • Variable can only be declared once in a method;
  • But variables with same name can exist in many methods, classes.
  • NB: just because two variables have the same name doesn’t mean they are the same. Scope rules say which is which.
  • Can initialise in a declaration.

Other modiers possible: e.g. static, nal etc. We’ll look at modiers later Variables have four important features:

  • Name by which they are referred in program. This is context dependent – scope rules.
  • What it represents conceptually
  • Reference or Address Where in memory it is physically stored
  • Value: the value that is stored there

7 Flow of control

When a program starts to run, the main method starts executing. Statements are executed sequentially in order except when altered by:

  • call to another method and when a method nishes executing, control passes back to where it was called
  • selection if, switch statements allow us to make choices
  • iteration for, while and do loops allow us to repeat sections of code.

A statements in a Java program can be a:

  • declaration
  • assignment statement
  • selection (e.g. if, switch)
  • loop (e.g. for, while)
  • method invocation (function call) method can be one you have written, or from a library, or from some other class.
  • compound statement: {sequence-of-statements}

7.1 Assignment

The most common form of the assignment is

varname = value;

On the left is a variable, on the right a value that is type compatible:

  • && does short-circuit evaluation; & does not. Suggestion: use one or the other, not both.
  • Conditional operator is ternary

boolean b; ... x = b? y : z; <--- if (b) x=y; else x=z; ...

This is not a complete list of all the operators. For example, there are integer bit-wise operators for doing bit-wise and, or and complementation. For example 325&7 represented in binary is 0101000101&0000000111 which is 101. We have done a bit-wise and of the bits in the number.

8 Input

Scanner To read an integer from the keyboard into a variable x:

import java.util.Scanner; public class Test{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int x = in.nextInt(); } }

  • Creating a Scanner object allows us to get that object to do the work for us
  • When the program runs, it suspends at in.nextInt(), waiting for keyboard input.
  • The user must then type in an integer using the keyboard and press the RETURN key.
  • The program then continues executing – the value the user typed in is stored in the variable x (it’s an assignment statement, remember).

The Scanner class provides a number of useful functions to read input:

  • nextInt() reads and returns an int
  • nextLine() reads and returns a String, by reading an entire line of text
  • nextDouble() reads and returns a double

Note that there are some complications involved, so in a lot of cases it makes sense to use nextLine() wherever possible. This can be accom- plished by converting the returned String into the data type required. For instance, if you needed to read in an int value, it could be done in the following way:

Scanner in = new Scanner(System.in); String r = in.nextLine(); int val = Integer.parseInt(r);

9 Selection

selection if The if statement is the most important method of selection: General form 1

if (condition) statement;

General form 2

if (condition) statement; else statement;

  • Parentheses around the condition is obligatory
  • If you need multiple statements, then need {sequence-of-statements}
  • Take care that indentation doesn’t mislead.
  • Can use braces to change if necessary.
  • Always a good idea to use braces for the then and else parts.

The switch statement is the other Java selection method:

switch (value) { case v1 : sequence-of-statements; case v2 : sequence-of-statements;

... case vn : sequence-of-statements; default : sequence-of-statements; };

Variable value is evaluated.

  • Each of the cases is examined in turn.
  • If a case matches value exactly, all the statements in the switch state- ment from that point on are executed.
  • If no case matches, optional default section executed. Typically use the break keyword to only have some of the state- ments executed.

switch (day) { case 0 : rate = 2.0; break; case 1 : rate = 0.8; break; case 2 : rate = 1.0; break; case 3 : case 4 : rate = 1.2; break; case 5 : case 6 : rate = 1.8; break; }

Using the switch statement:

  • Take care – usually want to have a break at the end of each case, but easy to forget and compiler doesn’t catch. switch is insecure in this way.
  • Usually good practice to put in a default section: it might just be error handling code to deal with unexpected values.
  • Always put a break at the end of the nal non-default case section.

The switch statement is very useful, but used too often can lead to complex code:

  • use of polymorphism in object-oriented programs reduces need to use it.
  • use table-based methods.

These latter approaches are more compact, often more efcient, easier to read and to maintain.

10 Loops

Three loops in Java, while , for , and do.

10.1 While loops

General form of the while loop is:

while (cond) statement

Evaluate the condition; if it’s true the statement is executed and then we repeat...

  • Good idea to use { statement-sequence } for body of loop;

10.2 For loops

General format is

for (init; cond; change) statement;

Semantics are:

  1. The init statement is rst executed;
  2. If cond is true the body is executed;
  3. After body is executed, change is executed;
  4. Goto step 2

In 1.5 there is a construct analogous to Python’s for statement. We’ll look at it after doing arrays.

for (i = 1; i <= 10; i++) { n = n + i − 3 ∗ n; System.out.println (i + ′′^ computer and its mouse went to mow a meadow” ); };

for (i = 10; i >= 1; i--)...

for (i = 0; i < 10; i++)...

Real computer scientists count from zero!!!! Example

static void compfn () { int x; double y1, y2; for (x=0; x<100; x=x+10) { y1 = 3.1xx - 38x + 15; y2 = 2xx + 2x + 1; System.out.print("x = "+x+"; y1= "+y1+"; ‘‘+ "y2="+y2+"; "); System.out.println(y1>y2?"+":"-"); } }

10.3 Do loops

Similar to the while loop except the condition testing is done at the end.

do {

... } while (cond); - Can use break and cont; - Take care in indentation.

10.4 Summary

Any loop can be coded as any of the three!

  • The for loop is the most powerful – don’t try to do too much, strive for simplicity.

11 Reference/Complex data types and references

The use of references is one of the basic features of the semantics of Java. For primitive types, when a variable is declared,

  • The compiler allocates memory big enough to store a value of that type;
  • String has many string manipulation routines – read up about them in a reference.
  • Examples:comparesTo and equals.

Why do a and b end up with different values?

String s1, s2; boolean a, b;

s1 = new String (”Wits”); s2 = new String (”Wits”);

a = s1.equals(s2); b = s1 == s2;

11.2 Simple Java arrays

An array is an homogeneous collection of objects, the individual elements of which can be accessed by index.

  • The rst item is indexed by zero;
  • The last item by n − 1 if the length of the array is n

Type array name[]; array name = new Type[n];

  • May need to worry about the memory allocation of individual items if the type is not primitive.

int rainfall[], sum; rainfall = new int [12]; sum = 0; for (int m = 0; m < 12; m + +) {

rainfall[m] = in.nextInt(); sum+ = rainfall[m]; }

int rainfall[][]; rainfall = new int [12][31];

  • Array size can be determined at run-time;
  • Can have multiple dimensions

For more complex objects, may need to take care of memory allocation:

Animal pets[]; String d; pets = new Animal[12]; for (int m = 0; m < 12; m + +) { d = in.nextInt(); pets[m] = new Animal(d); }

11.3 The enhanced for statment

There is a form of the for loop analogous to the for loop in Python.

for(variable : collection) statement

  • This allows looping over an array or a collection
  • The variable takes in turn the values of each value in the collection and the corresponding statement is exected.

Note:

  • You can iterate over a primitive Java array.
  • You can iterate over an object of any class which implements the Iter- able interface.