Java Tutorial - bohr.wlu.ca

Java Tutorial - bohr.wlu.ca

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 1. What is Java? 2. How to get started with Java programming Install Java, Eclipse IDE Create, compile and running a Java

application 3. Java syntax 4. Basic Java programming principles The name Java Oak _ a programming language created by James Gosling in 1991 for 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 1. simple, object-oriented and familiar 2. robust and secure" 3. architecture-neutral and portable 4. high performance 5. 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 Oracles 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 HelloWorld.java 1. compiling javac HelloWorld.java bytecode 2. Running java HelloWorld HelloWorld.class

How it works Compile-time Class Loader Java HelloWorld Java Source HelloWord.java move locally or through network Java Compiler javac HelloWorld.java

Java Interpreter Just in Time Compiler Runtime System Java Bytecode HelloWorld.class Operating System Hardware

Environment Java Class Libraries Java Virtual Machine Java Development Kit javac java

- The Java Compiler - 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 1. 2. 3. 4. 5. Data types Operators Control structures Classes and objects Packages Java Data Types

Primitive data types true or 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 double 64 bit IEEE 754 floating point boolean 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; int retVal, index = 2; double gamma = 1.2; boolean valueOk = 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 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};

String Java String is a special class String myString = "Java"; int len = 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 statement if ( 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 (int i = 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 (int i = 0; i < 10; i++ ) { userID[i] = ramdom.nextInt(10000); } int i = 0; while(i != 9) { System.out.println( "ID =" + userID[i]); i++; } do { } while loop int i = 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 ( 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, 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); } 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 } 36 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 37 4. Java Classes & Methods Objected-Oriented Programming (OOP) Principles of OOP Four basic principles of OOP 1. Encapsulation

Objects hide their data (instance variables) and functions (methods) 2. Polymorphism Interface same despite different data types 3. Abstraction hide non-essential details relevant to user. 4. 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.distanceFromO rigin());

} } 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.distanceFromOri gin()); } } Need methods to get and set x, y values!!! Passing arguments to methods

Primitive types: the method gets a copy of the value. Changes wont 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 49 Passing arguments to methods int sum(int x, int y) {

x = x + y; return x; } void increment(int[] a) { for (int i=0; i < a.length; i++) { a[i]++; } } Packages You can organize a bunch of classes and interfaces into a package. defines a namespace that contains all

the classes. You need to use some java packages in your programs java.lang java.io, java.util Netprog 2002 Java Intro 51 Java test program 3 Problem: Create geometry classes, such as point, rectangles, circles.

About to create point, rectangle, circle objects Able to compute the areas and circumstances of given rectangles and circles Netprog 2002 Java Intro 52 Design Abstract class

Shape: area(); cicum(); Inheritance Inheritance Class: Rectangle double w, h area(){} circum(){} Class: Circle double r

area(){} circum() {} Inheritance Package: Geometry Class : Point x, y containing

Class: Plane Circle radius r, center C isInside Example package Geometry; // package public abstract class Shape {

public abstract double area(); // Abstract methods public abstract double circumference(); // semicolon instead of body } 54 Rectangle class package Geometry; class Rectangle extends Shape { protected double w, h; public Rectangle(double w, double h) {

this.w = w; this.h = h; } public double getWidth() { return w; } public double getHeight() { return h; } public double area() { return w*h; } public double circumference() { return 2*(w + h); } } Rectangle class package Geometry; class Circle extends Shape { public static final double PI = 3.14159265358979323846; protected double r; public Circle(double r) { this.r = r; }

public Circle() { this.r = 1.0; } public double getRadius() { return r; } public double area() { return PI*r*r; } public double circumference() { return 2*PI*r; } } Rectangle class package Geometry; public class Point { protected double x, y; public Point(double x, double y) { this.setX(x); this.setY(y); }

public Point() { this.setX(0); this.setY(0); } public double distanceFromOrigin(){ return Math.sqrt(getX()*getX() +getY()*getY()); } public void setX(double x) { this.x = x; } public double getX() { return x;

} public void setY(double y) { this.y = y; } public double getY() { return y; } } Rectangle class package Geometry; public class PlaneCircle extends Circle { protected Point center = new Point();

public PlaneCircle(double r, double x, double y) { super(r); this.center.setX(x); this.center.setY(y); } public boolean isInside(double x, double y) { double dx = x - center.getX(), dy = y - center.getY(); double distance = Math.sqrt(dx*dx + dy*dy); return (distance < r); } } Rectangle class package Geometry;

