2. Concepts of OOP
The Introduction starts with giving a short definition of the
terms used in object oriented programming. This is
followed by a brief history and some good properties of
Java.
The chapter then introduces the concept of Java
programming, by explaining the various steps used to
write a simple Java class. The concept of a class is
described in detail.
3. Objects & Classes
To distinguish between an object and a class one may use the
analogy of a mobile phone. When we speak of a class we speak of
a type of object for example a class of a mobile, maybe a Nokia
370.
A Nokia 370 is not a distinct object – it has no actual colour or
number. On the other hand when we speak of my mobile of type
Nokia 370 we are specifying a distinct object. It‘s colour is black
and the number is 7942816. This is an object - a specific mobile.
You can have many objects of the same class and each object we
can call an instance of that class. Tom, Jerry, and Mary can each
have a Nokia 370; each an instance of a Nokia 370.
The designer didn't design my mobile but designed the Nokia 370
of which my mobile is an instance. So in programming we design a
class and then create new instances of that class.
4. Abstraction
The essence of abstraction is to extract essential properties while
omitting inessential details.
To keep to our analogy, an abstraction can be considered as a
mobile without any details of how it functions.
All that I am concerned, is that my mobile behaves exactly like
any other mobile of its type, and knowing how to use one
enables me to use any mobile of that type since all I am
concerned is that it provide all facilities offered by a my mobile.
5. Information Hiding
Information hiding is the principle of segregation of design
decisions in a computer program that are most likely to change,
thus protecting other parts of the program from extensive
modification if the design decision is changed.
The protection involves providing a stable interface which
protects the remainder of the program from the implementation
(the details that are most likely to change).
The user of the mobile is not concerned with the inner workings
of the mobile, but only to how to switch on the mobile and the
functions to use it.
6. Encapsulation
The concept of encapsulation refers to
building a capsule, in this case a
conceptual barrier, around some
collection of things.
All functions of the mobile are
encapsulated within the case.
This makes the object much more easy
to handle as identical functions are
grouped together in a single mobile.
7. Methods & Data Values
An object is composed of data values and methods.
Methods are ways to use an object and they normally receive
or return a value to or from the object. In our mobile analogy, a
subscriber uses the mobile by choosing the function and pass to
it, or retrieves from it, the required data
Data values are values contained within the object. They are the
properties of that object. These can be instance data values
which belong to only one particular instance, or a class data
value belonging to all objects of the same class.
Methods act on these data values. Methods which access data
values are called accessor methods whilst those which change it
are called mutator methods, just like the functions of your
mobile.
8. Java’s Past and Present
The Java language was originally created to solve the
problems surrounding personal digital assistants (PDAs) and
consumer electronic products, such as microwaves and toaster
ovens. The language had to be robust, small, and portable.
However, the Java team discovered that Java‘s design made it
ideal for another purpose: programming on the Internet. In
1993, the World Wide Web was gaining popularity, with its
myriad platforms and operating systems, and it desperately
needed a platform-independent language—so Java found a
new home.
9. Java Is Platform-Independent
The Java language was designed specifically to be platform-independent.
This means that programs written in Java can be compiled once and run on
any machine that supports Java. So, what exactly does platform-
independence mean, and how does it differ from what was available
before Java?
Traditional compiled programming languages are compiled to machine-
level binary code that is, of course, specific to the machine or platform on
which it is compiled. The advantage is that the compiled binary runs quickly
because it is running in the machine‘s native language. The disadvantage is
that a program written in a traditional language has to be recompiled to
binary code for each different hardware platform before it can be run on
that machine.
On the other hand, traditional interpreted programming languages are
machine-neutral and can be run on various platforms, they generally run
much slower than compiled applications.
10. The Java Virtual Machine (JVM)
Java has incorporated the best of both worlds. The Java team
created a platform-specific layer, called the Java Virtual
Machine (Java VM), which interfaces between the hardware and
the Java program. When you install a Java-capable browser on
your computer, for example, a copy of the Java interpreter is
also installed, which is what enables your browser to execute
Java applets and your system to run standalone Java programs.
Java interpreter and Java runtime are alternative terms for the
Java Virtual Machine (VM).
The Java VM presents the same interface to any applets that
attempt to run on the system, so to applets, all machines look the
same. The applet itself is compiled into a form of interpretable
code called Java bytecodes. This special form of code can be
run on any platform that has the Java VM installed.
11. The Bytecode
Bytecodes are a set of instructions that are similar to machine code but are
not processor-specific.
They are interpreted by the Java VM. Sun‘s trademark phrase ―write once,
run anywhere‖ is the promise that is fulfilled by Java.
This, above all other features of the language, is what makes it so essential
for interactive
Web programming. It makes code much safer as it interacts only with the
JVM.
12. Java Is Object-Oriented
Java is a real object-oriented language, which enables you to
create flexible, modular programs.
It includes a set of class libraries that provide basic data
types, system input and output capabilities, and other utility
functions.
It also provides networking, common Internet protocol, image
handling, and user-interface toolkit functions.
Java‘s object classes provide a rich set of functionality, and
they can be extended and modified to create new classes
specific to your programming needs.
13. Java Is Easy to Learn
Among the original design goals of the Java team members
was to create a language that was small and robust. Because
they started from scratch, they were able to avoid some of the
pitfalls of other more complex languages. By eliminating things
such as pointers, pointer arithmetic, and the need to manage
memory explicitly, the Java development team made Java one
of the easiest languages to learn. However, you can still do
anything in Java that you can do in traditional languages. If
you have previously used a high-level object-oriented
programming language, such as C++, much of Java will look
familiar to you.
14. My First Java Program
import javax.swing.*; import required package
/*
My First Java Program: comment
Displaying a Window
*/ filename must be saved as MyFirstProgram.java
public class MyFirstProgram { class definition starts here
main method starts
public static void main (String[ ] args) {
indent JFrame tieqa; declare object of given class
tieqa = new JFrame( ); create a new object
block tieqa.setSize(300, 200);
call methods of
tieqa.setTitle(―Hello Cutajar‖); class JFrame
tieqa.setVisible(true);
} main method ends
use methods
} class definition ends on object
15. /* Comments */
/* This is a multi-line comment
and ends with */
// This is a single line comment and ends with a return
Everything enclosed within (/*) and (*/) is a comment and is
ignored by the compiler.
Another way to write a single line comment is by starting the
line with a double slash (//), everything until the end of line is
ignored.
Special comments enclosed in (/**) and (*/) are used in
documentation. These are called JavaDoc comments
16. The Concept of a Class
The example is a class which comprises:
one or more import statements to import libraries (packages)
containing classes of objects already defined
a class
a method called main() having some parameters
a method has a header conveying the method‘s name (main)
a method
a block
a block
a block {enclosed in braces} comprises:
a set of declarations (what you need)
a set of statements (what to do)
each import, declaration or statement end with a semicolon (;)
17. Object Declaration
When declaring an object we are actually giving a name to
an object of that class.
class must be already defined
JFrame is
defined in JFrame tieqa;
javax.swing
object names
start with
lowercase
class names
start with
uppercase tieqa null
18. Object Creation
When we create an object
Example: tieqa = new JFrame();
we are effectively reserving memory space for an object. This
is when the object really comes in existence.
tieqa = new JFrame( );
calling the
creator of
JFrame
tieqa
JFrame
19. Methods - Calling Methods
In Java we call methods on objects. So we use the name of the
object and the method we want to use of that object
separated by a dot. Note that since we call the method of an
object we are only effecting that particular instance. ( We will
see later some exceptions on static classes).
the
dot
name of
parameters to send to method
object
tieqa.setVisible (true);
name of account.deposit( 200.0 );
method student.setName(“john”);
myMobile.addContact(“maria”);
20. Method Declaration
When declaring a class the following statements must be
included. This is the main method of which one and only one is
needed for a program to execute.
public static void main ( String args[ ] ) {
access scope return method
modifier parameters block start
modifier type name
optional
public void deposit ( float amount) {
balance = balance + amount;
}
21. Naming
In the example class illustrates several names
invented by the programmer to identify
classes, objects and variables in general.
Such names are also called identifiers
These identifiers :
cannot be Java keywords:
cannot contain punctuation marks or spaces
must not start with a numeral.
My Window
1stVariable
case
22. Naming Conventions
It is a common convention to name objects starting with a lower
case letters tieqa
We use an uppercase letter to separate words in the identifier.
myFirstWindow
On the other hand the name of the classes normally start with
an Uppercase letter. JFrame
Java is case-sensitive, meaning that lowercase letters and
upper-case letters are totally different letters. JPanel tieqa;
Number and number are different JFrame tieqa;
You cannot name two different things with the same name:
23. JAVA Components
This section introduces the building blocks of a program.
It introduces the concepts of primitive and non-primitive
(object) variables, their properties and their behaviour.
The operations among these variables are analysed
here, together with some new related pre-defined
classes.
The concept of constants is also discussed
24. Variables
A variable is an entities that can hold a value.
Before it can be used it must first be declared.
A variable has four properties:
An Address,
A memory location to store the value,
whose storage capacity depends on
the type of data to be stored,
The type of data stored in the
memory location, and
The name used to refer to the
memory location. (following the same
naming rules already discussed).
25. Primitive Data Types
byte
boolean
short
Primitive char Integers
Data Types
int
Numeric long
float
Reals
double
26. Sizes and Ranges of Variables
Declare the type of a
variable only once, as long
as its scope hasn't ended
Variables can be declared
anywhere in the program
int i, j, k;
float numberOne,
numberTwo;
long bigInteger;
double bigNumber;
int count = 10, height = 34;
numberOne = 3.45F;
i = 45;
27. Assignment Operators
The assignment operator in Java is denoted by a single equals sign:
The variable on the left of the equals sign takes the resulting value
of the evaluation of the expression on the right.
The syntax is: <variable name or identifier> = <expression> ;
Normally on the left of the expression is the name of a variable
and on the right evaluates to a value which is assigned to the
variable. The left hand is called l-value.
In Java the overall result of the RHS expression is returned, allowing
the LHS to be assigned too as follows:
29. Mixed Types Expressions
When terms of an expression are of different types, the
processor ‗coerces‘ values to a consistent type.
Coercion may cause a short to become long. (promotion) or a
long into a short (demotion).
If you wish to override coercion you may include a cast to
specify the precise promotion or demotion required.
This expression is called a mixed expression:
float x;
int y;
x*y
30. Automatic Promotion
The data types of the operands in mixed expressions are
converted, based on the promotion rules.
The promotion rules ensure that the data type of the
expression will be the same as the data type of an operand
whose type has the highest precision.
31. Explicit Type Casting
Instead of relying on the promotion rules, we can make an
explicit type cast by prefixing the operand with the data type
using the following syntax: (<data type> ) <expression>
Convert x and result to float
(float) x / 3
(int) (x / y * 3.0) Convert result to int
32. Implicit Type Casting
Consider the following expression:
double x = 3 + 5;
The result of 3 + 5 is of type int. However, since the variable
x is double, the value 8 (type int) is promoted to 8.0 (type
double) before being assigned to x.
int x = 3.5;
Demotion is not allowed higher precision
33. boolean
Another primitive data types in Java is boolean which has
only two possible values: true or false.
Use this data type for simple flags that track true/false
conditions.
This data type represents one bit of information, but its "size"
isn't something that's precisely defined.
boolean found = false;
34. Enumerated Data Types
An enum type is a kind of class definition.
The possible enum values are listed in the curly braces,
separated by commas.
By convention the value names are in upper case as are
actually constants.
public enum Shape { RECTANGLE, CIRCLE, LINE }
35. chars
The char data type is a single 16-bit Unicode
character.
Note the difference The code of „1‟ is 49 and not 1
between 1 and „1‟
Note that the single apostrophes delimit a
character. The double quotes (―) delimit a string
of characters.
Addition (+) between characters and strings
produces a concatenation and is stored in a
string
String s = „A‟ + „B‟
36. Character order
Characters in java have an ordinal value, thus there is an order
between them:
This means that you can even compare characters between
them.
37. Strings
A string constant consists of a sequence of characters separated by double
quotes. There are close to 50 methods defined in the String class.
String name;
name = new String(“Johnny Java”); name null
name J o h n n y J a v a
pointer to where index starts
string starts at 0
Note that a String is not a primitive data type but a class, and likewise
behaves like one. We say that Strings are immutable (cannot change value).
Notice the difference between primitive data types like strings. In primitive
data type the contents of the variable is the value, while in referenced data
type the contents is a pointer (address) of the location where the object
starts.
38. The String Class
A very commonly used class of the java.lang package is the
Sting class. Note that the java.lang package doesn't need to
be imported as it is imported directly by default by java.
There are various methods defined in the String class, to
mention a few, for an object str of class String:
str.substring(i,j) will return a new string by extracting characters of str
from position i to j-1 where 0 <= i < length of str, 0 < j <= length
of str, and i <=j.
str.length() will return the number of characters in str.
str.indexOf(substr) will return the first position substr occurs in str.
39. Primitive Data Types
Numerical data , boolean and chars are called primitive data types.
For Primitive Data Types: int firstNumber;
int secondNumber;
1. Allocate memory for variables.
firstNumber firstNumber = 234;
secondNumber = 87;
secondNumber
firstNumber = 187;
2. Values are placed in the memory locations of the variable
firstNumber 234 secondNumber 87
3. If one of them say firstNumber gets reassigned the new value will overwrite the
old one. The value of 234 is overwritten by 187
firstNumber 187
40. Referenced Data Types
Objects (including Strings) are called reference data types, because their
contents is an addresses that refers to a memory locations where the objects
are actually stored.
Customer customer, client;
For Objects: customer = new Customer(“John”);
1. Allocate memory for variables. customer = new Customer(“Mary”);
client = customer;
customer
client M a r y
2. An object is created and its address is stored in the variable to point at it.
customer J o h n customer J o h n
3.The reference to another object overwrites the reference in customer.
4. The reference in customer is assigned to client. So both point at the same object
customer M a r y
client
41. Wrapper Classes
A wrapper is a class that contains data or an
object of a specific type and has the ability of Primitive Wrapper
performing special operations on the data or boolean Boolean
object. byte Byte
Most common wrapper classes are for the char Character
primitives. double Double
Note that since wrapper classes are classes in all float Float
effects, by convention they start with uppercase. int Integer
Reasons for wrapper around the primitives: long Long
Converting from character strings to numbers short Short
and then to other primitive data types. void Void
A way to store primitives in an object.
A way of passing primitive data types by
reference.
Double myDouble = new Double("10.5");
42. Autoboxing
Autoboxing, introduced in Java 5, is the automatic conversion
the Java compiler makes between the primitive (basic) types
and their corresponding object wrapper classes (eg, int and
Integer, double and Double, etc).
The underlying code that is generated is the same, but
autoboxing provides a sugar coating that avoids the tedious
and hard-to-read casting typically required by Java
Collections, which can not be used with primitive
Double myDouble = 10.5;
43. Converting Back to Primitives
Here are some examples to convert back to basic types
Wrapper class Method Example (for converting back to primitives)
Integer parseInt Integer.parseInt(“25”) gives 25
Integer.parseInt(“25.3”) gives an error
Long parseLong Long.parseLong(“25”) gives 25L
Long.parseLong(“25.3”) gives an error
Float parseFloat Float.parseFloat(“25.3”) gives 25.3F
Float.parseFloat(“abc”) gives an error
Double parseDouble Double.parseDouble(“25”) gives 25.0
Double.parseDouble(“abc”) gives an error
44. Arithmetic Operators
We have already used and seen some of these as they are the
basic arithmetic operations whose function is intuitive.
45. Increment and Decrement
Java has two special operators for incrementing or
decrementing a variable by one.
These may either be prefix (before the variable) or postfix
(after the variable).
if you include i++ as a term of a larger expression, the original
value of i is used and afterwards incremented or decremented in
case of i--
if you include ++i or --i as a term of a larger expression, the new
value of i is used.
46. Comparison
Each comparison using one of the six infix operators below will
produce a boolean result of true or false.
Evaluation is from left to right and is short circuit.
Short circuit means that if the operation is an ―and‖ and the first
clause evaluates to false, the rest of the clauses are not
evaluated.
Similarly if the operation is an ―or‖ and the first clause is true
the rest are omitted.
47. Chaining Logical Conditions
NOT The logical not is a prefix operator.
AND & OR
The truth tables of the && (and) and the ||
(or) operations shown below indicate that the
two operations are commutative. For example
(i && j) produces the same result as (j && i)
int i = 10, j = 28;
boolean valid;
valid = ((i < 12) && (j <15));
48. Conditional Assignment Operator
The conditional assignment (ternary) operator provides an in-
line if/then/else.
If the condition is true, the expression after the ―?‖ is evaluated and
returned as a result of the statement.
If the condition is false, the expression after the ―:‖ is evaluated and
returned as a result of the statement.
49. Bitwise Operators
Bitwise operators are used only with operands of integral
types
51. Precedence and Associativity
Precedence of Operators
Java treats operators with different
importance, known as precedence.
There are in all 15 levels of
precedence. In general, the unary
operators have a higher precedence
over the binary operators and
parentheses can always be used to
improve clarity in the expression.
Associativity of Operators
For two operators of equal precedence
a second rule, ―associativity‖ applies.
Associativity is either ―left to right‖ (left
operator first) or ―right to left‖ (right
operator first):
52. Constants
We can change the value of a variable. If we want the value
to remain the same, we use a constant.
To specify the exact type of literal constants, one can use the
L,F and D or l,f and d to define the precision for numerals.
We then use the reserved keyword final to lock it.
final double PI = 3.14159D; As a convention we
final int MONTH_IN_YEAR = 12; use uppercase letters
final short FARADAY_CONSTANT = 23060; separated by
underscores for
constants
53. The Math Class
The Math class in the Method Description
java.lang package abs(a) Absolute value of a
contains class methods for exp(a) Natural number e raised to the power of a.
commonly used log(a) Natural logarithm (base e) of a.
floor(a) The largest whole number less than or equal to a.
mathematical functions.
max(a,b) The larger of a and b.
Most methods of the Math min(a,b) The smaller of a and b
class are static and pow(a,b) The number a raised to the power of b.
therefore there is no need sqrt(a) The square root of a.
sin(a) The sine of a. (Note: all trigonometric functions are
to instantiate any new computed in radians) Similarly cos and tan
object of the Math class random() Returns a double value with a positive sign, greater
before using it. than or equal to 0.0 and less than 1.0.
round(a) Returns the closest integer value, if a is double it
Most Math class methods returns long, if float it returns int
generate a double type, so toRadians(a) Converts the value of a in degrees to radians
pa attention to precision
errors //Generate a random number between 1 and 100
int r = (int)Math.round(1+Math.random()*99);
54. Op Summary
Here is a summary of the
operators used in Java.
B.E.D.M.A.S
In most simple cases it easier
to remember the precedence
of operators using the slightly
modified BEDMAS (Brackets
Exponent Division
Multiplcation Addition and
Subtraction). As a general
rule, instead of relying on
memory, in case of doubt, use
the brackets to make the
precedence you desire.
55. Example
public class Matematika{
public static int random(int startRange, int endRange){
int answer = (int) (startRange+Math.random()*(endRange-1));
return answer;
}
public static int power(int base, int exponent){
int answer = (int)Math.round(Math.exp(Math.log((double)base)*exponent));
return answer;
}
public static boolean isEven(int n){
return (n%2) == 0;
}
public static double sin(double degrees){
double radians = degrees*2*Math.PI/360D;
double answer = Math.sin(radians);
return answer;
}
}
56. Example main program and Output
public class UseMatematika{
public static void main (String args []){
int number1 = 1;
int number2 = 6;
int number3 = 2;
int dice = Matematika.random(number1,number2);
System.out.println("The first roll of the die gave: "+dice);
double result = Matematika.power(number3, number2);
System.out.println(number3+" to the power of "+number2+" = "+result);
System.out.println("Sine of 30 degrees is: "+Matematika.sin(30D));
System.out.println(number1+" is even ? "+Matematika.isEven(number1));
}
}
57. Programming Elements
In this section we start constructing our own classes.
First we discuss the standard input and standard output
which we need throughout the course to make our
programs interactive.
Secondly we deal with how classes are defined. Various
aspects of the data and methods will be described,
among which the most important is the constructor.
58. The Standard Input – The Keyboard
The technique of using System.in to input data is called
standard input. We can only input a single byte using System.in
directly, so to input primitive data values, we use the Scanner
class. Method Example
import java.util.*; nextByte( ) byte b=kb.nextByte( );
… nextDouble( ) double d=kb.nextDouble( );
Scanner kb;
kb = new Scanner(System.in); nextFloat( ) float f=kb.nextFloat( );
int num = kb.nextInt();
nextInt( ) int i=kb.nextInt( );
nextLong( ) long l=kb.nextLong( );
nextShort( ) short s=kb.nextShort( );
next() String str=kb.next();
useDelimiter(String) kb.useDelimiter(“n”);
59. The Standard Output – The Monitor
Using System.out, we can output multiple lines of text to the
standard output window.
We use the print method to output a value to the standard
output window. The print method will continue printing from the
end of the currently displayed output.
We use println instead of print to skip a line.
int x = 123, y = x + x;
System.out.println(" Hi John”);
System.out.print( " x = “ );
System.out.println( x );
System.out.print( " x + x = “ );
System.out.print( y );
System.out.print(“n”);
System.out.println( " THE END“ );
60. Defining a New Class
Learning how to define our own classes is the first step toward
mastering the skills necessary in building large programs.
Classes we define ourselves are called programmer-defined
classes. imports
comments
public class { class Name
Data Members
(fields)
Member
Methods
}
61. Class Example
imports
import java.util.*;
/**
* Account Class comments
*/
public class Account{ class Name
private String name;
private String idCard; Data Members
private float balance; (fields)
public Account(String n, String id, float b){
name =n; special method (The
idCard = id; Constructor ) which
balance = b; builds the object on
} instantiation
public void deposit(float amount){
balance += amount;
Member
} .........
Methods
}
62. Organizing Classes into a Package
For a class A to use class B, their bytecode files must be
located in the same directory. This is not practical if we want to
reuse programmer-defined classes in many different programs
The correct way to reuse programmer-defined classes from
many different programs is to place reusable classes in a
package.
A package is a Java class library.
import PackageA.*;
public class UsePackage{
public static void main (String args[]){
MyFrame newFrame = new MyFrame();
newFrame.setVisible(true);
}
}
63. Compiling and CLASSPATH
CLASSPATH
Specifying where to search for additional libraries in Windows is easily
done by setting the environment variable CLASSPATH, which Java uses
to see where it should find Java programs and libraries.
BankManager.java Account.java
Compilation
into bytecode
BankManager.class + Account.class
to JVM
64. Parameters
An argument or actual parameter is a value we pass to a
method.
A formal parameter is a placeholder in the called method to
hold the value of the passed argument.
An actual parameter is the actual value passed by the caller
program
actual parameter formal parameter
public void deposit(float amount){
a1234.deposit(500); balance += amount;
}
in
calling method Account
65. Matching Actual and Formal Parameters
The number of arguments and the number of parameters must
be equal
Formal and actual parameters are paired left to right, and the
names of the formal and actual parameters are by no means
important for matching.
Each matched pair must be assignment-compatible (e.g. you
cannot pass a double argument to a int parameter)
When we are passing primitive data values, the parameter
passing is by value, so the receiving side cannot alter the
values for the passing side.
When more than one parameter is passed, they are separated
by a comma (,)
66. Pass-By-Value (by Copy)
The actual parameter (or argument expression) is fully evaluated and the
resulting value is copied into a location being used to hold the formal
parameter's value during method execution. That location is typically a
chunk of memory on the runtime stack for the application (which is how Java
handles it),
float x = 25.5F public float add(float a, int b){
Item.add(x, 25); return a+b; in
} object
in main x 25.5 25.5 a
memory space
memory space of of object
25 25 b
main
no name matched
literal constant by position
67. Pass-By-Reference
As we can pass int and double values, we can also pass an
object to a method. When we pass an object, we are actually
passing the reference (address) of an object. This means a
duplicate of an object is NOT created in the called method, so
object parameters are passed by reference.
public void add(Student a){
Student s = new Student(); a.getName();
klassi.add(s); }
a
s
Student
memory space
of main
68. Note on Primitive Parameter Passing
Primitive data arguments are passed to a method by using the pass-by-
value scheme.
Arguments are matched to the parameters from left to right. The data type
of an argument must be assignment-compatible with the data type of the
matching parameter.
The number of arguments in the method call must match the number of
parameters in the method definition.
Parameters and arguments need not have to have the same name.
Local copies of values passed by reference as parameters, which are
distinct from arguments, are created even if the parameters and arguments
share the same name.
Parameters are input to a method, and they are local to the method.
Changes made to the parameters will not affect the value of corresponding
arguments
69. Access Modifiers
The access modifiers public and private designate the accessibility of data
members and methods.
If a class component (data member or method) is declared private, client
classes cannot access it.
If a class component is declared public, client classes can access it.
Internal details of a class are declared private and hidden from the clients.
This is information hiding.
If none of this is declared, the method or data member becomes package
friendly and can be accessed only from classes in the same package.
… class Service {
Service obj = new Service(); public int memberOne;
obj.memberOne = 10; private int memberTwo;
obj.memberTwo = 20; public void doOne() { … }
obj.doOne(); private void doTwo() { … }
obj.doTwo(); }
70. Guideline for Access Modifiers
Declare the class and instance variables private.
Declare the class and instance methods private
if they are used only by the other methods in the Class Diagram
same class.
Service
Declare the class constants public if you want to
make their values directly readable by the client +memberOne
-memberTwo
programs. If the class constants are used for
internal purposes only, then declare them +doOne()
-doTwo()
private.
Another access modifier is protected. We will private gets (-)
see this one after treating inheritance, as it is public gets (+)
visible by subclasses which inherit the class.
71. Static or Dynamic
Instance methods or variables are associated with an object
and methods use the instance variables of that object. This is
the default.
Static methods use no instance variables of any object of the
class they are defined in.
If you define a method to be static, you will be given a rude
message by the compiler if you try to access any instance
variables. You can access static variables, but except for
constants, this is unusual. Static methods typically take all their
data from parameters and compute something from those
parameters, with no reference to variables.
72. Typical Static Methods
Static methods typically do some kind of generic calculation.
A good example of this are the many utility methods in the
predefined Math class.
In any program there is only one version of a static method or
variable whilst in dynamic ones there is a new version every
instance created. Thus on static methods there is no need to call
the new statement in the client class as in dynamic classes.
public class Maths{
...
double result = Maths.cube(3);
public static double cube(int x) {
return (x*x*x);
}
no need to create a new object but ...
use the class directly since method
is static
73. Class Variables and Constants
Class Constants
provide a meaningful description of what the values stand for:
number = UNDEFINED; is more meaningful than number = -1;
provides easier program maintenance. We only need to change the
value in the constant declaration instead of locating all occurrences of
the same value in the program code. caps for constants
private static final int MAX_NUMBER=6;
Class Variables
Class variables are there to keep a overall copy of a value shared
among all objects of the same class, say the total number of objects
created, or the sum of money gained from all objects of a vending
machine. lower for variables
private static int minimumBalance;
74. Class Example – Complex Number
We are used to real numbers, but when we
get to the square root of a negative number I
we go in another dimension called the
imaginary numbers. Simply said we denote
sqrt(-1) = i. Thus sqrt(-9) becomes 3i. R
A complex number consists of two parts a
real part and an imaginary part. To keep
things simple we shall represent these as
integers.
Suppose we want to create a new data type
in the form of a class to represent complex
numbers.
75. The Data Members
First of all we need to define the data required for the
real
class, namely two integers, one for the real part and
another for the imaginary part. img
It is good practice to declare these as private, so that
they are not directly accessible from outside the object. member
methods
Methods on the other hand are declared as public so
that the users of this class can communicate with them.
So we begin by declaring the two required fields
Since only methods within the object have access to private int real;
these, any bug within their value can be attributed only private int img;
to the member methods.
76. The Constructor
The constructor is a special member method which initialises an
object when it is created.
We limit, for the time being to set all fields to zero.
The constructor has always the same name as the class and has
no return type. Normally be implement this method as the first
method in the class.
If the constructor is not implemented specifically by the
programmer, will be implemented by Java, resetting all data
members. – The default Constructor
public Complex(){
real = 0;
img = 0;
}
77. The Member Methods
These are methods that communicate with the external
environment and act upon the data members of the object.
Note that the constructor does not have a return type. This is
the only method not to have a return type.
Nearly all classes have setter (mutator) and getter (accessor)
methods to set the values of their private data members.
Setter (mutator) methods Getter (accessor) methods
public void setReal(int r){ public void getImaginary(){
real = r; return img;
} } Generic methods
public void setValue(int r, int i){
public void setImaginary(){ public int getReal(){ real = r;
img = i; return real; img = i;
} } }
78. Implementation
/**
* Class to represent a complex number
/** */
* Main Class for complex numbers public class Complex
*/ {
// The Real Part of the Complex Number
public class Roots{ private int real;
// The Imaginary Part
public static void main (String args[]){
private int img;
// Declare and instantiate
Complex number1; // The Constructor (Initialiser)
1 public Complex(){ 1
number1 = new Complex(); real = 0;
// Declare and instantiate again img = 0;
1 }
Complex number2 = new Complex();
// Set their value // Set the value of the complex number
number1.setValue(2,4); public void setValue(int r, int i){ 2
2 real = r;
number2.setValue(5,3); img = i;
// Display the two numbers }
System.out.println("Number 1 = " + // Get the real value
3
number1.getReal() + " + " + public int getReal(){ 3
number1.getImaginary()+"i"); return real;
}
System.out.println("Number 2 = " +
number2.getReal() + " + " +
4 // Get the imaginary part
number2.getImaginary()+"i"); 4
public int getImaginary(){
} return img;
} }
}
79. Local Variables
Local variables are declared within a method declaration and
used for temporary services, such as storing intermediate
computation results.
Global Variables are declared outside all methods and can
be seen anywhere within the class.
It is good practice to use local variables as much as possible.
public double convert(int num) {
double result;
result = Math.sqrt(num * num);
return result;
} local variable
80. Locals, Parameters & Data Members
An identifier appearing inside a method class CD {
can be a local variable, a parameter, or a private int n; 1
private String artist; 2
data member.
The rules are: 3 4
public CD(String n1, int n){
If there‘s a matching local variable
declaration or a parameter, then the String ident; 5
identifier refers to the local variable or the
parameter. 2 3
artist = n1;
Otherwise, if there‘s a matching data 4
1 this.n = n;
member declaration, then the identifier
refers to the data member. 5
ident = artist.substring(0,2)
Otherwise, it is an error because there‘s no
matching declaration. }
...
Local variables and parameters cannot have
}
the same name.
81. “this” Keyword
If a parameter or local variable
have the same name as a data
member, they hide the global
variable. public Circle(){
this(0D);
Thus a reference to that name }
will involve only the local
variable or parameter.
To overcome this, the keyword :Student
―this‖ is used to refer to the
global variable. this
―this‖ alone refers to the
constructor of the class.
82. Method Overloading
The Java programming language supports overloading methods, and Java
can distinguish between methods with different method signatures.
This means that methods within a class can have the same name if they have
different parameter lists.
Overloaded methods are differentiated by the number or the type of the
arguments passed to the method.
You cannot declare more than one method with the same name and the
same number and type of arguments, because the compiler cannot tell them
apart.
The compiler does not consider return type when differentiating methods, so
you cannot declare two methods with the same signature even if they have
a different return type.
83. Overloading Example
In this code sample, draw(String
s) and draw(int i) are distinct public class DataArtist {
and unique methods because ...
public void draw(String s) {
they require different argument ...
types. }
public void draw(int i) {
Note that a method with a ...
}
signature of: public void draw(double f) {
public int draw(int i){ ...
}
is not permitted because it public void draw(int i, double f) {
...
distinguishes itself from another }
method only on the return type }
84. Constructor Overloading
The constructor of the class can
be overloaded as all other 1
Circle circle1 = new Circle(3.5d);
methods, and it is normal Circle circle2 = new Circle(); 2
practice to provide more than
public class Circle{
one constructor method. private double radius;
...
this can also be used to call a public Circle(){ 2
different overloaded radius = 0;
}
constructor of the same object..
public Circle(double r){ 1
Pay Attention: The call to this in radius = r;
this case must be the first }
}
statement in the constructor.
85. Overloading Complex Constructor
Now that we have other tools at hand we can consider some
modifications to the Complex Numbers class implementation.
First we use the conditional assignment to display properly the
numbers in case the imaginary part is negative and we
provide an additional constructor to initialise a complex
number to a given value.
public class Complex{
...
... public Complex(int r, int i){
Complex number1; real = r;
number1 = new Complex(3,5); img = i;
... }
System.out.println("Number 1 = " + ...
number1.getReal() + } Overloaded
((number1.getImaginary()>0)?"+":"") + constructor to set
number1.getImaginary()+"i");
values too
86. The toString() Method
The toString() returns a string representation of the object.
In general, the toString() method returns a string that "textually represents" this
object. The result should be a concise but informative representation that is easy
for a person to read.
It is recommended that public class Complex{
all subclasses override ...
// Overiding the default toString
this method. public String toString(){
So for our Complex return(real+((img>0)?"+":"")+img+"i");
}
number class the ... ...
toString() method would } Complex number1;
look aside. number1 = new Complex(3,5);
This method is the ...
System.out.println("Number 1 = "+number1);
method called when you
try to print the object Solution is now much more
directly. elegant than previous slide
87. Text Formatting
The formatter class is used to present a formatted output.
Instead of using the Formatter class on its own it is much more
convenient to use it a a method in the Printstream (System.out)
or in the String classes.
System.out.printf("%6d", 498); is equivalent to:
Formatter fmt = new Formatter(System.out);
fmt.format("%6d", 498);
int n1=34, n2=9;
int n3=n1+n2;
System.out.printf("%3d + %3d = %5d", n1 , n2 , n3);
88. Formatting Options
Integers: % <field width> d
Real Numbers : % <field width> . <decimal places> f
When the string Strings: %s
needs to be Hex: %x or %X These are just
formatted without Octal: %o
some of the
displaying it, the control strings
Character %c possible in the
String class provides Scientific %e or %E printf
a static method
format which is
similar to the above. „-‟: left justified
„+‟: always include a sign
Flags: The optional „(„: negative number in brackets
flags is a set of
characters that
modify the output always show
A better toString for Complex
sign
format.
public String toString(){
return(String.format("%d %+di",real,img));
}
89. Returning Objects
As we can return a primitive data value from a method, we can return an
object from a method too.
We return an object from a method, we are actually returning a reference
(or an address) of an object.
This means we are not returning a copy of an object, but only the reference
of this object public class Roots
{
in main public static void main (String args[]){
class Complex n1 = new Complex(5,-5);
Complex n2 = new Complex(2,-3);
result is Complex n3 = n1.add(n2);
System.out.println("Number 1 = "+n1);
assigned to n3
System.out.println("Number 2 = "+n2);
System.out.printf("(%s) + (%s) = %s",n1,n2,n3);
}
}
90. Implementation of add in Complex
returns a
pointer to a class
Complex
public Complex add( Complex num){
result
= method in class
+ this
Complex
return result
} public Complex add(Complex num){
Complex result = new Complex();
result.real = num.real+this.real;
n3
result.img = num.img+this.img;
return result;
}
91. Program Control Structures
Here we first consider the selection constructs in java,
namely the if and the switch statements, followed by the
three iterative constructs, namely, the for loop, while loop
and the do while loop.
We also investigate the alternative recursive procedure
to obtain the same things in a more elegant, sometimes
more inefficient way.
92. The Student
public class Student This example will be used
{ throughout the rest of the
private String name; chapters so pay attention
private int mark;
Class public Student(){
name = "";
Student
mark = 0; name
}
public Student(String n, int m){ mark
:Student name = n;
mark = m; member methods
-name: String }
-mark: int public void setName(String n){
name = n;
}
public void setMark(int m){
+Student() mark = m;
}
+Student(String,int) public String getName(){
+setName(String); return name;
Note: This is
}
+setMark(int) public int getMark(){ overloading
not overriding!
+getMark():int return mark;
}
+getName():String public boolean equals(Student s){
+equals(Student):boolean return this.getName().equals(s.getName());
}
+compareTo(String):int public int compareTo(Student s){
+toString():String return this.name.compareTo(s.getName());
}
public String toString(){
return "Name: "+name+" Mark: "+mark;
}
}
93. Selection Statements
The first selection statement is the if statement.
The else part is optional in this statement
94. The if Statement
In this syntax, if the boolean expression evaluates to true, the
following statement or block of statements enclosed within
braces is performed, otherwise nothing is executed.
if ( <boolean expression> )
<statement>;
no “then”
keyword, we
use brackets
instead
if ( mark < 45 )
System.out.println(“You failed”);
95. The if-else statement
Here, if the boolean expression evaluates to true, the
statement1 or block of statements enclosed within braces is
performed, otherwise Statement2 is performed.
use semicolon
No semicolon here! before else if no
braces are used
if ( <boolean expression> )
<statement 1>;
if ( mark < 45 )
else
System.out.println(“You failed”);
<statement 2>;
else {
System.out.println(“Lucky !! “);
mark++;
}
use braces to enclose
more than one statement
96. Boolean Operators && || !
Use boolean operators to join expressions
&& is the logical and operator
|| is the logical or operator P Q P && Q P || Q !P
! is the not operator false false false false true
false true false true true
true false false true false
true true true true false
if ( wage > 45000 && holiday == true && !married )
System.out.println(“You can go on holiday to Hawaii”);
else {
System.out.println(“Go work!!“);
}
97. Nested if‘s
The else associates
with the nearest if.
Thus braces must be
used to impose the
required association.
Use of nested if‘s
can be a bit
confusing at times
and it is sometimes
preferred to use the
switch statement.
98. Comparing Objects
With primitive data types, we have only one way to compare
them, but with objects (reference data type), we have two
ways to compare them
We can test whether two variables point to the same object (use ==), or
We can test whether two distinct objects have the same contents.
Proper way to compare the contents‖
String str1 = new String("Java"); same sequence of
String str2 = new String("Java"); characters
if (str1.equals(str2)) {
System.out.println("They are equal");
}
else {
System.out.println("They are not equal");
}
99. Comparing Objects with ==
String str1 = new String("Java"); str1
String str2 = str1; J a v a
if (str1 == str2) {
System.out.println("They are equal");
} str2
else {
System.out.println("They are not equal");
}
str1
String str1 = new String("Java");
J a v a
String str2 = new String("Java");
if (str1 == str2) { str2
System.out.println("They are equal"); J a v a
}
else {
System.out.println("They are not equal");
}
100. equals Implementation in Complex
public class Roots{
public static void main (String args[]){
Complex number1 = new Complex(2,-5);
Complex number2 = new Complex(2,-5);
in main
System.out.println("Number 1 = "+number1);
class
System.out.println("Number 2 = "+number2);
method in class
if(number1.equals(number2)) Complex
System.out.println("They are equal");
} public boolean equals(Complex other){
} return ((this.real==other.real) && this.img==other.img));
}
if ((this.real==other.real)&&(this.img==other.img))
return true; We will see a
useless better
else
code implementation
return false; later
101. The switch Statement
The switch statement avoids a lot of nested if‘s
Note:
Only integral constants may be tested
If no condition matches, the default is executed
If no default, nothing is done (not an error). There can be
only one default
The break is a must! otherwise all statements from the
matched case onwards are executed
103. Example of the switch Statement
float f
switch (f) {
case
System.out.print("Input number of legs: ");
2:
int legs = keyboard.nextInt();
switch(legs){ switch (i) {
case 0: System.out.println("There's something fishy!"); break; case 2*j:
case 1: case 3: case 5: System.out.println("That's odd!"); break;
case 6: System.out.println("There must be a bug!");
System.out.println("Get it debugged"); break;
default:System.out.println("It's a sort of creature");
}
104. Iterations (Repetitive Statements)
Repetition statements control a block of code to be executed
for a fixed number of times or until a certain condition is met.
Count-controlled repetitions terminate the execution of the
block after it is executed for a fixed number of times.
Sentinel-controlled repetitions terminate the execution of the
block after one of the designated values called a sentinel is
encountered.
Repetition statements are also called loop statements.
105. The while statement (A Pretested Loop)
int sum = 0, number = 1;
while ( number <= 100 ) {
sum += number;
number++;
}
while ( number <= 100 );
{
106. The do-while Statement (Post-tested)
Use this when you want to loop at least once.
Ideal for keyboard entry validation.
int sum = 0, number = 1;
do {
sum += number;
number++;
} while ( sum <= 1000000 );
108. for Loops Examples
for (int c = 1; c <=3, c++){
for (int r= 1, r <=3, r++){ for (int j = 2; j < 40; j *= 2)
int product = r * c;
System.out.print (“ “ + product);
}
//finished one row; move on to next row for(int i=0; i < 3 ; i++)
System.out.println(“”); int count =2;
}
actually a
declaration and an
assignment. so use
braces or separate
109. Watch out!
Watch out for the off-by-one error (OBOE).
Make sure the loop body contains a statement that will
eventually cause the loop to terminate.
Make sure the loop repeats exactly the correct number of
times.
If you want to execute the loop body N times, then initialize the
counter to 0 and use the test condition counter < N or initialize
the counter to 1 and use the test condition counter <= N.
Avoid a semicolon after the boolean expression cause it will
make it an empty loop.
110. Escape the Block !
‗break‘ takes you out of the present block, and ‗continue‘ will take you at the end
of the end of the body of the loop ie at the next iteration of the body.
You can also escape from a whole nested blocks by using the ‗goto label‘.
All these are interruptions to the normal sequence of operations and should be
very rarely used where the application strictly requires it like the switch statement.
Abuse of these leads to ―spaghetti programming‖
111. Recursive Algorithms
A recursive method is a method that contains a statement (or
statements) that makes a call to itself.
Example - Factorial
The factorial of N is the product of the first N positive integers:
N! = N * (N – 1) * (N – 2 ) * . . . * 2 * 1
for example 5! = 5 * 4 * 3 * 2 * 1
The factorial of N can be defined recursively as
1 if n =1
factorial (n) =
n * factorial (n-1) otherwise
112. Factorial Recursive Implementation
Implementing the factorial of N recursively will result in the
following method.
public static long factorial (long m){ long k = factorial(4);
if (m == 1)
return 1;
else in calling program
return m* factorial(m-1);
}
public static long fac(long m ){
return (m==1)? 1 : m*fac(m-1); shorthand
}
113. Power Recursive Implementation
Similarly x to the power of y: xy = x * x(y-1)
x if y =1
power(x,y) =
x* power(x,(y-1)) otherwise
public static int power (int x, int y){ int k = power(2,10);
if (y == 1)
return x;
in main
else
return ( x* power(x, y-1));
}
114. Fibonacci series WHEN NOT TO USE RECURSION
The well known series of Fibonacci goes: 1, 1, 2, 3, 5, 8, 13,
etc ..
Where except for the first two terms, each term is the sum of
the previous two terms. The first two terms are 1.
1 n <= 2
fibonacci(n) =
fibonaccci(n-1)+fibonacci(n-2) otherwise
public static long fibonacci (long n){ long k = fibonacci(5);
if (n <=2)
return 1; in main
else
return (fibonacci(n-1)+fibonacci(n-2)); most of the terms are
} recalculated
115. Arrays Strings and Patterns
One of the most important structures in computer science
are arrays which are variables which can hold a number
of values. These are indispensable for making variables
change in loops and for not using too much variable
names.
Other important structure in Java is the String which is a
series (an array) of characters and Patterns which are
regular expressions used for matching strings and are
much helpful in the validation of input data.
116. Introduction to Arrays
Array, what is it? An array is a group of variables of the same
data type and referred to by a common name.
An array is contiguous block of memory locations referred by
a common name.
For example to store the marks of 5000 students, you can
declare an array, marks, of size 5000 and can store the marks
of as many students.
int marks[] = new int[5000];
117. Why are Arrays Needed?
You might come across a situation where you need to store
similar type of values for a large number of data items. For
example to store the marks of all the students of a university,
you need to declare thousands of variables.
In addition, each variable name needs to be unique. To avoid
such situations, you can use arrays.
An array consists of a name and the number of elements of the
array. You can refer to a specific array element by the array
name and the element number, which is known as the index.
Note: - Array index element number always starts with 0(zero)
in Java and ends at one less its length.
118. Creating Arrays
The length of an array is fixed at the time of its creation. An
array represents related entities having the same data type in
contiguous or adjacent memory locations. The related data
having data items form a group and are referred to by the
same name.
String employee = new String[5];
Here, the employee is the name of the array and of size 5. The
complete set of values is known as an array and the individual
entities are called as elements of the array.
A specific value in an array is accessed by placing the index
value of the desired element in a square bracket.
String bestEmployee = employee[3];
119. Arrays of Primitive Data Types
Array declaration
<data type> [] <variable name>; or
<data type> <Variable name>[];
float [] marks; float marks [];
Array Creation
<variable> = new <data type> [<size>];
marks = new float[12];
arrays are
objects
120. Array Initialization
Like other data types, it is possible to declare and initialize an
array at the same time.
121. Accessing Individual Elements
To access an individual element of an array we use the
following notation:
m1 = marks [1]; marks[2] = 97;
<variable name> [<index>]
The size of an array is given by a public data member inside
the array class named length;
public static void main (String args[]){
Scanner keyboard = new Scanner(System.in);
int assessments[] = new int[3]; //calculate total
//get marks int total = 0;
for(int i=0;i<assessments.length; i++){ for(int i=0;i<assessments.length;i++){
System.out.print("Enter mark: "); total += assessments[i];
assessments[i] = keyboard.nextInt(); }
} float average = (float)total/3;
System.out.println("The average mark is: "+average);
(float)(total/3);
cast number }
not result
122. Variable-Size Declaration
In Java, we are not limited to fixed-size array declaration at
compilation time unlike some other languages.
The following declares an array of size chosen at runtime by
the user:
public static void main (String args[]){
Scanner keyboard = new Scanner(System.in);
int dimension;
System.out.print("Enter dimension of array: ");
dimension = keyboard.nextInt();
float myArray [] = new float [dimension];
} size declared
at runtime
123. Two-Dimensional Arrays
Two-dimensional arrays are useful in representing tabular
information.
Declaration:
<data type> [][] <variable name> or <data type> <variable name> [][];
int [ ][ ] coefs [ ][ ]; int coefs [ ][ ];
Creation:
<variable name> = new <data type> [<size>][<size>];
coefr = new int[3][5];
All together:
Access elements
effectively a 2D array coefs[4][1]=5;
is an array of arrays
int x = coefs[3][2]=5;
125. Matrix Multiplication Implementation
public static void main (String args[]){
int a[][] = {{5, 2, 0, 10},{3, 5, 2, 5}, {20, 0, 0, 0}};
double b[][] = {{1.50, 0.20},{2.80, 0.40},{5.00, 1.00}, {2.00, 0.50}};
float c [][] = new float [3][2];
for(int i = 0;i< b[0].length; i++){
for(int j = 0;j <a.length;j++){
c[j][i] = 0.0F;
for(int k = 0;k<a[0].length;k++){
c[j][i] += (float)(a[j][k] * b[k][i]); for( int i =0; i< c.length;i++){
} for(int j = 0; j < c[0].length;j++){
} System.out.printf(" %6.2f ",c[i][j]);
} }
System.out.println("");
}
}
126. Ragged and Multi-Dimensional
In fact in Java, a two dimensional array is an array of arrays
and so the 2D array is not necessarily rectangular
An array in java is stored row-first.
double[][] tri = new double[4][];
for(int i=0;i<4;i++)
tri[i] = new double[i+1];
In fact in Java you can have 3D arrays, 4D arrays to any
dimension you desire. It is hard to visualise but a 3D array is
nothing but an array of 2D arrays, etc.
double[][] [] threeD = new double[4][4][4];
127. Arrays of Objects
In Java, in addition to arrays of primitive data types, we can
declare arrays of objects.
An array of primitive data is a powerful tool, but an array of
objects is even more powerful.
The use of an array of objects allows us to model the
application more cleanly and logically.
1
2
3
1
Student [] klassi;
klassi = new Studnet[6]; 2
klassi[0] = new Student();
3
klassi[1] = new Student();
128. Example of 2D Arrays
import java.util.*; int bestpos = 0; // assume first to be the best
public class BestWorst int worstpos = 0; // assume first to be the worst
{ for(int i = 0; i< klassi.length; i++){
if(klassi[i].getMark()>klassi[bestpos].getMark())
public static final int SIZE = 3; bestpos = i;
if(klassi[i].getMark()<klassi[worstpos].getMark())
public static void main (String args[]){ worstpos = i;
}
Student [] klassi = new Student[SIZE]; System.out.println(klassi[bestpos]);
System.out.println(klassi[worstpos]);
Scanner kb = new Scanner(System.in); Uses
kb.useDelimiter("n"); toString in
}
Student
}
for(int i = 0; i<klassi.length; i++){
System.out.print("Enter Name & Surname: ");
String name = kb.next(); kb.useDelimiter("n");
System.out.print("Enter Mark: ");
int mark = kb.nextInt(); to read space
klassi[i] = new Student(name,mark); between name
} and surname
129. Command-Line Arguments
A Java application can accept any number of arguments from the command line.
This allows the user to specify configuration information when the application is
launched.
When an application is launched, the runtime system passes the command-line
arguments to the application's main method via an array of Strings.
public class HaveMore{
public static void main (String args[]){
if (args.length > 0){
System.out.println("You got some extra stuff: ");
for(int i = 0; i <args.length;i++){
System.out.println(args[i]);
}
}
}
}
130. Strings
A string is a sequence of characters that is treated as a single value.
Instances of the String class are used to represent strings in Java.
In Java a String object is immutable
This means that once a String object is created, it cannot be changed, such
as replacing a character with another character or removing a character
The String methods we have used so far do not change the original string.
They created a new string from the original. For example, substring creates
a new string from a given string.
Single characters can be accessed using the charAt() method
String r = "Top 20";
r.charAt(1)
131. Some Useful methods in String
Note: there are far too many
methods in class String. See
String documentation for a
complete list
132. Different String Creations
Depending on the methods used for creation, Sting pointers
can point either to the same object or different objects:
String word1, word2; String word1, word2;
word1= "Java"; word1= new String("Java");
word2= "Java"; word2= new String("Java");
word1 word1
J a v a J a v a
word2
word2 J a v a
133. StringBuffers
In many string processing applications, we would like to change
the contents of a string. In other words, we want it to be
mutable.
Manipulating the content of a string, such as replacing a
character, appending a string with another string, deleting a
portion of a string, and so on, may be accomplished by using
the StringBuffer class.
StringBuffer word= new StringBuffer(“Java");
word.setCharAt(0,'L');
word word
J a v a L a v a
134. Patterns - Regular Expressions
A Pattern is called a regular expression.
Rules
The brackets [ ] represent choices
The asterisk symbol * means zero or more occurrences.
The plus symbol + means one or more occurrences.
The hat symbol ^ means negation.
The hyphen – means ranges.
The parentheses ( ) and the vertical bar | mean a range of choices for
multiple characters.
if(entry.matches("(21|27|79|99)[0-9]{6}"))
System.out.println("Valid Telephone Number ");
else
System.out.println("Invalid Telephone Number");
135. Some Examples
Expression Description
[013] A single digit 0,1 or 3
[0-9][0-9] Any two digit number 00 to 99
[0-9&&[^4567]] A single digit 0,1,2,3,8 or 9
[a-z0-9] Single lower case character or digit
[a-zA-Z][a-zA-Z0-9_$] A valid Java identifier consisting of alphanumeric
characters, underscores and dollar sign, with the first
charcter being an alphabetic character
[wb][qd|eed] Matches wad weed and beed
(AZ|CA|CD)[0-9][0-9] Matches AZxx, CAxx and COxx, where x is a single
digit
136. Garbage Collection
Garbage collection is the process of automatically finding memory
blocks that are no longer being used ("garbage"), and making
them available again. In contrast to manual deallocation that is
used by many languages, eg C and C++, Java automates this
error-prone process and avoids two major problems:
Dangling references. When memory is deallocated, but not all pointers to it
are removed, the pointers are called dangling references -- they point to
memory that is no longer valid and which will be reallocated when there is a
new memory request, but the pointers will be used as tho they still pointed to
the original memory.
Memory leaks. When there is no longer a way to reach an allocated memory
block, but it was never deallocated, this memory will sit there. If this error of
not deleting the block occurs many times, eg, in a loop, the program may
actually crash from running out of memory.
137. Javadoc
Many of the programmer-defined classes we design are intended to be
used by other programmers.
It is, therefore, very important to provide meaningful documentation to the
client programmers so they can understand how to use our classes correctly.
By adding javadoc comments to the classes we design, we can provide a
consistent style of documenting the classes.
Once the javadoc comments are added to a class, we can generate HTML
files for documentation by using the javadoc command.
Javadoc comments begins with /** and ends with */
Special information such as the authors, parameters, return values, and
others are indicated by the @ marker
@param @author @return @version
see: http://java.sun.com/j2se/javadoc
138. Stacks
A programmer‘s stack is a simple concept with wide application. Stacks
can be found in all kinds of programs, at system level and in every
field of application. To maintain the analogy of a physical stack (of
bricks or trays) we draw a programmer‘s stack (of numbers, chars or
even objects) upside down.
A stack may be created, as depicted, from an array of stackable
objects and an integer variable for storing the number of objects
currently stacked (top of stack)
Three functions needed to manage such a stack:
push: Place a new object on the top of the stack
pop: Take the item that is on top of the stack
peep: Take a copy of the item on top of the stack without removing it.
139. Stack Example - Reversing a String
Using the stack, we can easily reverse a string entered from
the keyboard.
public class Stack
{
public static void main (String args[]){ private int tos;
Scanner kb = new Scanner(System.in); char stack[] = new char[40];
public char pop(){
Stack x= new Stack(); public Stack() char item=' ';
System.out.print("Enter a string: "); { if (tos > 0)
tos = 0; item = stack[--tos];
String entry = kb.nextLine();
} return item;
for(int i = 0; i < entry.length(); i++) }
x.push(entry.charAt(i)); public void push(char item){
if (tos <40) public char peep(){
for(int i = 0; i < entry.length();i++)
stack[tos++] = item; char item=' ';
System.out.print(x.pop()); if (tos >= 0)
}
} item = stack[tos];
return item;
}
}
140. Reverse Polish Notation
Algebraic expressions in conventional form may be expressed in reverse
Polish notation which was devised by the polish logician Jan Lukaciewicz,
which only Poles can pronounce. ‗Reverse because his original order of
operators and operands has been reversed.
As an example of reverse Polish notation:
The reverse Polish expression is easier to evaluate than might appear.
For example let A=6, B=4, C=1, D = 2, F=3, G =7 and H = 5.
With these values the expression to be evaluated is:
Work from left to right taking each item in turn. Whenever you come to an operator,
apply it to the previous two terms, reducing two terms to one: