You are on page 1of 94

Java is much more language support error handling no pointers! (garbage collection) threads are part of the language.

some support for common application level protocols (HTTP). dynamic class loading source code and bytecode-level portability.

Netprog 2002 Java Intro

` ` ` ` `

Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread acceptance

` ` ` ` ` ` ` ` ` ` `

Java is simple Java is object-oriented Java is distributed Java is interpreted Java is robust Java is secure Java is architecture-neutral Java is portable Javas performance Java is multithreaded Java is dynamic

Simple
fixes some clumsy features of C++ no pointers automatic garbage collection rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/

Object oriented
focus on the data (objects) and methods manipulating the data all functions are associated with objects almost all datatypes are objects (files, strings, etc.) potentially better code organization and reuse

Interpreted
java compiler generate byte-codes, not native machine code the compiled byte-codes are platform-independent java bytecodes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine)

Portable
same application runs on all platforms the sizes of the primitive data types are always the same the libraries define portable interfaces

Reliable
extensive compile-time and runtime error checking no pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible automatic garbage collection tracks objects usage over time

Secure
usage in networked environments requires more security memory allocation model is a major defense access restrictions are forced (private, public)

Multithreaded
multiple concurrent threads of executions can run simultaneously utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables paradigm) to achieve this

Dynamic
java is designed to adapt to evolving environment libraries can freely add new methods and instance variables without any effect on their clients interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented can check the class type in runtime

Slower than compiled language such as C


an experiment in 1999 showed that Java was 3 or 4 times slower than C or C++
title of the article: Comparing Java vs. C/C++ Efficiency Issues to Interpersonal Issues (Lutz Prechelt)

adequate for all but the most time-intensive programs

` `

Sun Solaris OS JDK 1.4 (latest: J2SE 5.0) You can use the lab at CL112. Please follow the steps:
log into the Unix environment subscribe to JDK-CURRENT when you log in for the first time (% is a prompt sign)
%> subscribe JDK-CURRENT

and then log out by clicking on the EXIT button on the control panel

Can be installed on different platforms:


Unix/Linux Windows Mac OS

Follow the on-line instructions:


http://java.sun.com/docs/books/tutorial/getStarted/cupojava/index.html

` ` ` `

James Gosling and Sun Microsystems Oak Java, May 20, 1995, Sun World HotJava
The first Java-enabled Web browser

` `

JDK Evolutions J2SE, J2ME, and J2EE (not mentioned in the book, but could discuss here optionally)

12

` ` ` ` `

JDK 1.02 (1995) JDK 1.1 (1996) Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998) Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000) Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)

13

Java Standard Edition (J2SE)


J2SE can be used to develop client-side standalone applications or applets.

Java Enterprise Edition (J2EE)


J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages.

Java Micro Edition (J2ME).


J2ME can be used to develop applications for mobile devices such as cell phones.

This book uses J2SE to introduce Java programming.


14

Back in the "old days" we had Structured Programming:


data was separate from code. programmer is responsible for organizing everything in to logical units of code/data. no help from the compiler/language for enforcing modularity,

Hard to build large systems (not impossible, just hard).


Java Programming: OOP 16

` `

` `

Keep data near the relevant code. Provide a nice packaging mechanism for related code. Model the world as objects. objects can send "messages" to each other.

Java Programming: OOP

17

Collection of:
Fields (object state, data members, instance variables, ..) Methods (behaviors, )

Each object has it's own memory for maintaining state (the fields). All objects of the same type share code.

Java Programming: OOP

18

` ` ` `

Code re-use
programmer efficiency

Encapsulation
code quality, ease of maintenance

Inheritance
efficiency, extensibility.

Polymorphism
power!

Java Programming: OOP

19

nice packaging makes it easy to document/find appropriate code. everyone uses the same basic method of organizing code (object types). easy to re-use code instead of writing minor variations of the same code multiple times (inheritance).

Java Programming: OOP

20

` `

Information Hiding. Don't need to know how some component is implemented to use it. Implementation can change without effecting any calling code. "protects us from ourselves"

Java Programming: OOP

21

On the surface, inheritance is a code re-use issue.


we can extend code that is already written in a manageable manner.

Inheritance is more, it supports polymorphism at the language level!

Java Programming: OOP

22

Take an existing object type (collection of fields and methods) and extend it.
create a special version of the code without re-writing any of the existing code (or even explicitly calling it!). End result is a more specific object type, called the subclass / derived class / child class. The original code is called the superclass / parent class / base class.

Java Programming: OOP

23

Employee: name, email, phone


FulltimeEmployee: also has salary, office, benefits,
x Manager: CompanyCar, can change salaries, rates contracts, offices, etc.

Contractor: HourlyRate, ContractDuration,


`