public class PlaneCircle extends Circle { protected Point center = new Point(); public PlaneCircle(double r, double x, double y) { super(r); this.center.setX(x); this.center.setY(y); } public boolean isInside(double x, double y) { double dx = x - center.getX(), dy = y - center.getY(); double distance = Math.sqrt(dx*dx + dy*dy); return (distance < r); } }

Test class package Geometry; public class GeometryTest { public static void main(String[] args) { Rectangle R = new Rectangle(2, 4); System.out.println(R.area()); System.out.println(R.circumference()); Circle C = new Circle(3); System.out.println(C.area()); System.out.println(C.circumference()); PlaneCircle PC = new PlaneCircle(1, 2, 3); System.out.println(PC.area()); System.out.println(PC.circumference()); System.out.println(Radius = +PC.getRadius()+ , center = (" +

PC.center.getX() + , " +PC.center.getY()+)); } }

Recently Viewed Presentations

  • ENGI 8926: Mechanical Design Project II

    ENGI 8926: Mechanical Design Project II

    *We are designing a downhole turbine assy because they allow the passage of fluid in the event of a stall and . Project Overview. Client: Advanced Drilling Group. Purpose: Design a downhole turbine-operated assembly to power a variety of downhole...
  • EV3 Workshop Curriculum Developed by Joe DeRose, Ph.D.

    EV3 Workshop Curriculum Developed by Joe DeRose, Ph.D.

    NXT Color Sensor. Percent Mode: 5% = lowest dark. 100% = very bright. Reflected Light Mode: shines a red light. The light can be turned off - detecting ambient light (surrounding light) We will use EV3 Experiments to test our...
  • The Aeneid An Introduction - LVV-4U1 Classical Civilizations

    The Aeneid An Introduction - LVV-4U1 Classical Civilizations

    Myth had stopped being realistic and historical and had in fact become the complete opposite, used mainly by tragedians as 'exemplum', to demonstrate their ideals [1] [2] Otis, p2 Although the Aeneid has the Odyssey and the Iliad as its...
  • Présentation PowerPoint - Capri School

    Présentation PowerPoint - Capri School

    A 169, 103 (1992) Quantum corrections to Drude conductance (weak localization, UCF) Drude conductance Shot noise spectrum Quantum correction to shot noise Fano factors for metallic diffusive wire or for chaotic (many) channel cavity give no information on long range...
  • Looking Glass Self - Weebly

    Looking Glass Self - Weebly

    Looking Glass Self. Charles H. Cooley's term to explain how others influence the way we see ourselves. Film 1: Palin Interview Film 2: SNL Interview Spoof . Film 3:
  • Materials - DTOTW

    Materials - DTOTW

    Either way a table like this has to be remembered - and that is much easier to do if you understand what the differences between two named materials is - and that comes from knowing how the structure of hardwoods...
  • Volumetric Analysis - Weebly

    Volumetric Analysis - Weebly

    Volumetric Analysis Volumetric Analysis Volumetric analysis is the method of finding out the concentration of a solution. For example: Adding a solution of acid to a solution of base, in a measured way, until you have added enough to neutralise...
  • Procesamiento Post-traduccional - UNAM

    Procesamiento Post-traduccional - UNAM

    Important is especially the fact that such networks fit with their concave side tightly to membranes, for example to the inner surface of the plasmalemma. The growing network provides the mechanical force to pull the membrane into a bud. This...