Escolar Documentos
Profissional Documentos
Cultura Documentos
JAVA SYNTAX
A Simple Program
class classname
{ public static void main(String[ ] name)
{ statements
}
}
Example:
class Hello
{ public static void main(String[ ] args)
{ System.out.println("Hello, World!");
}
}
Output Statements
System.out.println(string);
System.out.print(string);
Examples:
System.out.println("Hello, World!");
System.out.print("The answer is " + (3 + 2));
System.out.println(22/7 - 3);
Variable Definition
(a) typeName variableName, variableName, ... , variableName;
(b) typeName variableName = expression;
where
typeName is one of: int double boolean char String ClassName
variableName is a string of alphabetic and/or numerical characters.
Examples:
int i, j;
char a = A;
double pi = 22.0/7.0;
String myName;
Assignment Statement
typeName variableName = expression;
variableName = expression;
Examples:
int i = 1;
myName = "John" + " " + "Smith";
total = total + deposit;
switch (choice)
{ case A: language = "Afrikaans"; break;
case E: language = "English"; break;
case X: language = "Xhosa"; break;
default: language = "Unknown";
}
Console Output
System.out.print(String)
System.out.println(String)
The println method displays the String and starts a new line. The print method does not start a
new line, and is used to build up a line.
String stringName = "characters";
String stringName = string1 + string2 ;
A string may include control characters:
\n Start a new line
\t Advance to the next tab position
\\ Print a backslash
\ Print a single quote
\ Print a double quote
Input and Output using Dialogue boxes
import javax.swing.JOptionPane;
String stringName = JOptionPane.showInputDialog(messageString);
JOptionPane.showMessageDialog(null, outputString);
System.exit(0);
int name = Integer.parseInt(stringName);
double name = Double.parseDouble(stringName);
Methods in Class JOptionPane
JOptionPane.showInputDialog(messageString);
JOptionPane.showInputDialog(messageString, initialValue);
JOptionPane.showInputDialog(null, messageString, titleString, messageType);
JOptionPane.showMessageDialog(null, outputString);
JOptionPane.showMessageDialog(null, outputString, titleString, messageType);
where messageType is one of the following:
JOptionPane.INFORMATION MESSAGE
JOptionPane.QUESTION MESSAGE
JOptionPane.WARNING MESSAGE
JOptionPane.ERROR MESSAGE
JOptionPane.PLAIN MESSAGE
Console Input Using BufferedReader
The method readLine() from the class BufferedReader uses the class InputStreamReader to read
in a string from the console.
A method which uses an InputStreamReader or a BufferedReader, or any method which calls
this method, must include the declaration throws IOException in the method header. (An
exception is thrownwhen something goes wrong.) Alternatively, the method call must be
included in a try . . . catch block (see below). We will discuss exeptions in more detail later on;
for now, we will simply do nothing when an exception is caught.
import java.io.;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = ;
try { s = br.readLine(); }
catch (IOException e) {
Return type
Method name
Description
String
toUpperCase()
String
toLowerCase()
char
charAt(int index)
int
indexOf(String str)
int
int
length()
String
String
substring(int beginIndex)
String
String
trim(String str)
boolean
equals(String str)
boolean
int
int
equalsIgnoreCase(String str)
compareTo(String str)
compareToIgnoreCase(String str)
import java.io.;
..
.
PrintWriter out = new PrintWriter(new FileWriter(filename));
String line1, line2;
..
.
out.println(line1);
out.println(line2);
out.close();
..
.
Arrays
An array is a list of variables of the same type that all have the same name. A specific variable
in the list is identified by its position. For example, instead of defining four integers:
int number1, number2, number3, number4;
we may define an array of type integer:
int[ ] number = new int[4];
and refer to each array variable by using an index:
number[0], number[1], number[2]. number[3]
The index of an array of length n runs from 0 to n 1.
An aray of any type may be defined:
double[ ] s = new double[20];
String[ ] args;
boolean[ ] isPositive;
The statement
int[ ] number = new int[4];
declares an array of integers, and allocates space for 4 integers. This may also be done in two
separate steps:
int n = 4;
int[ ] number;
number = new int[n];
An array may also be initialized:
int[ ] numbers = {1, 2, 5};
The number of elements in an array may be found by using the length property:
int s = 0;
for ( int i = 0; i <number.length; i++)
s = s + number[i];
Two-Dimensional Arrays
A table of values can be defined in Java using a two-dimensional array (also called a matrix):
int[ ][ ] numbers = new int[3][4];
for (int i = 0; i <3; i++)
for (int j = 0; j <4; j++)
numbers[i][j] = i + 2*j;
Exceptions
When something goes wrong while a Java program is running, the program generates an
exception. This means that normal program execution is stopped and a special error handling
procedure takes place.
There are two types of exceptions in Java: Checked exceptions and unchecked exceptions.
A checked exception must either be thrown, or caught in a try ... catch block. The compiler will not compile the program if it is ignored. An input/output error (IOException)
is an example of a checked exception.
An unchecked exception (or run-time exception) can either be ignored, or caught in a
try ... catch block. Examples of unchecked exceptions are attempting to divide by 0, or
to convert a string containing alphabetic characters to a number. When an unchecked
exception occurs and is ignored, the program stops immediately and an error message
is printed.
An exception is caught by using a try . . . catch block:
try { statements which may generate an exception }
catch(exceptionClass name) { statements which handle the exception }
finally { statements to be executed regardless }
If no exception is generated in the try block, the catch block is ignored and the program
continues normally.
If an exception is generated in the try block, the statements in the catch block are executed
as soon as the exception has been generated and the program then continues with the
statements following the catch block.
The finally block is optional. If there is a finally block, the statements in this block are
executed after the try block if no exception is generated, and after the catch block if an
exception is generated.
An exception is thrown by adding a throws clause to the method header, for example:
public String readString() throws IOExecption { . . . }
This means that the method will not catch the exception, but passes it on (throws it to) to
the method which called this method. If the main method has a throws clause, the program
is halted when an exception occurs.
Example:
while (true)
{ String in = readString();
try
{ return Integer.parseInt(in); }
catch (NumberFormatException e)
{ System.out.println(Not an integer, try again); }
}
What is a Java Method? A method is a series of statements to complete a specific task.
Examples:
class MultiplyMethod1
{ public static void main(String[] args)
{ multiply(2.4, 16.38);
}
public static void multiply(double a, double b)
{ double c = ab;
System.out.println(The product is + c);
}
}
class MultiplyMethod2
{ public static void main(String[] args)
{ double c = multiply(2.4, 16.38);
System.out.println(The product is + c);
}
public static double multiply(double a, double b)
{ double c = ab;
return c;
}
}
Syntax of Methods
1. A Class with Static Methods
class className
{ staticMethod
staticMethod
..
.
}
2. Static Method Definition
public static returnType methodName(parameterList)
{ statements
}
3. ReturnType
One of the following:
void int double boolean char String ClassName
4. ParameterList
Empty, or
typeName variableName, typeName variableName, . . ., typeName variableName
5. return Statement
return expression;
6. Calling a Method
methodName(argumentList)
ClassName.methodName(argumentList)
where
argumentList is empty, or
expression, expression, . . . , expression
Using a Static Method
1. When a method is called from the class where the method is defined, then class name can be
omitted: multply(2.0, 3.0). When a method from another class is called, the class name must
be included: Math.sqrt(2.0)
2. A method with a returnType which is not void, must contain a return statement. The type of
the expression following return must be same as the returnType of the method.
3. When a method is called, the number and types of the arguments and corresponding parameters must be the same.
Classes and Objects
A Java class is a description of the properties and capabilities of a set of objects. A class
contains fields which describe the properties of the class, and methods which describes the
capabilities of class. For example, class Circle states that each circle has a radius (a property
of the class Circle), and descibes how a circle can define its radius and calculate its area (the
methods of the class Circle).
A Java object is a specific example of a class. For example, smallCircle and bigCircle are two
objects which each has a specific radius. Each circle object can set its own radius and calculate
its own area.
Remember: An object is an instance of a class. An object is created by using the keyword
new.
Constructors
class Circle
{
double radius;
public Circle(double r)
{ radius = r; }
class TestCircle
{
public static void main(String[] args)
{ Circle smallCircle = new Circle(0.5);
Circle bigCircle = new Circle(2.0);
System.out.println(Small area is + smallCircle.area());
System.out.println(Big area is + bigCircle.area());
}
}
A constructor is a method which has the same name as the class in which it is defined.
When a new object of the class is constructed using the new keyword, the constructor is called.
A constructor has no return type. Its purpose is to set values for the class variables.
Private, Public Declarations
A variable or method which is declared private can only be accessed from the class where the
variable or method is defined.
A variable or method which is declared public can be accessed from any class.
A variable which is declared neither private nor public can be accessed from all classes in the
same package.
In general, class variables should be declared private and methods should be declared public.
Static Declaration
A variable which is declared static is associated with the class and not with each instance of
the class.
A variable which is not declared static and is not a local variable, is an object variable. Each
instance of the class contains all object variables.
A method which is declared static can only access static variables. A static method is called
by using the name of the class followed by the name of the method. Example: Math.sqrt(2.0)
A method which is not declared static, is an object method and can access object variables as
well as static variables. An object method is called by using the name of an object followed
by the name of the method. Example (see above): br.readLine()
Accessor and Mutator Methods
An accessor method (a get method) returns the value of a variable, but does not modify the
value of any variable.
A mutator method ( a set method) assigns a value to a variable. (Mutate means to
change.)
Overloaded Methods A class may contain two methods with the same name, but different
signatures. Example:
class Multiply
{ public static void main(String[] args)
{ System.out.println(The product is + multiply(2, 16));
// First method is called
System.out.println(The product is + multiply(2.4, 16.38)); // Second method is called
}
public static int multiply(int a, int b)
{ return ab; }
public static double multiply(double a, double b)
{ return ab;}
}
The signature of the first method is multiply(int, int)
The signature of the second method is multiply(double, double)
Abstract Classes and Abstract Methods
When a class is declared abstract, no object of that class can be created. An abstract class
can be extended, and objects of the subclasses can be created. In the example which follows,
class Shape is declared abstract and there can be no object of class Shape.
An abstract class is a pattern (a template) which all its subclasses inherit.
An abstract class may contain one or more abstract methods. An abstract method has no
body, and must be implemented in every subclass of the abstract class. In the example, class
Shape has an abstract class getArea() which has no statements, since a general shape does not
have an area. By including the abstract method, every subclass of Shape (such as Rectangle
or Circle) is forced to have a method getArea().
Polymorphism
The word polymorphism means many shapes. In a Java program, polymorphism means
that an instance of a subclass can take the place of an instance of any of its superclasses. In
the example which follows, objects of class Rectangle and of class Circle may be stored in an
array of class Shape. Remember: A rectangle is a Shape; a Circle is a Shape; but not the
other way round.
//Class property
//Constructor
//Accessor method
// Constructor
Every class has a variable called super which is declared automatically. The variable super
refers to the superclass of the class in which super is used.
The statement super( ) calls the constructor of the superclass. If present, it must be the
first statement in a constructor of a subclass. (See example above.)
Arrays of Objects
An array of any data type may be declared. A class is considered to be a data type; therefore
an array of objects of a class may be declared. Example: An array of circles:
class Circle
{
double radius;
public Circle(double r)
{ radius = r; }
public double area()
{ return Math.PIradiusradius; }
}
class TestCircle
{
public static void main(String[] args)
{ Circle[] circles = new Circle[3];
circles[0] = new Circle(0.5);
circles[1].= new Circle(2.0);
circles[2].= new Circle(1.5);
System.out.println(Total area is +
circles[0].area()+circles[1].area()+circles[2].area());
}
}
Sorting an Array
Sorting is the process of arranging the elements of an array from smallest to largest, or from
largest to smallest, or in alphabetic order. In many applications it is important to work with
sorted arrays.
There are many sorting techniques. The simple techniques which we will discuss here are
quite slow, but are adequate for arrays shorter than (say) 1000 elements. The Quicksort
method, which is more involved, is much more efficient for large arrays. We will discuss
sorting in ascending order; descending order is similar. Suppose that elements to be sorted
are numbered 0 to n 1.
Selection Sort: Repeat the following for i = 0, 1, 2, . . ., n 2:
Find the smallest element in the subarray consisting of elements i to n 1; switch the smallest
element with the element at position i.
Bubble Sort: Run through the array repeatedly; if any two adjacent elements are out of
order, switch them.
Insertion Sort: Repeat the following for i = 1, 2, . . . , n 1:
Insert the element at position i into its correct position amongst elements 0, 1, . . ., i 1.
Search Methods
Searching is the process of finding (the index of) a specific element of an array.
If the elements of the array are unsorted, a linear search must.be performed: Starting at the
first element, examine each element and stop as soon as the target has been found.
Vector()
Vector(int capacity)
add(Object obj)
get(int i)
remove(int i)
size()
An object which has been stored in a vector, must be cast back before it can be used:
Vector v = new Vector();
v.add(Harry);
String name = (String)v.get(0);
The Object Class
Java contains a class named Object, which is a superclass of every other class. This implies
that a variable of type Object can hold a reference to any object of any class:
Object s = new Circle(4);
Object name = Harry;
A vector actually stores instances of class Object.
Class Object provides a number of methods which are inherited by all objects; the most
important of these methods are equals(...) and toString() (see below).
Wrapper Classes
For each primitive data type, Java provides a corresponding class (wrapper class). An
instance of a wrapper class stores one variable of that datatype:
Data Type
int
double
boolean
char
Wrapper Class
Integer
Double
Boolean
Character
Each wrapper class has a method which returns the value stored in an instance of that class:
Integer i = new Integer(2); // The object i stores the integer value 2
int j = i.intValue();
Wrapper classes also contain several static methods (such as Integer.parseInt()) and static
constants (such as Integer.MAX VALUE) which are related to the corresponding primitive type.
See the online documentation for details.
When a primitive variable must be stored in a vector, an instance of the corresponding wrapper
class can be stored (since a vector cannot store primitive variables):
Vector v = new Vector();
v.add(new Integer(2));
int i = v.get(0).intValue();
StringBufffer(String str )
append(String str )
charAt(int pos)
hasMoreTokens()
nextToken()
countTokens()
Locales
A locale object stores information about a country or a region: Name of the country, language,
currency symbol (such as $), and conventions regarding the formatting of numbers.
The Java Virtual Machine (the program which runs Java classes) on each computer, stores a
default locale. Some methods in Java (see below) use the default locale object when displaying
a number or other information.