Programming using Java
Java Classes and Objects
Arrays
Objectives:
Get an introduction to Classes and Objects
Get a general idea of how a small program is
put together
Simple Java Program
A class to display a simple message:
public class Hello {
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
Running the Program
Type the program, save as
[Link].
In the command line, type:
> ls
[Link]
> javac [Link]
> ls
[Link], [Link]
> java Hello
Hello World!
Explaining the Process
1) creating a source file - a source file contains text written
in the Java programming language, created using any
text editor on any system.
2) compiling the source file Java compiler (javac) reads
the source file and translates its text into instructions that
the Java interpreter can understand. These instructions are
called bytecode.
3) running the compiled program Java interpreter (java)
installed takes as input the bytecode file and carries out its
instructions by translating them on the fly into instructions
that your computer can understand.
Java Program Explained
Hello is the name of the class:
class Hello{
main is the method with one parameter args and no
results:
public static void main(String[] args) {
println is a method in the standard System class:
[Link](“First Java program.");
}}
Main Method
The main method must be present in every Java
application:
public static void main(String[] args)
a)public means that the method can be called by any object
b)static means that the method is shared by all instances
c)void means that the method does not return any value
Interpreter executes an application-calling its main
method
The main method accepts a single argument – a string
array- command-line parameters.
public class SomeClass
{ Attributes / variables that define the
object’s state. Can hold numbers,
Fields characters, strings, other objects.
Usually private.
Code for constructing a
Constructors new object and initializing
its fields. Usually public.
Actions that an object
Methods can take. Can be
} public or private.
private: visible only inside this class
public: visible in other classes
public class Fraction
{
private int num, denom;
Fields
public Fraction ( )
{
The name of a
num = 0;
denom = 1; constructor is
Constructor always the same
}
as the name of
public int getNum ( ) the class.
{
return num;
}
Methods
}
Fields
Fields You name it!
private (or public) [static] [final]
Usually datatype name;
private
May be present:
means the field
May be present: is a constant
means the field is
shared by all objects
int, double, etc., or an
in the class
object: String, JButton,
FallingCube, Timer
Field
Access Modifier
– Access Permission Level from other classes
– public, protected, private
– Default/no declaration: package
Modifier Class Sub-Class Same Package All Class
private O X X X
package O X O X
protected O O O X
public O O O O
Constructors
Constructors
Constructors are like methods for creating
objects of a class. Have the same name as
the class.
Most constructors initialize the object’s fields.
Constructors may take parameters.
A class may have several constructors that
differ in the number or types of their
parameters.
Default constructor- If no other constructor.
Constructors
go = new JButton("Go");
Constructors (cont’d)
public class Fraction
{ public Fraction (int p, int q)
private int num, denom; {
num = p;
public Fraction ( ) denom = q;
{ reduce ();
num = 0; }
denom = 1; “No-args”
} public Fraction (Fraction other)
constructor
{
public Fraction (int n) num = [Link];
{ denom = [Link];
num = n; }
denom = 1; ...
Copy
} }
constructor
Constructors
Constructors of a class can call each other
using the keyword this — a good way to
avoid duplicating code:
public class Fraction ...
{ public Fraction (int p,
... int q)
{
public Fraction (int n) num = p;
{ denom = q;
this (n, 1); reduce ();
} }
... ...
Operator new
Constructors are invoked using new
Fraction f1 = new Fraction ( ); 0/1
Fraction f2 = new Fraction (5); 5/1
Fraction f3 = new Fraction (4, 6); 2/3
Fraction f4 = new Fraction (f3);
2/3
Object references
A variable holds a memory location of an
object.
Fraction
f1 = 0, 1
Fraction
f2 =
5, 1
f = f2
null references
The null value can be assigned to a
variable of any reference type
Ex:
– String middleInitial = null;
– Car c = null;
Compare objects
– if (c == null)……
Methods
Methods
Call them for a particular object:
[Link]();
But call static (“class”) methods for the whole
class, not a specific object:
y = [Link] (x);
Methods: Java Style
Method names start with lowercase letters.
Method names usually sound like verbs.
The name of a method that returns the
value of a field often starts with get:
getWidth, getX
The name of a method that sets the value
of a field often starts with set:
setLocation, setText
Method
Method Qualifier
– Access Modifier
• Access Permission Level to Method from
Other Class
• Same as that of access modifier in field
– static
• static method, class method
• Same role of Global function
• Use only the static field of correspond
class or the static method
• Can be referred by only class name
[Link];
Method
– final
• Final method
• Method which cannot be redefined in
subclass
– synchronized
• Synchronization method
• Control the threads so that only one thread
can always access the target
– native
• To use the implementation written in other
programming languages such as C language
Overloaded Methods
Methods of the same class that have the
same name but different numbers or types of
arguments are called overloaded methods.
Use overloaded methods when they perform
similar tasks:
public void move (int x, int y) { ... }
public void move (double x, double y)
{ ... }
public void move (Point p) { ... }
public Fraction add (int n) { ... }
public Fraction add (Fraction other) {
... }
Static
Static Fields
A static field (a.k.a. class field or class variable) is
shared by all objects of the class.
A static field can hold a constant shared by all
objects of the class:
A non-static field (a.k.a. instance field or instance
variable) belongs to an individual object.
Static Fields
Static fields are stored with the class code,
separately from non-static fields that describe an
individual object.
public static fields, usually global constants, are
referred to in other classes using “dot notation”:
[Link]
double area = [Link] * r * r;
setBackground([Link]);
[Link](btn, [Link]);
[Link](area);
Static Methods
Static methods can access and manipulate a
class’s static fields.
Static methods cannot access non-static
fields or call non-static methods of the class.
Static methods are called using “dot
notation”: [Link](...)
double x = [Link]();
double y = [Link] (x);
[Link]();
Instance Methods
Non-static methods are also called instance
methods.
An instance method is called for a particular
object using “dot notation”:
[Link](...);
Instance methods can access ALL fields and
call ALL methods of their class — both class
and instance fields and methods.
Static (Class) vs. Non-Static (Instance)
public class MyClass
{
public static final int statConst;
private static int statVar; public int instMethod(...)
{
private int instVar; statVar = statConst;
... inst Var = statConst;
... All OK instVar = statMethod(...);
statVar = instMethod2(...);
public static int statMethod(...) ...
{ }
statVar = statConst;
statMethod2(...); public int instMethod2(...)
OK {
instVar = ...; ...
instMethod(...); Error! }
} ...
}
Static vs. Non-Static (cont’d)
Note: main is static and therefore cannot
access non-static fields or call non-static
methods of its class:
public class Hello
{
private String message = "Hello, Error:
World"; non-static
variable
public static void main (String[ ] message is
args) used in static
{ context (main)
[Link] (message);
}
}
Static Initialization Statement
The Statement to be executed at the same time
when the system initialize the static variable in
the class
From
static { <statement> }
Static Initialization Statements
public class Test {
static{
[Link]("Static");
}
{
[Link]("Non-static block");
}
public static void main(String[] args) {
Test t = new Test();
Static
Test t2 = new Test(); Non-static block
} Non-static block
Static Initialization Statements
public class Main{
//instance variable initializer
String s = "abc"; Output:
//constructor static initializer called
public Main() { 4
[Link]("constructor called"); } instance initializer called
static int i, j=4; constructor called
//static initializer instance initializer called
static { constructor called
[Link]("static initializer called");
[Link](j); }
//instance initializer
{ [Link]("instance initializer called"); }
public static void main(String[] args) {
new Main();
new Main(); }
}
Passing Objects as Arguments
Objects are always passed as references:
the address is copied, not the object.
Fraction f1 = new Fraction (1, 2); f1: addr1
Fraction f2 = new Fraction (5, 17);
Fraction f3 = [Link] (f2); f2: addr2
public class Fraction copy
{ 5/17
...
public Fraction add (Fraction f)
{ f: addr2
Fraction sum;
... sum:
}
}
import
Full library class names include the package
name. For example:
[Link]
[Link]
import statements at the top of your program
let you refer to library classes by their short
names:
Fully-qualified
import [Link]; name
...
JButton go = new JButton("Click here");
import (cont’d)
You can import names for all the classes in
a package by using a wildcard .*:
import [Link].*; Imports all classes
import [Link].*; from awt, [Link],
import [Link].*; and swing packages
[Link] is imported automatically into all
classes; defines System, Math, Object, String,
and other commonly used classes.
Fraction- Methods
public class Fraction
{ public Fraction (int p, int q)
private int num, denom; {
num = p;
public Fraction reduce( ) denom = q;
{ // reduce
}
}
public Fraction invert(Fraction a){ public Fraction add(Fraction a,
Fraction b){
}
}
public Fraction add (Fraction a, int n)
{ ... }
}
Fraction Methods
class FractionDemo {
public class Fraction
public static void main(String args[]) {
{ int num, denom;
public Fraction (int p, int q) //Create 3 Fraction objects,
{ // initialize 2 with 4 hardcoded values
num = p; (i,j,k,l)
denom = q; // Print them on screen
} // add the two Fraction objects
and assign it to third Fraction
//invert method should verify if
numerator is zero.
}
public add ( Fraction f)… }
public Fraction invert (Fraction f)…
}
Java Arrays
Introduction
Array is a useful and powerful aggregate data
structure presence in modern programming
languages
Arrays allow easy access and manipulation to
the values/objects that they store
Arrays are indexed by a sequence of integers
Arrays
new is used to construct a new array:
new double[10]
Store 10 double type variables in an array of doubles
double[] data = new double[10];
integer Arrays
int[] a = new int[5];
Array of Object References
class Foo() { ….}
Foo[ ] myFooList = new Foo[N];
1 Foo[0]
myFooList
Foo[1]
Foo[N-1]
N-1
Arrays
fixed length
Element of specific type or references to Objects
[ ] is used to access array elements
data[4] = 29.95;
Use length attribute to get array length.
– [Link]
– (Not a method!)
Array
homogeneous data structure: each of its
members stores the same type (either
primitive or reference)
indices go from 0 to one less than the length
of the array
each array object stores a public final int
length instance variable that stores the
length of the array
we can access the value stored in this field, in
the example above, by writing [Link]
Copying Arrays
Copying an array reference yields a second
reference to the same array
double[] data = new double[10];
// fill array . . .
double[] prices = data;
Cloning Arrays
• Use clone to make true copy
double[] prices = (double[])[Link]();
Swapping Array Elements
Suppose you want to swap two elements in the
array, say entries with indices i and j.
Assuming we are dealing with an array of ints
– int temp = A[i]; // save a copy of A[i] in temp
– A [i] = A[j]; // copy the content of A[j] to A[i]
– A[j] = temp; // copy the content of temp to A[j]
Note that : A[i]= A[j] and A[j] = A[i] do not
swap content
Exercise: Reverse an array using swaps
Accessing Arrays
int[] a = new int[]{4, 2, 0, 1, 3};
[Link]( a[0] );
if (a[5] == 0) ...some statement
if the value computed for the index is less
than 0, or greater than OR EQUAL TO the
length of the array
– trying to access the member at an illegal
index causes Java to throw the
– ArrayIndexOutOfBoundsException which
contains a message showing what index
was attempted to be accessed