java lecture1 introduction
TRANSCRIPT
-
8/6/2019 Java Lecture1 Introduction
1/54
1
Object Oriented Programmingwith
JAVA
References:Java JDK6 documentations. http://java.sun.com/javase/
Java How to Program, Sixth Edition
Instructor: Haya Sammaneh
-
8/6/2019 Java Lecture1 Introduction
2/54
2
History of Java
Java
Originally for intelligent consumer-electronic
devices (cell phones)
Then used for creating Web pages with dynamic
content
Now also used for:
Develop large-scale enterprise applications
-
8/6/2019 Java Lecture1 Introduction
3/54
3
The Java Programming Language
A high-level language that can be characterized by all of thefollowing:
Simple Object oriented
Portable
Distributed
High performance
Multithreaded
Robust
Secure
-
8/6/2019 Java Lecture1 Introduction
4/54
4
Java life cycle Java programs normally undergo four phases
Edit
Programmerwritesprogram (and stores program on
disk)
Compile Compiler creates bytecodes from program (.class)
Load
Class loaderstores bytecodes in memory
Execute
Interpreter: translates bytecodes into machine language
-
8/6/2019 Java Lecture1 Introduction
5/54
5
Java life cycle
Source code (.java)
Compiled into Byte codes (.class) , as (.exe) in c++
The Java Application Programming Interface
(API)
a large collection of ready-made software components. It isgrouped into libraries of related classes and interfaces;these libraries are known aspackages.
Java Virtual Machine (JVM)
Machine code
-
8/6/2019 Java Lecture1 Introduction
6/54
6
Java life, cont..
-
8/6/2019 Java Lecture1 Introduction
7/54
7
JVM an Portability Through the Java VM, the same application is
capable ofrunning on multiple platforms.
-
8/6/2019 Java Lecture1 Introduction
8/54
8
Java Technology
Java EE vs.
Java SE
EE: enterprise edition (web services, distribution, RMI, )
SE: standard edition (stand alone app.)
D
evelopment Tools The main tools you'll be using are thejavac compiler, thejava launcher (java), and thejavadoc documentation tool.
Application Programming Interface (API)
Java SE Development Kit 6 (JDK 6)
Offers a wide array of useful classes ready for use in yourown applications.
-
8/6/2019 Java Lecture1 Introduction
9/54
9
Java Technology, cont
UserInterface Toolkits
Swing and Java 2D toolkits to create GraphicalUserInterfaces (GUIs).
Integration Libraries
Application Programming Interface (API)
Java RMI, and Java Remote Method InvocationoverInternet Inter-ORB Protocol Technology(Java RMI-IIOP Technology) enable databaseaccess.
-
8/6/2019 Java Lecture1 Introduction
10/54
10
Before you startInstall the Java SE Development
Kit 6 (JDK 6).
Modify the Java Path environment. Go to the System Properties by right
clicking you My Computer andchoosing properties Environmentvariablesclick on TEMP Edit.
Add the path to the javabin directory asshown in the next slid.
Install the Textpad editorwhichwe will use to develop ourapplications.
-
8/6/2019 Java Lecture1 Introduction
11/54
11
Modifying the Path Environment variable.
-
8/6/2019 Java Lecture1 Introduction
12/54
12
Hello world
To begin you need a text editor. Notepad, TextPad,
Create a new directory on C: name it JavaProjects.
Open new file, save it as HelloWorld.java in new directoryHelloWorld inside the JavaProjects Directory.
Write the following code and save the file:
class HelloWorld {
/*simple java application*/
public static void main(String[] args) {
System.out.println(Hello World); //displays a string }
}
Note: the file name should have the same name as the class
-
8/6/2019 Java Lecture1 Introduction
13/54
13
Compiling and running Assuming the HelloWorld.java is saved in the c:\JavaProjects\HelloWorld
directory:
Open the a Console, (startRun), type cmd.
Type cd \ to return to c:>
Go to the helloworld directry (cd c:\JavaProjects\HelloWorld)
compile your application
javac HelloWorld.java
Run your application
java HelloWorld.class
Note: Type all code, commands, and file names exactly as shown. Both the
compiler (javac) and launcher (java) are case-sensitive
-
8/6/2019 Java Lecture1 Introduction
14/54
14
Closer Look Three primary components: source code comments, the
HelloWorld class definition, and the main method.
Comments are ignored by the compiler but are useful to otherprogrammers.
Two supported kinds of comments
/* text */ The compiler ignores everything from /* to */.
// text The compiler ignores everything from // to the end of the
line.
The most basic form of a class definition is
class name {}
Every program must have at least one class, and this class shouldcontain the main method.
-
8/6/2019 Java Lecture1 Introduction
15/54
15
Closer Look, cont
In the Java programming language, every application mustcontain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order(publicstatic or static public).
You can name the argument anything you want, but most programmers
choose "args" or "argv.
This is the string array that will contains the command linearrguments.
The main method is the entry point for your application and will
subsequently invoke all the other methods required by your program.
System.out.println("Hello World!");
uses the System class from the API to print the "Hello World!" messageto standard output.
-
8/6/2019 Java Lecture1 Introduction
16/54
16
Example, Prints.java
import java.lang.System;
class Prints
{
public static void main(String[] args)
{System.out.print(":Haya ");
System.out.println("This Text in one line");
System.out.printf("\nFormatedtext;\n%s\t%s\n%s\t%d\n%s\t%d\n","Student","Mark","Ahmad",3,"Sami",5);
System.out.printf(" %x\n",15); // f
System.out.printf(" %o\n",15); // 17
}
}
%o for octal, %x for hexadicemal, %f for floating point representations.
-
8/6/2019 Java Lecture1 Introduction
17/54
17
-
8/6/2019 Java Lecture1 Introduction
18/54
18
Example
Name of class called identifier
Series of characters consisting of letters, digits,underscores ( _ ) and dollar signs ( $ )
Does not begin with a digit, has no spaces
Java is case sensitive
Examples: Print, $Print, _Print, Print7 is valid
7print is invalid
-
8/6/2019 Java Lecture1 Introduction
19/54
19
Summation of two numbers
Exampleimport java.util.Scanner; // program uses class Scanner
public class Summation
{
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in );
int number1;
int number2;
int sum;
System.out.print( "Enter first integer: " );
number1 = input.nextInt(); // read first number from user
System.out.print( "Enter second integer: " );number2 = input.nextInt(); // read second number from user
sum = number1 + number2; // add numbers
System.out.printf( "Sum is %d\n", sum ); // display sum
-
8/6/2019 Java Lecture1 Introduction
20/54
20
Summation cont. import: used to get the library (Java API) contains the definition for the used
classes
We need the scanner class defined in java.util.scanner package
All imports must be at the beginning, before class definition.
Using a Java APIwithout importing the required package cause syntax
error.
A Scanner enables a program to read data (e.g., numbers). The data cancome from many sources, such as a file on disk or the user at thekeyboard (System.in).
By default, packagejava.lang is imported in every Java program, thispackage contains the definition for System class.
We uses Scanner object input's nextInt method to obtain an integerfrom the user at the keyboard.
-
8/6/2019 Java Lecture1 Introduction
21/54
21
Object-Oriented ProgrammingConcepts
What Is an Object?
What Is a Class? What Is Inheritance?
What Is an Interface?
What Is a Package?
-
8/6/2019 Java Lecture1 Introduction
22/54
22
What Is an Object?
Real world consists ofobjects (desk, your television set, yourbicycle).
They share two characteristics: They all have state and behavior.
Bicycles have state (current gear, current speed) and behavior(changing gear, applying brakes).
Hiding internal state and requiring all interaction to be performedthrough an object's methods is known as data encapsulation.
-
8/6/2019 Java Lecture1 Introduction
23/54
23
What Is an Object? cont.
Grouping code into individual software objects provides a number ofbenefits, including:
Modularity: The source code for an object can be written andmaintained independently of the source code for other objects. Oncecreated, an object can be easily passed around inside the system.
Information-hiding: By interacting only with an object's methods, thedetails of its internal implementation remain hidden from the outsideworld.
Code re-use: If an object already exists , you can use that object in
your program.
Pluggability and debugging ease: If a particular object turns out to beproblematic, you can simply remove it from your application andplug in a different object as its
-
8/6/2019 Java Lecture1 Introduction
24/54
24
What Is a Class?
In object-oriented terms, we say that yourbicycle is aninstance of the class of objects known as bicycles.
class Bicycle {
int speed = 0;int gear = 1;
void changeGear(int newValue) { gear = newValue; }
void speedUp(int increment) { speed = speed + increment; }
void applyBrakes(int decrement) { speed = speed - decrement; }
void printStates() { System.out.println( speed:"+speed+"gear:"+gear); }
}
-
8/6/2019 Java Lecture1 Introduction
25/54
25
What Is a Class? cont. Here's a BicycleDemo class that creates two separate Bicycle objects
and invokes theirmethods:
class BicycleDemo {public static void main(String[] args) {// Create two different Bicycle objectsBicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();// Invoke methods on those objectsbike1.speedUp(10);bike1.changeGear(2);bike1.printStates();
bike2.speedUp(10);bike2.changeGear(2);bike2.speedUp(10);bike2.changeGear(3);bike2.printStates();}
}
-
8/6/2019 Java Lecture1 Introduction
26/54
26
What Is Inheritance?
Object-oriented programming allows classes to inherit commonly usedstate and behavior from other classes.
The syntax for creating a subclass is simple. At the beginning of your
class declaration, use the extends keyword, followed by the name ofthe class to inherit from:
class MountainBike extends Bicycle{// new fields and methods defining a mountain bike
// would go here}
-
8/6/2019 Java Lecture1 Introduction
27/54
27
What Is an Interface? An interface is a group of related methods with empty bodies.
interface Bicycle{
void changeGear(int newValue);void speedUp(int increment);void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (toACMEBicycle, for example), and you'd use the implements keywordin the class declaration:
class ACMEBicycle implements Bicycle{// remainder of this class implemented as before}
-
8/6/2019 Java Lecture1 Introduction
28/54
28
What Is a Package?
A package is a namespace that organizes
a set ofrelated classes and interfaces.
you can think of packages as being similar
to different folders on your computer.
-
8/6/2019 Java Lecture1 Introduction
29/54
29
Language Basics
Variables
Operators
Expressions, Statements, and Blocks Control Flow Statements
-
8/6/2019 Java Lecture1 Introduction
30/54
30
Variables
Four kinds:
Instance Variables (Non-Static Fields). Values are unique to each instance (object) of a class
Class Variables (Static Fields). There is exactly one copy of this variable in existence.
Local Variables.
Parameters.
-
8/6/2019 Java Lecture1 Introduction
31/54
31
Variables Naming
Variable names are case sensitive.
Can be any legal identifier an unlimited-length sequenceof Unicode letters and digits, beginning with a letter, thedollar sign, "$", or the underscore character, "_".
If the name you choose consists of only one word, spell
that word in all lowercase letters. If it consists ofmorethan one word, capitalize the first letter of eachsubsequent word. Ex: GearRatio
-
8/6/2019 Java Lecture1 Introduction
32/54
32
Variables - Primitive Data Types
byte: 8-bit signed integer.
short : 16-bit signed integer int: 32-bit signed integer
long: 64-bit signed integer
-
8/6/2019 Java Lecture1 Introduction
33/54
33
Variables - Primitive Data Types
float: 32-bit This data type should never be used for precise values, such as
currency. For that, you will need to use thejava.math.BigDecimalclass instead.
double: 64-bit
boolean: has only two possible values: true and false.
char:The char data type is a single 16-bit Unicode character. ('\u0000'(or 0) to '\uffff' (or65,535).
String object; for example, String s = "this is a string";.Once created, their values cannot be changed.
-
8/6/2019 Java Lecture1 Introduction
34/54
34
-
8/6/2019 Java Lecture1 Introduction
35/54
35
Literals Ex:
boolean result = true;char capitalC = 'C' ;byte b = 100;short s =10000;int i = 100000;
int: int decVal = 26; // The number 26, in decimal int hexVal = 0x1a; // The number 26, in hexadecimal
float and double: E or e (for scientific notation)
F or f (32-bit float literal) D or d (64-bit double literal). double d1 = 123.4; double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f;
-
8/6/2019 Java Lecture1 Introduction
36/54
36
Literals cont.
char and String:
char ch='\u0108;
-
8/6/2019 Java Lecture1 Introduction
37/54
37
Arrays
An array is a containerobject. Each item in an array is called an element, and each element is
accessed by its numerical index.
Declaring a Variable to Refer to an Array
type[] ; Ex: int[] arrayOfIntegers; float arrayOfFloats[ ]; // this form is discouraged
Creating, Initializing, and Accessing an Array =new type[]; Ex: arrayOfIntegers = new int[10]; // create an array of integers Or you can create and initialize at the same time: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
-
8/6/2019 Java Lecture1 Introduction
38/54
38
-
8/6/2019 Java Lecture1 Introduction
39/54
39
Multidimensional Arrays
int b[][] = { { 1, 2 }, { 3, 4, 5 } };
int b[][];
b = new int [ 3 ][ 4 ];
int b[][];
b = new int[ 2 ][ ]; // create 2 rows
b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1
-
8/6/2019 Java Lecture1 Introduction
40/54
40
Operator
-
8/6/2019 Java Lecture1 Introduction
41/54
41
Operators cont.
The + operatorcan also be used for concatenating (joining) twostrings together, as shown in the following ConcatDemo
class ConcatDemo
{public static void main(String[] args){String firstString = "This is";String secondString = " a concatenated string.";String thirdString = firstString+secondString;
System.out.println(thirdString);}
}
-
8/6/2019 Java Lecture1 Introduction
42/54
42
-
8/6/2019 Java Lecture1 Introduction
43/54
43
Expressions, Statements, and Blocks
An expression is a construct made up of variables, operators, and
method invocations.1 * 2 * 3x + y / 100 // ambiguous(x + y) / 100 // unambiguous, recommendedx + (y / 100) // unambiguous, recommended
A statement forms a complete unit of execution.aValue = 8933.234; // assignment statementaValue++; // increment statementSystem.out.println("Hello World!"); // method invocation // statementBicycle myBike = new Bicycle(); // object creation // statement
-
8/6/2019 Java Lecture1 Introduction
44/54
44
Expressions, Statements, and Blocks
A block is a group of zero or more statements between balancedbraces and can be used anywhere a single statement is allowed.
class BlockDemo {
public static void main(String[] args) {boolean condition = true;
if (condition) { // begin block 1System.out.println("Condition is true."); } // end block oneelse { // begin block 2
System.out.println("Condition is false.");} // end block 2}}
-
8/6/2019 Java Lecture1 Introduction
45/54
45
Control Flow Statements
Decision-making statements
if, if-else, switch
The looping statements
for, while, do while
The branching statements
break, continue, return
-
8/6/2019 Java Lecture1 Introduction
46/54
46
Decision-making statements .void applyBrakes(){
if (isMoving){ // the "if" clause: bicycle must be movingcurrentSpeed--; // the "then" clause: // decrease current speed}} The opening and closing braces are optional, provided that the
"then" clause contains only one statementvoid applyBrakes(){if (isMoving) {currentSpeed--;}else {
System.err.println("The bicycle has already stopped!");}
}
-
8/6/2019 Java Lecture1 Introduction
47/54
47
-
8/6/2019 Java Lecture1 Introduction
48/54
48
-
8/6/2019 Java Lecture1 Introduction
49/54
49
-
8/6/2019 Java Lecture1 Introduction
50/54
50
-
8/6/2019 Java Lecture1 Introduction
51/54
51
The while and do-while Statements Ex1:
class WhileDemo {public static void main(String[] args){int count = 1;while (count < 11) {System.out.println("Count is: " + count); count++;}
}} Ex2:class DoWhileDemo {
public static void main(String[] args){int count = 1;do { System.out.println("Count is: " + count); count++; } while (count
-
8/6/2019 Java Lecture1 Introduction
52/54
52
The for Statement and continue.
class PsDemo {public static void main(String[] args) {String searchMe = "peter piper picked a peck of " + "pickled
peppers";int max = searchMe.length();
int numPs = 0;for (int i = 0; i < max; i++) { //interested only in p'sif (searchMe.charAt(i) != 'p')continue; //process p'snumPs++;
}System.out.println("Found " + numPs + " p's in the string.");}
}
-
8/6/2019 Java Lecture1 Introduction
53/54
53
The for statement and break.class BreakDemo {
public static void main(String[] args) {int[ ] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;break; //
-
8/6/2019 Java Lecture1 Introduction
54/54
54
continue and break with lableclass BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 }};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search: //