A Brief Introduction to Java Chin-Chih Chang. Overview of Java In comparison with C++ –Based on C++ –Support for object-oriented programming –No user-defined.

Slides:



Advertisements
Similar presentations
Java Language Quick-Reference Guide B. Oracle10g: Java Programming B - 2 Console Output Java applications and applets can output simple messages to the.
Advertisements

CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
A Brief Introduction to Java Programming the World Wide Web.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
Abstract data types & object-oriented paradigm. Abstraction Abstraction: a view of an entity that includes only the attributes of significance in a particular.
COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004.
Lecture 9 Concepts of Programming Languages
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Programming Languages and Paradigms Object-Oriented Programming.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
Java and C++, The Difference An introduction Unit - 00.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Copyright Curt Hill Variables What are they? Why do we need them?
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Object Oriented Programming Lecture 2: BallWorld.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
JAVA MULTIPLE CHOICE QUESTION.
Abstract Data Types and Encapsulation Concepts
Yanal Alahmad Java Workshop Yanal Alahmad
Java Programming Language
University of Central Florida COP 3330 Object Oriented Programming
Objects, Classes, Program Constructs
I/O Basics.
Lecture 9 Concepts of Programming Languages
Introduction to Programming in Java
Starting JavaProgramming
Abstract Data Types and Encapsulation Concepts
Java Programming Language
Chap 2. Identifiers, Keywords, and Types
Exception Handling and Event Handling
Lecture 9 Concepts of Programming Languages
Presentation transcript:

A Brief Introduction to Java Chin-Chih Chang

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.

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

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

Switch Conditions Example switch (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."); }

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

While Loops Format: while (condition) { bodyOfLoop; } Example: int count = 0; while ( count < array1.length && array1[count] !=0) { array2[count] = (float) array1[count++]; }

Do.. While Loops Format do { bodyOfLoop; } while (condition); Example int x = 1; do { System.out.println("Looping, round " + x); x++; } while (x <= 10);

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

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

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 command- line 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 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); }

Applets HelloWorld Applet This is the HelloWorld Applet.

Input/Output SourceExample of SourceClassResult Disk fileFile (“file.data”)FileInputStream FileOutputStream Stream of bytes Disk fileFile (“file.data”)FileReaderStream of chars Stream of bytesFileInputStream FileOutputStream InputStreamReader PrintStream Stream of chars InputStreamReaderBufferedReaderLines of strings

Input/Output import 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(); }

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.