A manager a special kind of FullTimeEmployee, which is a special kind of Employee.

Java Programming: OOP

24

` ` `

Layered systems allow specific functionality to be handled in one place (and only one place). Development can be incremental, develop each layer based on the others. Testing can be done on individual layers (test subfunctions directly instead of indirectly).

Java Programming: OOP

25

Create code that deals with general object types, without the need to know what specific type each object is. Generate a list of employee names:
all objects derived from Employee have a name field! no need to treat managers differently from anyone else.

Java Programming: OOP

26

` `

The real power comes with methods/behaviors. A better example:


shape object types used by a drawing program. we want to be able to handle any kind of shape someone wants to code (in the future). we want to be able to write code now that can deal with shape objects (without knowing what they are!).

Java Programming: OOP

27

Shape:
color, layer draw() calcArea() fields draw itself on the screen calculates it's own area.

serialize() generate a string that can be saved and later used to re-generate the object.

Java Programming: OOP

28

Rectangle Triangle

Each could be a kind of shape (could be specializations of the shape class).

Each knows how to draw itself, etc.

Circle

Could write code to have all shapes draw themselves, or save the whole collection to a file.

Java Programming: OOP

29

` `

Create new object type with class keyword. A class definition can contain:
variables (fields) initialization code methods

Java Programming: OOP

30

class classname { field declarations { initialization code } Constructors Methods }

Java Programming: OOP

31

sample code: SimpleClass and FooPrinter

Defining a class does not create an object of that class - this needs to happen explicitly: classname varname = new classname(); In general, an object must be created before any methods can be called. the exceptions are static methods.

Java Programming: OOP

32

An object is a chunk of memory: holds field values holds an associated object type All objects of the same type share code they all have same object type, but can have different field values.

Java Programming: OOP

33

` `

Very similar to C++ You can create multiple constructors, each must accept different parameters. If you don't write any constructor, the compiler will (in effect) write one for you: classname() {} If you include any constructors in a class, the compiler will not create a default constructor!

Java Programming: OOP

34

sample code: ConstructorDemo

` `

One constructor can call another. You use "this", not the classname:

class Foo { int i; Foo() { this(0); } Foo( int x ) { i = x; }

A call to this must be the first statement in the constructor!

Java Programming: OOP

35

` `

Nope! There is a finalize() method that is called when an object is destroyed.


you don't have control over when the object is destroyed (it might never be destroyed). The JVM garbage collector takes care of destroying objects automatically (you have limited control over this process).

Java Programming: OOP

36

public: anyone can create an object of the defined class.


only one public class per file, must have same name as the file (this is how Java finds it!).

default is non-public (if you don't specify "public").

Java Programming: OOP

37

` ` `

A Simple Java Application Compiling Programs Executing Applications

38

Example 1.1
//This application program prints Welcome //to Java! package chapter1; public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
Source Run

NOTE: To run the program, install slide files on hard disk.

39

On command line
javac file.java

Create/Modify Source Code

Source Code

Compile Source Code i.e. javac Welco me.java


If compilation errors Bytecode

Run Byteode i.e. java Welcome

Result

If runtime errors or incorrect result

40

On command line
java classname

Bytecode

Java Interpreter on Windows

Java Interpreter on Linux

...

Java Interpreter on Sun Solaris

41

javac Welcome.java java Welcome output:...

42

Where are the files stored in the directory?


c:\example chapter1 Welcome.java Welcome.class Welcome.java~ chapter2 Java source files and class files for Chapter 2

. .
chapter19 Java source files and class files for Chapter 19

43

public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); } }

44

Netprog 2002 Java Intro

javac HelloWorld.java

HelloWorld.java
compile source code run

java HelloWorld

HelloWorld.class
bytecode
45 Netprog 2002 Java Intro

bytecode is an intermediate representation of the program (class). The Java interpreter starts up a new Virtual Machine. The VM starts executing the users class by running its main() method.

46

Netprog 2002 Java Intro

The java_home/bin directory is in your $PATH If you are using any classes outside the java or javax package, their locations are included in your $CLASSPATH

47

Netprog 2002 Java Intro

