Java Review
COS3711 The Java Platform
Lecture 2
Based on chapter 1 Creating a Java Application
of our recommended
book
Data Types (Primitives and Reference Types)
Access Modifiers
Variables and Methods
Overview of OOP
Concept Definition Our interest
Objects a software bundle of related state and how state and behavior are represented within an object
behavior used to model the real-world the concept of data encapsulation
objects the benefits of designing your software in this manner
Classes a blueprint or prototype from which modeling the state and behavior of a real-world object
objects are created
Inheritance a mechanism for organizing and inheriting state and behavior from superclasses
structuring software deriving a class from another
Interface a contract between a class and the outside creating interfaces
world implementing interfaces
Packages a namespace for organizing classes and placing your code into packages
interfaces in a logical manner. Creating an Application Programming Interface (API)
Generics enable types to be parameters when re-using the same code with different inputs
defining classes, interfaces and methods. Eliminate casts
implementing generic algorithms
Exceptions Event which disrupts the normal flow of a handle exceptional events
program's execution
Testing and Compare programs behavior to expected Improve the confidence in the correctness of the program
Debugging behaviour
The Java Platform
a software-only platform that runs on top of other
hardware-based platforms
HelloWorld.java
It has two components: API Java
platform
• The Java Virtual Machine - runs the application Java Virtual Machine
Hardware-Based Platform
• The Java Application Programming Interface (API)
• a large collection of ready-made software components
that provide many useful capabilities
• grouped into libraries of related classes and interfaces
known as packages
Introduction
• Every Java program is a (collection of) class(es)
• Every class source code written in plain text
files ending with the .java extension and stored
in a file with name same as the class name
e.g. HelloWorld.java
• Source files are compiled into .class files using
the javac compiler e.g. javac HelloWorld.java
• The result of compilation is a file with .class
extension
e.g. HelloWorld.class
• The .class file contains bytecodes that can be
run with the java launcher tool on an instance
of the Java Virtual Machine
Creating a Java Application
• A Java application contains a method called main HelloWorld.java
package na.edu.unam.helloworld;
• Main method contains all code that must be executed /**
* @author kmufeti
• Other Java classes can be instantiated and used in Java */
public class HelloWorld {
Applications public static void main(String[] args) {
System.out.println("Hello World!");
• Java programs are executed through the Java virtual }
machine (JVM) }
• Java applications may be executed or run by typing the
command:
java ProgramName
Structure of a Java class
Every class contains:
1. comments
2. Instance variables, ((also known as attributes, class data or fields)
• defines the data associated with an object of a class to store the state of the object
• must have a type, either base type or any class type.
3. Methods
• blocks of code that can be called to perform actions.
• can accept parameters as arguments
• their behavior may depend on the object upon which they are invoked and the values of any
parameters that are passed.
• accessor - methods that returns information to the caller without changing any instance
variables
• mutator - methods that may change one or more instance variables when invoked
• constructors - methods that create objects are called
1. Comments
• Comment line /*
* COS3711 Data Structures & Algorithms
* UNAM 2023
• begins with two slashes (//) * @author mee Kauna
*/
• Continues until the end of the line
• Multiple-line comment /**swaps the integers x and y */
public static void swap(int x, int y){
int temp = x;
• Begins with /* and ends with */ x = y;
y = temp;
• Useful for debugging }
• Cannot contain another multiple-line comment
• javadoc comments – Begins with /** and ends with */
2. Instance variables
Syntax for instance variable declaration has three components
(1) access-modifier (2) type (3) identifier
e.g. public int age;
• access modifier (can be default, private, protected or public)
• type can be any primitive type or reference type
• identifier can be any valid combination of characters (use camelCase)
Syntax for instance variable declaration - Access modifiers
public protected private
• all objects may • access only • access to a
access the granted to defined member
defined aspect. subclasses of the of a class be
given class granted only to
through code within that
inheritance or in class.
the same
package.
a static variable is associated with the class as a whole,
rather than with each individual instance of that class.
access to members permitted by each modifier.
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Instance variable Identifiers
• Identifier - Sequence of letters, digits, underscores, and dollar signs
• Must begin with either a letter or underscore
• Used to name various parts of the program
• Java distinguishes between uppercase and lowercase letters
• an identifier must bot be a reserved word
• Keywords - Java reserved identifiers
Reserved Java Keywords
abstract assert boolean break byte case
catch char class const continue default
double do else enum extends false
final finally float for goto if
implements import instanceof int interface long
native new null package private protected
public return short static strictfp super
switch synchronize this throw throws transient
d
true try void volatile while
Other Variables in Java
Java programming language defines the following kinds of variables:
Instance Variables (Non- Class Variables (Static
Local Variables Parameters
Static Fields) Fields)
• objects store their • A class variable • used in a method to • declared in the
individual states in declared with the static store temporary state signature for a method
"non-static fields“ modifier • only visible to the • parameters are always
• Non-static fields • exactly one copy of methods in which they classified as "variables"
known as instance this variable in are declared; not not "fields"
variables existence, regardless of accessible from the
• their values are unique number of class rest of the class
to each instance of a objects
class • final indicates that the
variable will never
change.
Java Data Types
Java offers two main data types:
• primitive (built-in) data types, and
• reference types (defined using classes)
Each Java Data type is a set of values together with a set of operations on
those values
Java Data Types - Primitive types
Java has several base types, which are
basic ways of storing data.
These base types are also known as
primitive types in Java
An identifier variable can be declared
to hold any base type and it can later
be reassigned to hold another value of
the same type.
Primitive Data Types Ranges and Default values
Primitive Data
Size Range Default values
Types
byte 8 -128..127 0
short 16 -32,768..32,767 0
int 32 -2,147,483,648.. 2,147,483,647 0
-9,223,372,036,854,775,808..
long 64 0L
9,223,372,036,854,775,807
float 32 3.4e-0.38.. 3.4e+0.38 0.0f
double 64 1.7e-308.. 1.7e+308 0.0d
char 16 Complete Unicode Character Set '\u0000'
boolean 1 true, false false
Declaring and initializing primitive types
An identifier variable can be declared to hold any base type
it can later be reassigned to hold another value of the same type.
Consider the following statement
int x; // declares x to be an int variable
allocates memory space x to store an int value.
x can store an int value in its memory space. e.g.
x = 45;
x can later be reassigned to hold another value of the same type. e.g.
x = 92;
Java Data Types - Reference types
Every object is an instance of a class
A variable of a class type is also known as a reference variable
Objects of class types are created using the new operator
new causes the system to:
• allocate memory space of a specific type
• store specific data in that memory space, and
• return the address of the memory space.
Unlike primitive types, reference variables cannot directly store data in memory space
• They store the memory location or the address of where the actual data is stored.
Creating Java Classes
A class is the blueprint from which individual objects are created.
An object stores its state in fields (variables) and exposes its behavior
through methods (functions).
Classes thus must consist of variables and methods.
Methods operate on an object's internal state and is the primary mechanism for
object-to-object communication.
Hiding internal state and requiring all interaction to be performed through an
object's methods is known as data encapsulation.
Creating classes requires the ability to identify the state and behavior of real-
world objects
Java methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also
known as functions.
Method allow code reuse: define the code once, use it many times.
Creating methods
A method must be declared within a class.
It is defined with the name of the method, followed by
parentheses ().
Java provides some pre-defined methods, such as
System.out.println(), but you can also create your own methods
to perform certain actions:
public class Main {
Create a method inside class Main: static void myMethod() {
// code to be executed
}
}
Parameters
parameters are defined in a comma-separated list enclosed in parentheses after the name
of the method.
• A parameter consists of the parameter type and name.
• If a method has no parameters, use an empty pair of parentheses
All parameters are passed by value
Any time we pass a parameter to a method, a copy of that parameter is made for use
within the method body.
• So if we pass an int variable to a method, then that variable’s integer value is copied.
• The method can change the copy but not the original.
• If we pass an object reference as a parameter to a method, then the reference is copied as well.
public void setCount(int count) {
this.count = count;
}
Calling a method
public class Main
{
static void myMethod(String fname)
{
System.out.println(fname);
}
public static void main(String[] args)
{
myMethod(“Douglas");
myMethod(“Malakia");
myMethod(“Josephine");
}
}
Method Declaration and Usage
Methods have a specific return type that comes before the function name.
A method that returns nothing has a return type of void.
Methods also need to specify their arguments’ types.
Calling a function looks the same as in C#
public static String greet(String name) {
return "Hello, " + name;
}
// elsewhere...
System.out.println(greet("Josephine"));
Creating full class with methods
all code in a Java class name same
program belongs as filename.java
in a class
curly brace
anyone can indicates beginning
use this class of class body
any instance
can access this
class method, no method returns
attribute method name
need for instance nothing
curly brace
indicates beginning
of method body
any instance
can access this end of statement
method
curly brace indicates
end of method body parameter to
method main
curly brace indicates argument to
end of class body method println
located in class method println
System
Declaring and creating an object
The following statement declares a variable name of type String
String name; //line 1
The following assignment statement creates a name object (of type String)
name = new String(“Java Programming”);
The statement has the following effect:
2500
name 2500 v Java Programming
Using Objects
Object reference variable can be used to access the members of the class
access is performed with the dot (“.”) operator.
System.out.println("Hello World");
calls a method associated with an object by using the reference variable
name, followed by the dot operator and then the method name and its
parameters.
Class constructors
A constructor:
• a method that shares the same name as
its class
• Used to specify how objects of that
class should be created
• can be overloaded
• new operator returns a reference to the
newly created instance
• returned reference is typically assigned
to a variable for further use. Counter count1 = new Counter();
Counter count2 = new Counter(10);
This keyword
Within the body of a method in Java, the keyword this is automatically
defined as a reference to the instance upon which the method was
invoked. There are three common uses:
1. To store the reference in a variable, or send it as a parameter to
another method that expects an instance of that type as an
argument.
2. To differentiate between an instance variable and a local variable
with the same name.
3. To allow one constructor body to invoke another constructor
body.