33
A Brief Introduction to Java 1

A Brief Introduction to Java

Embed Size (px)

DESCRIPTION

A Brief Introduction to Java. 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. - PowerPoint PPT Presentation

Citation preview

Page 1: A Brief Introduction to Java

1

A Brief Introduction to Java

Page 2: A Brief Introduction to Java

2

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.

Page 3: A Brief Introduction to Java

3

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.

Page 4: A Brief Introduction to Java

4

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.

Page 5: A Brief Introduction to Java

5

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 youYou should eat 7 apples each weekGrapes are good, too

Page 6: A Brief Introduction to Java

6

Data Types and Structures• Java has only one way to reference an object through a

reference variable.• The Java primitive types are boolean, byte, char, double,

float, int, long, and short.• 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);

Page 7: A Brief Introduction to Java

7

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;

Page 8: A Brief Introduction to Java

8

Control Flow

• Almost identical that of C language: if-else, do-while, for, while, switch, break and continue, etc.

• No infamous goto • Unlike C, we can define any local variable anywhere

in methods • Block scope - define the scope of your variable, can

be nested

Page 9: A Brief Introduction to Java

9

Switch Conditions• Format:switch (test) { case valueOne: resultOne; break; case valueTwo: resultTwo; break; case valueThree: resultThree; break; ... default: defaultresult; }

Page 10: A Brief Introduction to Java

10

Switch Conditions

• Exampleswitch (x) {

case 2:

case 4:

case 6:

case 8:

System.out.println("x is an even number."); break; default:

System.out.println("x is an odd number.");

}

Page 11: A Brief Introduction to Java

11

While Loops

• Format:

while (condition) { bodyOfLoop; }

• Example:int count = 0; while ( count < array1.length && array1[count] !=0) {

array2[count] = (float) array1[count++];

}

Page 12: A Brief Introduction to Java

12

Do .. While Loops

• Formatdo { bodyOfLoop; } while (condition);• Exampleint x = 1;

do {

System.out.println("Looping, round " + x); x++;

} while (x <= 10);

Page 13: A Brief Introduction to Java

13

For Loops

• Format:for (initialization; test; increment) { statements; }

• Multiple Initializers and Incrementers • Example:

for (int i = 1, j = 100; i < 100; i = i+1, j = j-1) { System.out.println(i + j); }

• for (type var : arr) { body-of-loop }for (int i : a) { total += i; }

Page 14: A Brief Introduction to Java

14

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.

Page 15: A Brief Introduction to Java

15

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.

Page 16: A Brief Introduction to Java

16

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.

Page 17: A Brief Introduction to Java

17

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, that is

any method that must be invoked with respect to an instance of a class.

– The abstract modifier specifies that the method is not defined in the class.

– The final modifier specifies that the method cannot be overridden.

Page 18: A Brief Introduction to Java

18

Classes, Objects, and Methods• Static methods are allocated when the class is loaded and

invoked through the class but not an instance of a class.• 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 static variable or method in a package can be specified in

the following way:

weatherpkg.WeatherData.avgTemp

Page 19: A Brief Introduction to Java

19

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.*;

Page 20: A Brief Introduction to Java

20

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 command-

line parameters from the user.

Page 21: A Brief Introduction to Java

21

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.

Page 22: A Brief Introduction to Java

22

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

Page 23: A Brief Introduction to Java

23

Classes, Objects, and Methodsimport 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);}}

Page 24: A Brief Introduction to Java

24

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 }}

Page 25: A Brief Introduction to Java

25

Interfaces and Applets

• Java 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);

}

}

Page 26: A Brief Introduction to Java

26

Applets<html><head><title>HelloWorld Applet</title></head><body><center>This is the HelloWorld Applet. <br><applet code = "HelloWorld.class" width = 150 height = 50></applet></center></body></html>

Page 27: A Brief Introduction to Java

27

Input/Output

Source Example of Source Class Result

Disk file File (“file.data”) FileInputStreamFileOutputStream

Stream of bytes

Disk file File (“file.data”) FileReader Stream of chars

Stream of bytes FileInputStreamFileOutputStream

InputStreamReaderPrintStream

Stream of chars

Stream of chars InputStreamReader BufferedReader Lines of strings

Page 28: A Brief Introduction to Java

28

Input/Outputimport java.io.*;

public class DisplayFile { public static void main (String[] args) throws Exception {

BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream(args[0]))); BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in)); String line;

System.out.print("Output File Name: "); line = keyboard.readLine(); PrintStream out = new PrintStream (new FileOutputStream(line));

while((line = in.readLine()) != null) { System.out.println(line); out.println(line); } in.close(); out.close(); }}

Page 29: A Brief Introduction to Java

29

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.

Page 30: A Brief Introduction to Java

30

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.

Page 31: A Brief Introduction to Java

31

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

Page 32: A Brief Introduction to Java

32

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

Page 33: A Brief Introduction to Java

33

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.