600 likes | 780 Views
Introduction to Java. Write Once, Run Anywhere Speaker: Dr. Hongbing Fan Department of Physics & Computer Science Wilfrid Laurier University Waterloo, ON. Canada http://bohr.wlu.ca/hfan/java/intro_to_java_acse2011.html. One hour on Java. What is Java?
E N D
Introduction to Java Write Once, Run Anywhere Speaker: Dr. Hongbing FanDepartment of Physics & Computer ScienceWilfrid Laurier UniversityWaterloo, ON. Canadahttp://bohr.wlu.ca/hfan/java/intro_to_java_acse2011.html
One hour on Java • What is Java? • How to get started with Java programming • Install Java, Eclipse IDE • Create, compile and running a Java application • Java syntax • Basic Java programming principles
The name Java • Oak _ a programming language created by James Gosling in 1991for Sun Microsystems set-top box project • Oak was renamed Java in 1994
What Java really is • a platform independent programming language • similar to C++ in syntax
Why Java It was designed by five primary principles • simple, object-oriented and familiar • robust and secure" • architecture-neutral and portable • high performance • Interpreted, threaded, and dynamic The most popular programming language
A live, actively evolving JDK 1.0 (January 23, 1996) JDK 1.1 (February 19, 1997) J2SE 1.2 (December 8, 1998) J2SE 1.3 (May 8, 2000) J2SE 1.4 (February 6, 2002) J2SE 5.0 (September 30, 2004) Java SE 6 (December 11, 2006) Java SE 7 (July 28, 2011)
2. How to install Java • Download Java from Oracle’s site http://www.oracle.com/technetwork/java/javase/downloads/index.html • Download Eclipse from http://www.eclipse.org/ Eclipse is the most popular Java IDE (Integrated Development Environment ) • Other Java IDE • Netbeans, BlueJ, Jcreator, IntelliJ, Dr. Java, …
Fist test Java program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); } }
Compiling and Running 1. compilingjavacHelloWorld.java HelloWorld.java bytecode 2. Running java HelloWorld HelloWorld.class
Java Interpreter Just in Time Compiler How it works Compile-time Environment Class Loader Java HelloWorld Java Class Libraries Java Source HelloWord.java move locally or through network Java Compilerjavac HelloWorld.java Java Virtual Machine Runtime System Java Bytecode HelloWorld.class Operating System Hardware
Java Development Kit • javac - The Java Compiler • java - The Java Interpreter • jdb - The Java Debugger • appletviewer - Tool to run the applets • javap - to print the Java bytecodes • javaprof - Java profiler • javadoc - documentation generator • javah - creates C header files
3. Basic Java Syntax Language Data types Operators Control structures Classes and objects Packages
Java Data Types • Primitive data types • boolean trueor false • char unicode! (16 bits) • byte signed 8 bit integer • short signed 16 bit integer • int signed 32 bit integer • long signed 64 bit integer • float, 32 bit • double64 bit IEEE 754 floating point
Other Data Types • Reference types (composite) • classes • arrays • strings are supported by a built-in class named String • string literals are supported by the language
Variables & initialization • Declaring primitive variables float initVal; intretVal, index = 2; double gamma = 1.2; booleanvalueOk = false;
Complex types int[] five ={0, 1, 2, 3, 4}; // array String hello = “Hello world\n”; // String Object my_obj = new Object(); //object
Declaring Arrays intmyArray[]; 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] intmyArray[] = 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 intmyArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
String • Java String is a special class String myString = "Java"; intlen = myString.length(); System.out.println(len); System.out.println(myString.toUpperCase());
Arrays of Objects • Array of Strings String[] languages ={"Java","C","C++","Python","What else?"}; for(i=0;i<5;i++){ System.out.println(languages[i]); }
Operators • Assignment: =, +=, -=, *=, … • Numeric: +, -, *, /, %, ++, --, … • Relational: ==, !=, <, >, <=, >=, … • Boolean: &&, ||, ! • Bitwise: &, |, ^, ~, <<, >>, …
Math operators and expression double myVal = a + b % d – c * d / b; Or double myVal = (a + (b % d)) – ((c * d) / b);
Statements & Blocks • A simple statement is a command terminated by a semi-colon: string name = “Fred”; • A block is a compound statement enclosed in curly brackets: { name1 = “Fred”; name2 = “Bill”; } Blocks may contain other blocks
Control Structures • conditional: if, if else, switch • loop: while, for, do • Escapes: break, continue, return
If – The Conditional Statement • The if statementif ( x < 10 ) x = 10; Or if ( x < 10 ) { x = 10; } • Or statements in a selection if ( x < 10 ) { x = 10; y = 15; }
If… else if (x != oldx) { System.out.print(“x was changed”); } else { System.out.print(“x is unchanged”); }
else if if ( n == 1 ) { // execute code block #1 } else if ( j == 2 ) { // execute code block #2 } else { // if all previous tests have failed, execute code block #3 }
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 int sum = 0, n = 10; for (inti = 0; i < n; n++ ) { sum += i; } double[][] mat = new double[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++){ if (i == j) mat[i][j]= 1; else mat[i][j]= 0; } }
while loops Random ramdom = new Random(); int[] userID = new int[10]; for (inti = 0; i < 10; i++ ) { userID[i] = ramdom.nextInt(10000); } inti = 0; while(i != 9) { System.out.println( "ID =" + userID[i]); i++; }
do {… } while loop inti = 0; do { System.out.println( "ID =" + userID[i]); i++; } while (i != 9);
Break • A break statement causes an exit from the innermost containing while, do, for or switch statement. for ( inti = 0; i < maxID, i++ ) { if ( userID[i] == targetID ) { index = i; break; } } // program jumps here after break
Continue • Can only be used with while, do, for. • The continue statement causes the innermost loop to start the next iteration immediately for ( inti = 0; i < maxID; i++ ) { if ( userID[i] != -1 ) continue; System.out.print( “UserID ” + i + “ :” + userID); }
Second Java example: Factorial From Java in a Nutshell public class Factorial { // Define a class public static void main(String[] args) { // The program starts here // int input = Integer.parseInt(args[0]); // Get the user's input int input = 10; int result = factorial(input); // Compute the factorial System.out.println(result); // Print out the result } // The main() method ends here public static int factorial(int x) { // This method computes x! if (x < 0) // Check for bad input return 0; // if bad, return 0 int fact = 1; // Begin with an initial value while(x > 1) { // Loop until x equals 1 fact = fact * x; // multiply by x each time x = x - 1; // and then decrement x } // Jump back to the star of loop return fact; // Return the result } // factorial() ends here }
Syntax Notes • No global variables • class variables and methods may be applied to any instance of an object • methods may have local (private?) variables • No pointers • but complex data objects are “referenced”
4. Java Classes & MethodsObjected-Oriented Programming (OOP)
Principles of OOP • Four basic principles of OOP • Encapsulation • Objects hide their data (instance variables) and functions (methods) • Polymorphism • Interface same despite different data types • Abstraction • hide non-essential details relevant to user. • Inheritance • Each subclass inherits all variables of its superclass
Classes ARE Object Definitions • Code is built from objects • Everything is encapsulated in a class! • A class is blueprint of an object • describes some data objects, and the methods that can be applied to those data objects • An object is an instantiation of a class.
String class and object public class StringDemo{ public static void main(String args[]){ char[] helloArray = {'h','e','l','l','o'}; String helloString = new String(helloArray);//create a new object of the string class System.out.println( helloString ); } }
How to create our own class • Each class definition is coded in a separate .java file • Name of the object must match the class/object name
Example public class Point { public double x, y; //data public Point(double x, double y) { this.x = x; this.y = y; } // constructor, a special method public double distanceFromOrigin(){ return Math.sqrt(x*x+y*y); } // a method to calculate length }
Create an object (instance) public class PointDriver { public static void main(String[] args) { Point myPoint = new Point(1, 1); double distance; distance = myPoint.distanceFromOrigin(); System.out.println(distance); } }
Change data of an object public class PointDriver { public static void main(String[] args) { Point myPoint = new Point(1, 1); myPoint.x = 3; myPoint.y = 4; System.out.println(myPoint.distanceFromOrigin()); } }
Public/private • Methods/data may be declared public or private meaning they may or may not be accessed by code in other classes … • Good practice: • keep data private • keep most methods private • well-defined interface between classes - helps to eliminate errors
Example public class Point { private double x, y; //private data public Point(double x, double y) { this.x = x; this.y = y; } // constructor, a special method public double distanceFromOrigin(){ return Math.sqrt(x*x+y*y); } // a method to calculate length }
Will work with private x and y public class PointDriver { public static void main(String[] args) { Point myPoint = new Point(1, 1); myPoint.x = 3; myPoint.y = 4; System.out.println(myPoint.distanceFromOrigin()); } } Need methods to get and set x, y values!!!
Passing arguments to methods • Primitive types: the method gets a copy of the value. Changes won’t show up in the caller. • Reference types: the method gets a copy of the reference, the method accesses the same object! Netprog 2002 Java Intro
Passing arguments to methods int sum(int x, int y) { x = x + y; return x; } void increment(int[] a) { for (inti=0; i < a.length; i++) { a[i]++; } }