Java is an object-oriented programming language that is platform independent. It is compiled to bytecode that can run on any Java Virtual Machine (JVM), allowing code to run on any device. The document provides an overview of Java concepts including classes and objects, methods, variables and data types, flow control, and arrays. It also discusses how Java code is compiled and run, with bytecode being executed by the JVM and just-in-time compilers attempting to increase speed.
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0 ratings0% found this document useful (0 votes)
102 views76 pages
Java Tutorial: Write Once, Run Anywhere
Java is an object-oriented programming language that is platform independent. It is compiled to bytecode that can run on any Java Virtual Machine (JVM), allowing code to run on any device. The document provides an overview of Java concepts including classes and objects, methods, variables and data types, flow control, and arrays. It also discusses how Java code is compiled and run, with bytecode being executed by the JVM and just-in-time compilers attempting to increase speed.
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 76
Java Tutorial
Write Once, Run Anywhere
Java - General Java is: platform independent programming language similar to C++ in syntax Compile-time Environment Compile-time Environment Java Bytecodes move locally or through network Java Source (.java) Java Compiler Java Bytecode (.class ) Java Interpreter Just in Time Compiler Runtime System Class Loader Bytecode Verifier Java Class Libraries Operating System Hardware Java Virtual machine How it works! How it works! Java is independent only for one reason: Only depends on the Java Virtual Machine (JVM), code is compiled to bytecode, which is interpreted by the resident JVM, JIT (just in time) compilers attempt to increase speed. Object-Oriented Java supports OOD Polymorphism Inheritance Encapsulation Java programs contain nothing but definitions and instantiations of classes Everything is encapsulated in a class! Java Advantages Portable - Write Once, Run Anywhere Security has been well thought through Robust memory management Designed for network programming Multi-threaded (multiple simultaneous tasks) Dynamic & extensible (loads of libraries) Classes stored in separate files Loaded only when needed Basic Java Syntax Primitive Types and Variables boolean, char, byte, short, int, long, float, double etc. These basic (or primitive) types are the only types that are not objects (due to performance issues). This means that you dont use the new operator to create a primitive variable. Declaring primitive variables: float initVal; int retVal, index = 2; double gamma = 1.2, brightness boolean valueOk = false; Initialisation If no value is assigned prior to use, then the compiler will give an error Java sets primitive variables to zero or false in the case of a boolean variable All object references are initially set to null An array of anything is an object Set to null on declaration Elements to zero false or null on creation Declarations int index = 1.2; // compiler error boolean retOk = 1; // compiler error double fiveFourths = 5 / 4; // no error! float ratio = 5.8f; // correct double fiveFourths = 5.0 / 4.0; // correct
1.2f is a float value accurate to 7 decimal places. 1.2 is a double value accurate to 15 decimal places. All Java assignments are right associative int a = 1, b = 2, c = 5 a = b = c System.out.print( a= + a + b= + b + c= + c)
What is the value of a, b & c Done right to left: a = (b = c); Assignment Statements & Blocks A simple statement is a command terminated by a semi-colon: name = Fred; A block is a compound statement enclosed in curly brackets: { name1 = Fred; name2 = Bill; } Blocks may contain other blocks Flow of Control Java executes one statement after the other in the order they are written Many Java statements are flow control statements: Alternation: if, if else, switch Looping: for, while, do while Escapes: break, continue, return
If The Conditional Statement The if statement evaluates an expression and if that evaluation is true then the specified action is taken if ( x < 10 ) x = 10; If the value of x is less than 10, make x equal to 10 It could have been written: if ( x < 10 ) x = 10; Or, alternatively: if ( x < 10 ) { x = 10; } Relational Operators == Equal (careful) != Not equal >= Greater than or equal <= Less than or equal > Greater than < Less than If else The if else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false. if (x != oldx) { System.out.print(x was changed); } else { System.out.print(x is unchanged); } Nested if else if ( myVal > 100 ) { if ( remainderOn == true) { myVal = mVal % 100; } else { myVal = myVal / 100.0; } } else { System.out.print(myVal is in range); } The switch Statement switch ( n ) { case 1: // execute code block #1 break; case 2: // execute code block #2 break; default: // if all previous tests fail then //execute code block #4 break; } The for loop Loop n times for ( i = 0; i < n; n++ ) { // this code body will execute n times // ifrom 0 to n-1 } Nested for: for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } }
while loops while(response == 1) { System.out.print( ID = + userID[n]); n++; response = readInt( Enter ); }
What is the minimum number of times the loop is executed? What is the maximum number of times? do { } while loops do { System.out.print( ID = + userID[n] ); n++; response = readInt( Enter ); }while (response == 1); What is the minimum number of times the loop is executed? What is the maximum number of times? Break A break statement causes an exit from the innermost containing while, do, for or switch statement. for ( int i = 0; i < maxID, i++ ) { if ( userID[i] == targetID ) { index = i; break; } } // program jumps here after break Continue Can only be used with while, do or for. The continue statement causes the innermost loop to start the next iteration immediately for ( int i = 0; i < maxID; i++ ) { if ( userID[i] != -1 ) continue; System.out.print( UserID + i + : + userID); } Arrays An array is a list of similar things An array has a fixed: name type length These must be declared when the array is created. Arrays sizes cannot be changed during the execution of the code myArray has room for 8 elements the elements are accessed by their index in Java, array indices start at 0 3 6 3 1 6 3 4 1 myArray = 0 1 2 3 4 5 6 7 Declaring Arrays int myArray[]; declares myArray to be an array of integers myArray = new int[8]; sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7] int myArray[] = new int[8]; combines the two statements in one line
Assigning Values refer to the array elements by index to store values in them. myArray[0] = 3; myArray[1] = 6; myArray[2] = 3; ... can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
Iterating Through Arrays for loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length; i++) { myArray[i] = getsomevalue(); }
Java Methods & Classes Classes ARE Object Definitions OOP - object oriented programming code built from objects Java these are called classes Each class definition is coded in a separate .java file Name of the object must match the class/object name The three principles of OOP Encapsulation Objects hide their functions (methods) and data (instance variables) Inheritance Each subclass inherits all variables of its superclass Polymorphism Interface same despite different data types
car auto- matic manual Super class Subclasses draw() draw() Simple Class and Method Class Fruit{ int grams; int cals_per_gram;
int total_calories() { return(grams*cals_per_gram); } } Methods A method is a named sequence of code that can be invoked by other Java code. A method takes some parameters, performs some computations and then optionally returns a value (or object). Methods can be used as part of an expression statement.
Method Signatures A method signature specifies: The name of the method. The type and name of each parameter. The type of the value (or object) returned by the method. The checked exceptions thrown by the method. Various method modifiers. modifiers type name ( parameter list ) [throws exceptions ] public float convertCelsius (float tCelsius ) {} public boolean setUserInfo ( int i, int j, String name ) throws IndexOutOfBoundsException {} What is an object? Object is a thing An object has state, behavior and identity Internal variable: store state Method: produce behavior Unique address in memory: identity An object is a manifestation of a class What is class? Class introduces a new data type A class describes a set of objects that have identical characteristics (data elements) and behaviors (methods). Existing classes provided by JRE User defined classes Once a class is established, you can make as many objects of it as you like, or none. Simple example: class Person A Person has some attributes The class defines these properties for all people Each person gets his own copy of the fields Attributes = properties = fields Class Person: definition class Person { String name; int height; //in inches int weight; //in pounds public void printInfo(){ System.out.println(name+" with height="+height+", weight="+weight); } } class ClassName{ /* class body goes here */ } class: keyword Class Person: usage Person ke; //declaration ke = new Person(); //create an object of Person ke.name= Ke Wang; //access its field Person sal = new Person(); sal.name=Salvatore J. Stolfo; ke.printInfo(); Sal.printInfo(); // error here?? Class Person Name: Ke Wang height: 0 weight: 0 Name: Salvatore J. Stolfo height: 0 weight: 0 ke sal Class Person: variables Person x; x=ke; x.printInfo(); x=sal; x.printInfo(); This gives the same output as previous code ! Class Person: variables Name: Ke Wang height: 0 weight: 0 Name: Salvatore J. Stolfo height: 0 weight: 0 ke sal x references objects Reference We call x, as well as ke and sal, reference to the object Handles to access an object Reference itself is not accessible/manipulable Different from C/C++, cannot increment/decrement it Implemented as pointer+ Java runtime is watching all assignment to references Why? garbage collection (later) Reference Person ke; //only created the reference, not an object. It points to nothing now (null). ke = new Person(); //create the object (allocate storage in memory), and ke is initialized. ke.name=Ke Wang; //access the object through the reference More on reference Have distinguished value null, meaning pointing to nothing if( x==null) { } Multiple references can point to one object When no reference point to an object, that object is never accessible again. Class Person: problem ke.weight = 150; // too bad, but possible ke.weight = -20; // Houston, we have a problem!! Need to ensure the validity of value. Solution: ask the class to do it! ke.setWeight(150); // OK, now kes weight is 150 ke.setWeight(-10); ******** Error, weight must be positive number Class Person: add method class Person{ ... void setWeight(int w){ if(w<=0) System.err.println("***** error, weight must be positive number! "); else weight = w; } } Class Person: new problem ke.setWeight(-10); ******** Error, weight must be positive number ke.weight = -20; //haha, Im the boss! How about we forgot to use the set function? Or we just dont want to? Solution: just make the variable inaccessible from outside! Class Person class Hello{
public static void main ( String[] args ) { Person ke = new Person(); ke.weight = -20; } } >javac Hello.java Hello.java:5: weight has private access in Person ke.weight = -20; ^ 1 error Access functions Generally make fields private and provide public getField() and setField() access functions O-O term for this is Encapsulation C# does this by default copy Primitive types get copied directly by = int x= 10; int y=x; Objects and arrays just copy the reference, still only one copy of the object existing. Name: Ke Wang height: 0 weight: 0 ke x Person ke =new Person(); ke.name="Ke Wang"; Person x=ke; x.name="Sal"; System.out.println(ke.name); // print Sal! Static keyword Want to have only one piece of storage for a data, regardless how many objects are created, or even no objects created Need a method that isnt associated with any particular object of this class static keyword apply to both fields and methods Can be called directly by class name Example: java.lang.Math Non-static fields/methods must be called through an instance Constructor Constructor has the same name as that of a class but no return type. Default Constructor is a no-argument constructor automatically generated by the compiler. If we define a constructor for a given class then the compiler doesnt generate the default constructor.
Final keyword Final can be declared at class level, method level, variable level. Final variable implies constant Final method cannot be overridden Final class cannot be extended. Access Modifiers In Java code, class and variable and method and constructor declarations can have access specifiers, that is one of: private, protected, public. (or none.) I) Class level access modifiers (java classes only) Only two access modifiers is allowed, public and no modifier If a class is public, then it CAN be accessed from ANYWHERE. If a class has no modifer, then it CAN ONLY be accessed from same package.
Access Modifiers II) Member level access modifiers (java variables and java methods) All the four public, private, protected and no modifer is allowed. public and no modifier the same way as used in class level. private members CAN ONLY access. protected CAN be accessed from same package and a subclass existing in any package can access.
Access Modifiers
Access Modifiers Same Class Same Package Subclass Other packages public Y Y Y Y protected Y Y Y N no access modifier Y Y N N private Y N N N For better understanding, member level access is formulated as a table:
First row {public Y Y Y Y} should be interpreted as: Y A member declared with public access modifier CAN be accessed by the members of the same class. Y A member declared with public access modifier CAN be accessed by the members of the same package. Y A member declared with public access modifier CAN be accessed by the members of the subclass. Y A member declared as public CAN be accessed from Other packages. Second row {protected Y Y Y N} should be interpreted as: Y A member declared with protected access modifier CAN be accessed by the members of the same class. Y A member declared with protected access modifier CAN be accessed by the members of the same package. Y A member declared with protected access modifier CAN be accessed by the members of the subclass. N A member declared with protected access modifier CANNOT be accessed by the members of the Other package. Inheritance An object acquiring the properties of another is knows an inheritance. A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). Every class has one and only one direct superclass (single inheritance). Inheritance What You Can Do in a Subclass A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members: The inherited fields can be used directly, just like any other fields. You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). You can declare new fields in the subclass that are not in the superclass. The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. You can declare new methods in the subclass that are not in the superclass. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. Interfaces In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiatedthey can only be implemented by classes or extended by other interfaces. To use an interface, you write a class that implements the interface. Abstract Classes An abstract class is a class that is declared abstractit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be sub classed. An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: public abstract String move(); Abstract Classes versus Interfaces Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead. Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example. Exception Handling An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory..
To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Exception Handling Keywords: Try, catch: A try/catch block is placed around the code that might generate an exception.
Finally: A finally block of code always executes, whether or not an exception has occurred.
Throw: In order to explicitly throw an exception.
Throws: If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. Collections Framework The Collections Framework is made up of a set of interfaces for working with groups of objects. The following diagram shows the framework interface hierarchy.
When designing software with the Collections Framework, it is useful to remember the following hierarchical relationships of the four basic interfaces of the framework: The Collection interface is a group of objects, with duplicates allowed Set extends Collection but forbids duplicates List extends Collection also, allows duplicates and introduces positional indexing Map extends neither Set nor Collection.
Collections Framework Moving on to the framework implementations, the concrete collection classes follow a naming convention, combining the underlying data structure with the framework interface. The following table shows the six collection implementations introduced with the Java 2 framework, in addition to the four historical collection classes. For information on how the historical collection classes changed, like how Hashtable was reworked into the framework
There are no implementations of the Collection interface. The historical collection classes are called such because they have been around since the 1.0 release of the Java class libraries. If you are moving from the historical collection classes to the new framework classes, one of the primary differences is that all operations are unsynchronized with the new classes. While you can add synchronization to the new classes, you cannot remove it from the old.
Interface Implementation Historical Set HashSet TreeSet List ArrayList LinkedList Vector Stack Map HashMap TreeMap Hashtable Properties 66 What is JDBC? An API that lets you access virtually any tabular data source from the Java programming language JDBC Data Access API JDBC Technology Homepage Whats an API? See J2SE documentation Whats a tabular data source? access virtually any data source, from relational databases to spreadsheets and flat files. JDBC Documentation Well focus on accessing Oracle databases 67 General Architecture What design pattern is implied in this architecture? What does it buy for us? Why is this architecture also multi-tiered? 68 69 Basic steps to use a database in Java 1.Establish a connection 2.Create JDBC Statements 3.Execute SQL Statements 4.GET ResultSet 5.Close connections
70 1. Establish a connection import java.sql.*; Load the vendor specific driver Class.forName("oracle.jdbc.driver.OracleDriver"); What do you think this statement does, and how? Dynamically loads a driver class, for Oracle database Make the connection Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@oracle-prod:1521:OPROD", username, passwd); What do you think this statement does? Establishes connection to database by obtaining a Connection object
71 2. Create JDBC statement(s) Statement stmt = con.createStatement() ; Creates a Statement object for sending SQL statements to the database 72 Executing SQL Statements String createLehigh = "Create table Lehigh " + "(SSN Integer not null, Name VARCHAR(32), " + "Marks Integer)"; stmt.executeUpdate(createLehigh); //What does this statement do?
String insertLehigh = "Insert into Lehigh values + "(123456789,abc,100)"; stmt.executeUpdate(insertLehigh);
73 Get ResultSet String queryLehigh = "select * from Lehigh";
ResultSet rs = Stmt.executeQuery(queryLehigh); //What does this statement do?
while (rs.next()) { int ssn = rs.getInt("SSN"); String name = rs.getString("NAME"); int marks = rs.getInt("MARKS"); } 74 Close connection stmt.close(); con.close(); 75 Transactions and JDBC JDBC allows SQL statements to be grouped together into a single transaction Transaction control is performed by the Connection object, default mode is auto-commit, I.e., each sql statement is treated as a transaction We can turn off the auto-commit mode with con.setAutoCommit(false); And turn it back on with con.setAutoCommit(true); Once auto-commit is off, no SQL statement will be committed until an explicit is invoked con.commit(); At this point all changes done by the SQL statements will be made permanent in the database. 76 Handling Errors with Exceptions Programs should recover and leave the database in a consistent state. If a statement in the try block throws an exception or warning, it can be caught in one of the corresponding catch statements How might a finally {} block be helpful here? E.g., you could rollback your transaction in a catch { } block or close database connection and free database related resources in finally {} block