Você está na página 1de 18

COMPUTER STUDIES (HG)

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;

Some Methods in class Math


Math.round(x)
Math.sqrt(x)
Math.abs(x)
Math.pow(x, y)
Math.random()
Math.max(a, b)
Math.min(a, b)
Math.PI
Examples:
double s = 2.5 + 1/Math.sqrt(0.5);
double fiveCubed = Math.pow(5, 3);
x = Math.round(x);
The if Statement
(a) if (condition)
statement
(b) if (condition)
statement
else
statement
Examples:
if ( num % 2 == 0)
System.out.println("This number is even!");
if (x >= 0)
y = Math.sqrt(x);
else
System.out.println("Square root cannot be calculated.");
The while Statement
while (condition)
statement
Example:
int sum = 0;
int i = 0;
while (sum <100)
{ i++;
sum = sum + i;
}

The for Statement


for (initialization; condition; update)
statement
Example:
int sum = 0;
for ( int i = 1; i <= 100; i++)
sum = sum + i;
The do...while Statement
do
statement
while (condition);
Example:
int i = 0; int sum = 0;
do
{ i++; sum = sum + i; }
while ( sum <100 );
The break statement
break
Example:
while (true)
{ String in = br.readLine();
if (in.equalsIgnoreCase("Q"))
break;
..
.
The execution of a break statement causes the current loop to end, and the program continues
with the first statement following the loop.
The switch Statement
switch (variable)
{ caseStatement;
caseStatement;
.
.
caseStatement;
}
where
variable is of type int or char
caseStatement has the form
case constant: statements; break;
or
default: statements;
Example

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) {

Some String Methods


A String in Java is an object of class String. A string is a sequence of characters, numbered from
0 to length()1. The following methods belong to the String class. Since each string is an object,
the methods are called using the name of the object and the name of the method, for example:
word.length(), "Hello.toUpperCase

Return type

Method name

Description

String

toUpperCase()

All letters to upper case.

String

toLowerCase()

All letters to lower case.

char

charAt(int index)

Returns the character at the specified index.

int

indexOf(String str)

Index of the first occurrence of str.

int

indexOf(String str, int fromIndex)

Same as indexOf, but starting at index fromIndex.

int

length()

Returns the number of characters in this string.

String

replace(char oldChar, char newChar)

All oldChar replaced by newChar.

String

substring(int beginIndex)

Substring, from beginIndex to the end of the string.

String

substring( int beginIndex, int endIndex)

Substring, from beginIndex to endIndex1.

String

trim(String str)

Removes leading and trailing blanks.

boolean

equals(String str)

True if str is equals this string; false otherwise.

boolean
int
int

equalsIgnoreCase(String str)
compareTo(String str)
compareToIgnoreCase(String str)

As for equals, but ignore case of characters.


Compare two strings: Returns -1, 0 or 1 for <, =, >
As for compareTo, but ignore case of characters.

Reading a Text File


The method readLine() from the class BufferedReader uses FileStreamReader to read in a string
from a text file (see below).
A method which uses a FileReader or a BufferedReader, or any method which calls this method,
must include the declaration throws IOException in the method header. Alternatively, the
method call must be included in a try . . . catch block.
import java.io.;
..
.
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while (true)
{ line = br.readLine();
if (line == null) break;
System.out.println(line);
}
Creating and Writing a Text File
The method printLine() from the class PrintWriter writes characters to a text file (see below).
Remember to throw or catch an IOException.
After writing to a text file, the file must be closed to ensure that the print buffer is emptied.

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());

public double area()


{ return Math.PIradiusradius; }
}

}
}

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.

Method Overriding and Method Overloading


When a subclass contains a method with the same name, same return type and same number
and types of parameters as a method in one of its superclasses, the subclass method overrides
the method of the superclass. For example, the getArea() methods in classes Rectangle and
Circle overrides the getArea() method of class Shape.
A method or constructor in a class is overloaded if the class contains more than one method
with the same name, but different parameters.
Final Classes and Final Methods
When a class is declared final, the class can not be extended by another class.
When a method is declared final, the method can not be overridden in a subclass.
The toString() Method
Every class inherits a toString() method from class Object. Some classes have toString() methods which override the inherited method:
String number = Integer.toString(2)
Any class can override the inherited method:
class Circle
{ private double radius;
public String toString()
{ return Circle with radius + Double.toString(radius): }
}
When an object is printed using the standard println (or print) method, the objects toString()
method is called:
Circle c = new Circle(3);
System.out.println(c); // Prints: Circle with radius 3.0
Named Constants (final declaration)
If a variable is declared final, the value of the variable cannot be modified after a value has
been assigned to the variable. The variable is therefore a constant.
Final variables are used to name constants (and by its name explain its use) in a Java program.
Example: Math.PI is a named constant with value .
By convention, the name of a final variable is written in UPPERCASE letters.
Class Inheritance, Class Extension
If a class extends another class, all variables and methods of the second class are also considered
to be part of the first class.
Example:
class Shape
{ private String type;
public Shape(String type)
{ this.type = type; }
public String getType()
{ return type; }
}

//Class property
//Constructor
//Accessor method

class Rectangle extends Shape


