Download Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

C syntax wikipedia , lookup

Falcon (programming language) wikipedia , lookup

Smalltalk wikipedia , lookup

Scala (programming language) wikipedia , lookup

Exception handling wikipedia , lookup

Design Patterns wikipedia , lookup

Java syntax wikipedia , lookup

Name mangling wikipedia , lookup

Java (programming language) wikipedia , lookup

Class (computer programming) wikipedia , lookup

Object-oriented programming wikipedia , lookup

C++ wikipedia , lookup

Java performance wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

C Sharp syntax wikipedia , lookup

Transcript
A Brief Introduction to Java
Programming the World Wide Web
Overview of Java
• In comparison with C++
–
–
–
–
–
Based on C++
Support for object-oriented programming
No user-defined overloading
Implicit deallocating heap objects
No pointers
• Java is an object-oriented language.
– Java does not support procedure-oriented programming.
– Subprograms in Java can appear only as methods defined in class
definitions.
– All data and functions are associated with classes, and also with
objects.
Overview of Java
• Java does not allow user-defined operator overloading.
• Garbage collection is used to reclaim heap storage that has
been deallocated.
• Java does not support multiple inheritance but uses interfaces
instead.
• Java does not include pointers. Instead, it provides references.
• Java does not allow narrowing coercions.
• Control expressions in control statement in Java must have
Boolean values.
Overview of Java
• Output to the screen from a Java application appears through
the object System.out.
– The values of non-String variables that appear in the parameter to
System.out.print or System.out.println.
– The string parameter to print and println is often specified as a
catenation of several strings, using the + catenation operation.
• Examples:
System.out.println(“Apples are good for you”);
System.out.println(“You should eat “ + numApples + “ apples each
week”);
System.out.print(“Grapes “);
System.out.println(“are good, too”);
Apples are good for you
You should eat 7 apples each week
Grapes are good, too
Overview of Java
• Naming conventions used in Java are as follows:
–
–
–
–
–
Class and interface names begin with uppercase letters.
Variable and method names begin with lowercase letters.
Package names use all lowercase letters.
Constant names use all uppercase letters.
The first letter of all embedded words is capitalized.
Data Types and Structures
• Java has only one way to reference an object through a
reference variable.
• The Java primitive types are int, float, double, char, and
boolean.
• Each primitive type has a corresponding “wrapper” class,
which is used when it is convenient to treat a primitive value
as object.
• For example, the wrapper class for double is Double.
Integer wrapsum = new Integer (sum);
Data Types and Structures
• To convert the float value speed to a String object, the
following can be used:
Float speedObj = new Float(speed);
String SpeedStr = speedObj.toString();
• Reference variables are defined the same way as primitive
variables:
String str1;
• An array of characters can be created using the String and
StringBuffer classes in two ways:
String greet1 = new String(“Guten Morgan);
String greet2 = “Guten Morgan;
String in Java
• Both Java String and StringBuffer objects use 2 bytes per
character because they use the Unicode character coding.
• String catenation can be done with the plus (+) operator.
greet3 = greet3 + “ New Year”;
• The String object has methods such as charAt, substring,
concat, and indexOf.
• The equals method of String must be used to compare two
strings of equality (== can not be used.)
• If a string must be manipulated, it cannot be a String object. A
Stringbuffer object can be used.
• The Stringbuffer class has methods such as append, delete,
and insert.
Arrays in Java
• In Java, arrays are objects of a class that has some special
functionality. Array objects can be created with statements:
element_type arary_name[] = new element_type[length];
• Consider the following statements:
int [] list1 = new int[100];
Float [] list2 = new float[10];
Int[] list3;
list3 = new int[200];
• When a subscript is detected that is out of range, the exception
ArraryIndexOutOfBoundsException is thrown.
• Java does not have the struct and union data structures. It also
does not have the unsigned types or the typedef declaration.
Classes, Objects, and Methods
• The parent of a class is specified in the class definition with
the extends reserved word.
[modifier] class class_name [extends parent_class] { …}
• Three different modifiers can appear at the beginning of a
class definition: public, abstract, and final.
– The public modifier makes the class visible to classes that are not in the
same package.
– The abstract modifier specifies that the class cannot be instantiated.
– The final modifier specifies that the class cannot be extended.
• The root class of all Java classes is Object.
Classes, Objects, and Methods
• The visibility of variables and member functions (methods)
defined in classes is specified by placing their declarations in
public, private, and protected.
• A variable declaration can include the final modifier to specify
that the variable is a constant.
• Java class methods are specified by including the static
modifier to their definitions.
– Any method without static is an instance method.
– The abstract modifier specifies that the method is not defined in the
class.
– The final modifier specifies that the method cannot be overridden.
Classes, Objects, and Methods
• Java includes the package at a level above classes. Packages
can contain more than one class definition.
• Packages often contain libraries and can be defined in
hierarchies.
• A package can be included as the following way:
Package cars;
• A variable or method in a package can be specified in the
following way:
weatherpkg.WeatherData.avgTemp
Classes, Objects, and Methods
• An import statement provides a way to abbreviate such
imported names.
import weatherpkg.WeatherData;
• Now the variable avgTemp can be accessed directly with just
its name. The import statement can include an asterisk to
indicate all classes in the package are imported:
import weatherpkg.*;
Classes, Objects, and Methods
• A Java application program is a compiled class that includes a
method named main.
Public class Hello {
public static void main (String[] args) {
System.out.println(“Hello World”);
}
• The modifier on the main method are always the same.
– The public modifier indicates the class must have public accessibility.
– The void modifier indicates that main does not return a value.
– The only parameter to main is an array of strings that has commandline parameters from the user.
Classes, Objects, and Methods
• In Java, method definitions must appear in their associated
classes.
• Java does not have destructors.
• In Java, the method is dynamically bound by default.
• Objects of user-defined classes are created with new.
MyClass myObject1;
myObject1 = new MyClass();
MyClass myObject2 = new MyClass();
• Numeric variables are implicitly initialized to zero. Boolean
variables are initialized to false. Reference variables are
initialized to null.
Classes, Objects, and Methods
• Instance variables are referenced through the reference
variables that point to their associated object - for example:
Class MyClass extends Object {
public int sum;
…
}
MyClass myObject = new MyClass();
• The instance variable sum can be referenced with this:
myObject.sum
Classes, Objects, and Methods
import java.io.*;
class Stack_class {
private int [] stack_ref;
private int max_len, top_index;
public Stack_class() { // A constructor
stack_ref = new int [100];
max_len = 99;
top_index = -1;
}
public void push (int number) {
if (top_index == max_len)
System.out.println("Error in push-stack is full");
else stack_ref[++top_index] = number;
}
public void pop () {
if (top_index == -1)
System.out.println("Error in push-stack is empty");
else --top_index;
}
public int top () {return (stack_ref[top_index]);}
public boolean empty () {return (top_index == -1);}
}
Classes, Objects, and Methods
public class Tst_Stack {
public static void main (String[] args) {
Stack_class myStack = new Stack_class();
myStack.push(42);
myStack.push(29);
System.out.println("29 is: " + myStack.top());
myStack.pop();
System.out.println("42 is: " + myStack.top());
myStack.pop();
myStack.pop(); // Produces an error message
}
}
Interfaces
• Java directly supports only single inheritance. An interface can
contain only named constants and method declarations.
• Applets are programs that are interpreted by a Web browser
after being downloaded from a Web server.
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
Interfaces
html>
<head>
<title>HelloWorld Applet</title>
</head>
<body>
<center>
This is the HelloWorld Applet. <br>
<applet code = "HelloWorld.class" hidth = 150 height = 50>
</applet>
</center>
</body>
</html>
Exception Handling
• All Java exceptions are objects of classes that are descendants
of the Throwable class.
• The Java system includes two system-defined exception
classes that are subclasses of Throwable: Error and
Exception.
• There are two system-defined direct descendants of Exception:
RuntimeException and IOException.
• User-defined exceptions are subclasses of Exception.
Exception Handlers
• An instance of the exception class is given as the operand of
the throw statement.
class MyException extends Exception {
public MyException();
public MyException(String message) {
super(message);
}
}
– The first constructor does nothing
– The second sends its parameter to the parent class (specified with
super) constructor.
Exception Handlers
• The exception can be thrown with this statement:
throw new MyException();
• Creating the instance of the exception for throw can be done
separately from the throw statement.
MyException myExceptionObject = new MyException();
…
throw myExceptionObject;
• A new exception could be thrown with the following
statement.
Throw new MyException (“a message to specify the
location of the error”);
Exception Propagation
• When a handler is found in the sequence of handlers in a try
construct, that handler is executed and program execution with
the statement following the try construct.
• If none is found, the handlers of enclosing try constructs are
searched, starting from the innermost. If no handler is found,
the exception is propagated to the caller of the method.
• To ensure that exceptions thrown in a try clause are always
handled in a method, a special handler can be written that
matches all exceptions:
Catch (Exception genricObject) {
…
}
The throws Claus
• When a method specifies that it can be throw IOException, it
can throw an IOException object or an object of its
descendent.
• Exceptions of class Error and RuntimeException and their
descendants are called unchecked exceptions. All are called
checked exceptions. The compiler ensures that all checked
exceptions are either listed in its throws clause or handled in
the method.
• Java has no default handlers, and it is not possible to disable
exceptions.