class Example2 { public static void main(String args[]) { int num; // this declares a variable called num num = 100; // this assigns num the value 100 System.out.println("This is num: " + num); num = num * 2; System.out.print("The value of num * 2 is "); System.out.println(num); } }

` `

When you run this program, you will see the following output: This is num: 100 The value of num * 2 is 200

` `

` `

The if Statement The Java if statement works much like the IF statement in any other language. Further, it is syntactically identical to the if statements in C, C++, and C#. Its simplest form is shown here: if(condition) statement;

which may be used in a conditional expression. Here are a few: ` Operator Meaning ` < Less than ` > Greater than ` == Equal to

` ` ` ` ` ` ` ` ` ` ` ` ` `

class IfSample { public static void main(String args[]) { int x, y; x = 10; y = 20; if(x < y) System.out.println("x is less than y"); x = x * 2; if(x == y) System.out.println("x now equal to y"); x = x * 2; if(x > y) System.out.println("x now greater than y"); // this won't display anything if(x == y) System.out.println("you won't see this"); } }

for(initialization; condition; iteration) statement;

` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `

class ForTest { public static void main(String args[]) { int x; for(x = 0; x<10; x = x+1) System.out.println("This is x: " + x); } } This program generates the following output: This is x: 0 This is x: 1 This is x: 2 This is x: 3 This is x: 4 This is x: 5 This is x: 6 This is x: 7 This is x: 8 This is x: 9

` ` ` `

Java allows two or more statements to be grouped into blocks of code, also called code blocks. if(x < y) { // begin a block x = y; y = 0; } // end of block

` `

Java programs are a collection of whitespace, identifiers, comments, literals, operators, separators, and keywords.

Java is a free-form language. This means that you do not need to follow any special indentation rules. For example, the Example program could have been written all on one line or in any other strange way you felt like typing it, as long as there was at least one whitespace character between each token that was not already delineated by an operator or separator. In Java, whitespace is a space, tab, or newline.

Identifiers are names of variables, functions, classes etc. The name used as an identifier must follow the following rules in JavaTM technology.
Each character is either a digit, letter, underscore(_) or currency symbol ($,, or ) First character cannot be a digit. The identifier name must not be a reserved word.

A literal in Java technology denotes a constant value. So for example 0 is an integer literal, and 'c' is a character literal. The reserved literals true and false are used to represent boolean literals. "This is a string" is a string literal.

Java technology supports three type of comments A single line comment starting with // A multi-line comment enclosed between /* and */ A documentation or javadoc comment is enclosed between /** and */. These comments can be used to generate HTML documents using the javadoc utility, which is part of Java language.

Symbol Name

Purpose

()

{}

[]

Parentheses Used to contain lists of parameters in method definition and invocation. Also used for defining precedence in expressions, containing expressions in control statements, and surrounding cast types. Braces Used to contain the values of automatically initialized arrays. Also used to define a block of code, for classes, methods, and local scopes. Brackets Used to declare array types. Also used when dereferencing array values.

; ,

Semicolon Terminates statements. Comma Separates consecutive identifiers in a variable declaration. Also used to chain statements together inside a for statement. Period Used to separate package names from subpackages and classes. Also used to separate a variable or method from a reference variable.

keyword or reserved word in Java technology has special meaning and cannot be used as a user defined identifier. It is important to note the following
const and goto are not currently in use. null, true, and false are reserved literals but can be considered as reserved words for the purpose of exam. It is important to understand that Java language is casesensitive. So even though super is a keyword, Super is not. All the Java technology keywords are in lower case. strictfp is a new keyword added in Java 1.2. assert is added in Java 1.4 and enum in Java 5.0

abstract char double for int package static throw while

boolean class else goto interface private strictfp throws assert

break const extends if long protected super transient enum

byte continue final implements native public switch try

case default finally import new return synchronized void

catch do float instanceof null short this volatile

The sample programs shown in this chapter make use of two of Javas built-in methods: println( ) and print( ). As mentioned, these methods are members of the System class, which is a class predefined by Java that is automatically included in your Programs. In the larger view, the Java environment relies on several built-in class libraries that contain many built-in methods that provide support for such things as I/O, string handling, networking, and graphics. The standard classes also provide support for windowed output. Thus, Java as a totality is a combination of the Java language itself, plus its standard classes.

As you will see, the class libraries provide much of the functionality that comes with Java. Indeed, part of becoming a Java programmer is learning to use the standard Java classes. Throughout Part I of this book, various elements of the standard library classes and methods are described as needed. In Part II, the class libraries are described in detail.

If you come from a C or C++ background, keep in mind that Java is more strictly typed than either language. For example, in C/C++ you can assign a floating-point value to an integer. In Java, you cannot. Also, in C there is not necessarily strong type-checking between a parameter and an argument. In Java, there is. You might find Javas strong type-checking a bit tedious at first. But remember, in the long run it will help reduce the possibility of errors in your code.

Integers This group includes byte, short, int, and long, which are for whole valued signed numbers. Floating-point numbers This group includes float and double, which represent numbers with fractional precision. Characters This group includes char, which represents symbols in a character set, like letters and numbers. Boolean This group includes boolean, which is a special type for representing true/false values.

Data types byte short int long char float double

Width (in bytes) 1 2 4 8 2 4 8

Minimum value -27 -215 -231 -263 0x0 1.401298e-45 4.940656e-324

Maximum Value 27 - 1 215-1 231 - 1 263 - 1 0xffff 3.402823e+38 1.797693e+308

Data types int short long byte char float double

Wrapper class Integer Short Long Byte Character Float Double

type identifier [ = value][, identifier [= value] ...] ;

int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing // d and f. byte z = 22; // initializes z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'.

// Demonstrate dynamic initialization. class DynInit { public static void main(String args[]) { double a = 3.0, b = 4.0; // c is dynamically initialized double c = Math.sqrt(a * a + b * b); System.out.println("Hypotenuse is " + c); } }

class Scope { public static void main(String args[]) { int x; // known to all code within main x = 10; if(x == 10) { // start new scope int y = 20; // known only to this block // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } // y = 100; // Error! y not known here // x is still known here. System.out.println("x is " + x); } }

Conversion rules in Assignments In the description below, I am giving basic conversion rules for assignment when source and destination are of different types. I. If source and destination are of the same type, assignment happens without any issues. II.If ource is of smaller size than destination but source and destination are of compatible types, then no casting is required. Implicit widening takes place in this case. An example is assigning an int to a long. III.If source and destination are of compatible types, but source is of larger size than destination, explicit casting is required. In this case, if no casting is provided then the program does not compile.

` ` ` `

int a; byte b; // ... b = (byte) a;

// Demonstrate casts. class Conversion { public static void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("\nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); } }

Conversion of int to byte. i and b 257 1 Conversion of double to int. d and i 323.142 323 Conversion of double to byte. d and b 323.142 67

byte a = 40; byte b = 50; byte c = 100; int d = a * b / c;

byte b = 50; b = b * 2; // Error! Cannot assign an int to a byte!

byte b = 50; b = (byte)(b * 2); which yields the correct value of 100.

rules that apply to expressions. They are as follows. First, all byte and short values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double.

class Promote { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); } }

Arrays are used to represent fixed number of elements of the same type. The following are legal syntax for declaring one-dimensional arrays. int anArray[]; int[] anArray; int []anArray; It is important to note that the size of the array is not included in the declaration. Memory is allocated for an array using the new operator as shown below. An Array = new int[10]; The declaration and memory allocation may be combined together as shown below. int an Array[] = new int[10];

int anArray[] = new int[10]; The elements of the array are implicitly initialized to default values based on array types (0 for integral types, null for objects etc.). This is true for both local arrays as well as arrays which are data members. In this respect arrays are different from normal variables. Variable defined inside a method are not implicitly initialized, where as array elements are implicitly initialized.

Array Initializations Arrays are initialized using the syntax below int intArray[] = {1,2,3,4}; The length operator can be used to access the number of elements in an array (for example intArray.length). Multidimensional Arrays The following are legal examples of declaration of a two dimensional array. int[] arr[]; int[][] arr; int arr[][]; int []arr[];

When creating multi-dimensional arrays the initial index must be created before a later index. The following examples are legal. int arr[][] = new int[5][5]; int arr[][] = new int[5][]; The following example will not compile; int arr[][] = new int[][5];

It is just that Javas string type, called String, is not a simple type. Nor is it simply an array of characters (as are strings in C/C++). Rather, String defines an object, and a full description of it requires an understanding of several object-related features.

` `

String str = "this is a test"; System.out.println(str);

Operators

` ` ` ` `

Assignment: =, +=, -=, *=, Numeric: +, -, *, /, %, ++, --, Relational: ==. !=, <, >, <=, >=, Boolean: &&, ||, ! Bitwise: &, |, ^, ~, <<, >>, Just like C/C++!

90

Netprog 2002 Java Intro

The conditional operators && and || Operator && returns true if both operands are true, false otherwise. Operator || returns false if both operands are false, true otherwise. The important thing to note about these operators is that they are short-circuited. This means that the left operand is evaluated before the right operator.

If the result of the operation can be evaluated after computing the left operand, then the right side is not computed. In this respect these operators are different from their bit-wise counterparts - bit-wise and (&), and bit-wise or (|). The bit-wise operators are not short-circuited. This means both the operands of bit-wise operator are always evaluated independent of result of evaluati

Control Statements

of what you expect: conditional: if, if else, switch loop: while, for, do break and continue (but a little different than with C/C++).
94 Netprog 2002 Java Intro

` More

You might also like