{ private double length, breadth;
public Rectangle(double length, double breadth)
{ super(Rectangle);
this.length = length;
this.breadth = breadth; }
public double getArea()
{ return lengthbreadth; }
}
class Circle extends Shape
{ private double radius;
public Circle(double radius)
{ super(Circle);
this.radius = radius; }
public double getArea()
{ return Math.PIradiusradius; }
}
class UseShapes
{ public static void main(String[] args)
{ Rectangle shape1 = new Rectangle(3, 2);
Circle shape2 = new Circle(4);
System.out.println(Area of + shape1.getType()
+ is + shape1.getArea() + \n);
System.out.println(Area of + shape2.getType()
+ is + shape2.getArea() + \n);
}
}
The class which extends another class is called a subclass of of the second class, and the class
which is extended is the superclass. In the example above, class Shape is the superclass of
classes Rectangle and Circle; Rectangle and Circle are both subclasses of Shape.
In the example above, classes Rectangle and Circle both have a property type and a method
getType which are defined in class Shape.
A private variable can not be referenced from a subclass; the declaration protected enables a
variable to be referred from any subclass, but not from other classes.
The Keyword this
Every method in a class has a variable called this which is declared automatically. The type
of this is the class in which the method is defined. The variable this contains the address (or
reference) of the current object. Example:
class Circle
{ private double radius;
public Circle(double radius)
{ this.radius = radius;
..
.
The Keyword super

// 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.

static int linearSearch(int[] a, int length, int target)


{
int n = -1;
for (int i = 0; i <length; i++)
if (a[i] == target)
{ n = i;
break;
}
return n;
}
If the elements of the array are sorted, a binary search is much more efficient: Compare the
target with the middle element of the array. If their values are the same, the search is complete;
otherwise, the target must be in either the top half or the bottom half of the array. Repeat
the search on that half of the array which contains the target.
static int binarySearch(int[] a, int length, int target)
{
int low = 0;
int high = length - 1;
int middle;
while (low <= high)
{
middle = (low + high)/2;
if (a[middle] == target) return middle;
if (target <a[middle])
high = middle - 1;
else
low = middle + 1;
}
return -1;
}
The Vector Class
In Java, a vector is a list of objects, similar to an array, but without a fixed length. The
number of objects which the list can contain, need not be specified; when a vector is filled, it
is automatically replaced by a larger vector.
A vector can store any object (a string, an array, or an instance of any class) but can not store
primitive types (int, double, boolean, char). A vector only stores references to objects; not the
objects themselves.
A vector is an instance of the Vector class, which should be imported from the package java.util.
Objcts are stored in a vector, and retrieved, using methods of the Vector class:

Vector()

Default constructor; initial capacity 10;


size is doubled when vector grows

Vector(int capacity)

Construct a vector with specified capacity

Vector(int capacity, int increment)

Construct a vector with specified capacity


and specified value by which vector grows

add(Object obj)

Appends an object to the end of the vector

add(int i, Object obj)

Inserts an object at the specified position


(index starts at 0)

set(int i, Object obj)

Replaces an object at the specified position

get(int i)

Returns the object at the specified position

remove(int i)

Removes the object at the specified position

size()

Returns the number of objects in the vector

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();

The StringBuffer Class


A Java string can not be changed in any way once it has been created; strings are immutable
objects. Statements like the following:
String name =Harry;
name = name + Potter;
causes the string Harry to be discarded and replaced by a new string. After the string
HarryPotter has been formed, there is no way to inserrt a space into the string.
The StringBuffer class allows the construction of strings of characters which can be modified.
An object of class StringBuffer does not have a fixed length; it can be extended or shortened
(in the same way as a Vector). Example:
StringBuffer name =new StringBuffer(Harry);
name.append(Potter); // name is now HarryPotter
name.insert(5, ); // name is now Harry Potter
Some methods of the StringBuffer class:
StringBufffer()

Default constructor; initial capacity 6

StringBufffer(String str )

Constructs a StringBuffer containing the string str

append(String str )

Appends the string str to the current string

insert(int pos, String str )

Inserts the string str at position pos in the current string

charAt(int pos)

Returns the character at position pos (index starts at 0)

The StringTokenizer Class


Tokens are substrings of a string, separated by delimiters such as a comma, a space or a tab.
Using methods of the StringTokenizer class (in the package java.util), we can pick off substrings
from a string. Example:
String name = Potter,Harry Weasly,Ron
StringTokenizer st = new StringTokenizer(name, , ); // Delimiters: comma and space
while (st.hasMoreTokens())
System.out.println(st.nextToken()); // Print 4 tokens: Potter Harry Weasly Ron
Some methods of the StringTokenizer class:
StringTokenizer(String str )

Constructs a tokenizer for string str with


delimiters space, tab, new line

StringTokenizer(String str, String delims)

Constructs a tokenizer for string str with


specified delimiters

hasMoreTokens()

Returns true if there are more tokens available

nextToken()

Returns then next token

countTokens()

Returns the number of tokens in the string

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.

The dafault locale can be displayed using the following statements:


Locale where = Locale.getDefault();
System.out.println(where.getDisplayCountry());
System.out.println(where.getDisplayLanguage());
The Formatter Classes
Java contains several formatter classes which can be used to specify the output format of
numbers and currency. The output of some of the formatters depend on the curent locale (see
above); for example, a currency amount may be displayed as R2,20 or $2.20 or 2.20.
The NumberFormat class (in the package java.text) contains methods which control the number
of decimal places of a decimal number which are to be printed:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(2.6186) + + nf.format(3.1)); // Prints 2.62 3.10
A curency amount is formated by the CurrencyInstance class:
NumberFormat cf = NumberFormat.getCurrencyInstance();
System.out.println(cf.format(2.6186)); // Prints R2.62

Você também pode gostar