0% found this document useful (0 votes)
61 views

Internet Programming Chapter 2

This document provides an overview of the Java programming language, including key concepts such as object-oriented programming, primitive data types, control structures, predefined classes, writing and documenting custom classes, and compiling and executing Java programs. It discusses Java characteristics like platform independence and memory management. It also covers topics like operators, type compatibility/conversion, variables, objects, methods, control statements, and classes.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Internet Programming Chapter 2

This document provides an overview of the Java programming language, including key concepts such as object-oriented programming, primitive data types, control structures, predefined classes, writing and documenting custom classes, and compiling and executing Java programs. It discusses Java characteristics like platform independence and memory management. It also covers topics like operators, type compatibility/conversion, variables, objects, methods, control statements, and classes.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

Chapter Two

Overview of Java
Language
Topics of the Review

• Essentials of object-oriented programming, in Java


• Java primitive data types, control structures, and arrays
• Using some predefined classes:
• Math
• JOptionPane, I/O streams
• String, StringBuffer, StringBuilder
• StringTokenizer
• Writing and documenting your own Java classes

2
Some Characteristics of Java

• Java is platform independent: the same program can


run on any correctly implemented Java system
• Java is object-oriented:
• Structured in terms of classes, which group data with
operations on that data
• Can construct new classes by extending existing ones
• Java is robust
• Manages memory/the idea of garbage collector
• Handles exceptions
• Java is multithreaded

3
Java categories / editions

• Java micro edition : for developing mobile application


• Java standard edition : for developing standalone
application
• Java enterprise edition : for large scale application

4
Java Processing and Execution

• Begin with Java source code : Model.java


• A Java source code compiler produces Java byte code
• Outputs one file per class: Model.class
• A Java Virtual Machine loads and executes class files

5
Compiling and Executing a Java Program

6
Classes and Objects

• The class is the unit of programming


• A Java program is a collection of classes
• Each class definition (usually) in its own .java file
• The file name must match the class name
• A class describes objects (instances)
• Describes their common characteristics: is a blueprint
• Thus all the instances have these same characteristics
• These characteristics are:
• Data fields for each object
• Methods (operations) that do work on the objects
7
Grouping Classes: The Java API

• API = Application Programming Interface


• Java = small core + extensive collection of packages
• A package consists of some related Java classes:
• Swing: a GUI (graphical user interface) package
• AWT: Application Window Toolkit (more GUI)
• util: utility data structures (important to CS 187!)
• The import statement tells the compiler to make
available classes and methods of another package
• A main method indicates where to begin executing a
class (if it is designed to be run as a program)

8
A Little Example of import and main

import javax.swing.*;
// all classes from javax.swing
public class HelloWorld { // starts a class
public static void main (String[] args) {
// starts a main method
// in: array of String; out: none (void)
}
}
• public = can be seen from any package
• static = not “part of” an object
9
Processing and Running HelloWorld

• javac HelloWorld.java
• Produces HelloWorld.class (byte code)
• java HelloWorld
• Starts the JVM and runs the main method

10
References and Primitive Data Types

• Java distinguishes two kinds of entities


• Primitive types
• Objects
• Primitive-type data is stored in primitive-type variables
• Reference variables store the address of an object

11
Primitive Data Types

• Represent numbers, characters, boolean values


• Integers: byte, short, int, and long
• Real numbers: float and double
• Characters: char

12
Primitive Data Types

Data type Range of values

byte -128 .. 127 (8 bits)


short -32,768 .. 32,767 (16 bits)
int -2,147,483,648 .. 2,147,483,647 (32 bits)
long -9,223,372,036,854,775,808 .. ... (64 bits)
float +/-10-38 to +/-10+38 and 0, about 6 digits precision
double +/-10-308 to +/-10+308 and 0, about 15 digits precision
char Unicode characters (generally 16 bits per char)
boolean True or false

13
Primitive Data Types (continued)

14
Operators

1. subscript [ ], call ( ), member access .


2. pre/post-increment ++ --, boolean complement !,
bitwise complement ~, unary + -, type cast (type),
object creation new
3. * / %
4. binary + - (+ also concatenates strings)
5. signed shift << >>, unsigned shift >>>
6. comparison < <= > >=, class test instanceof
7. equality comparison == !=
8. bitwise and &
9. bitwise or |

15
Operators

11. logical (sequential) and &&


12. logical (sequential) or ||
13. conditional cond ? true-expr : false-expr
14. assignment =, compound assignment += -= *= /=
<<= >>= >>>= &= |=

16
Type Compatibility and Conversion

• Widening conversion:
• In operations on mixed-type operands, the numeric
type of the smaller range is converted to the numeric
type of the larger range
• In an assignment, a numeric type of smaller range
can be assigned to a numeric type of larger range
• byte to short to int to long
• int kind to float to double

17
Declaring and Setting Variables

• int square;
square = n * n;
• double cube = n * (double)square;
• Can generally declare local variables where they are
initialized
• All variables get a safe initial value anyway (zero/null)

18
Referencing and Creating Objects

• You can declare reference variables


• They reference objects of specified types
• Two reference variables can reference the same object
• The new operator creates an instance of a class
• A constructor executes when a new object is created
• Example: String greeting = ″hello″;

19
Java Control Statements

• A group of statements executed in order is written


• { stmt1; stmt2; ...; stmtN; }
• The statements execute in the order 1, 2, ..., N
• Control statements alter this sequential flow of execution

20
Java Control Statements (continued)

21
Java Control Statements (continued)

22
Methods

• A Java method defines a group of statements as


performing a particular operation
• static indicates a static or class method
• A method that is not static is an instance method
• All method arguments are call-by-value
• Primitive type: value is passed to the method
• Method may modify local copy but will not affect
caller’s value
• Object reference: address of object is passed
• Change to reference variable does not affect caller
• But operations can affect the object, visible to caller

23
Escape Sequences

• An escape sequence is a sequence of two characters


beginning with the character \
• A way to represents special characters/symbols

24
The String Class

• The String class defines a data type that is used to


store a sequence of characters
• You cannot modify a String object
• If you attempt to do so, Java will create a new object
that contains the modified character sequence

25
Comparing Objects

• You can’t use the relational or equality operators to


compare the values stored in strings (or other objects)
(You will compare the pointers, not the objects!)

26
The StringBuffer Class

• Stores character sequences


• Unlike a String object, you can change the contents of
a StringBuffer object

27
StringTokenizer Class

• We often need to process individual pieces, or tokens, of


a String

28
Wrapper Classes for Primitive Types

• Sometimes we need to process primitive-type data as


objects
• Java provides a set of classes called wrapper classes
whose objects contain primitive-type values: Float,
Double, Integer, Boolean, Character, etc.

29
Defining Your Own Classes

• Unified Modeling Language (UML) is a standard diagram


notation for describing a class

Field
signatures:
type and name

Method signatures:
name, argument Field Class
types, result type Class values name
name

30
Defining Your Own Classes (continued)

• The modifier private limits access to just this class


• Only class members with public visibility can be
accessed outside of the class* (* but see protected)
• Constructors initialize the data fields of an instance

31
The Person Class

// we have omitted javadoc to save space


public class Person {
private String givenName;
private String familyName;
private String IDNumber;
private int birthYear;

private static final int VOTE_AGE = 18;


private static final int SENIOR_AGE = 65;
...
32
The Person Class (2)

// constructors: fill in new objects


public Person(String first, String family,
String ID, int birth) {
this.givenName = first;
this.familyName = family;
this.IDNumber = ID;
this.birthYear = birth;
}
public Person (String ID) {
this.IDNumber = ID;
}
33
The Person Class (3)

// modifier and accessor for givenName


public void setGivenName (String given) {
this.givenName = given;
}

public String getGivenName () {


return this.givenName;
}

34
The Person Class (4)

// more interesting methods ...


public int age (int inYear) {
return inYear – birthYear;
}
public boolean canVote (int inYear) {
int theAge = age(inYear);
return theAge >= VOTE_AGE;
}

35
The Person Class (5)

// “printing” a Person
public String toString () {
return “Given name: “ + givenName + “\n”
+ “Family name: “ + familyName + “\n”
+ “ID number: “ + IDNumber + “\n”
+ “Year of birth: “ + birthYear + “\
n”;
}

36
The Person Class (6)

// same Person?
public boolean equals (Person per) {
return (per == null) ? false :
this.IDNumber.equals(per.IDNumber);
}

37
Arrays

• In Java, an array is also an object


• The elements are indexes and are referenced using the
form arrayvar[subscript]

38
Array Example

float grades[] = new float[numStudents];


... grades[student] = something; ...

float total = 0.0;


for (int i = 0; i < grades.length; ++i) {
total += grades[i];
}
System.out.printf(“Average = %6.2f%n”,
total / numStudents);

39
Array Example Variations

// possibly more efficient


for (int i = grades.length; --i >= 0; ) {
total += grades[i];
}

// uses Java 5.0 “for each” looping


for (float grade : grades) {
total += grade;
}

40
Input/Output using Class JOptionPane

• Java 1.2 and higher provide class JOptionPane, which


facilitates display
• Dialog windows for input
• Message windows for output

41
Input/Output using Class JOptionPane
(continued)

42
Converting Numeric Strings to Numbers

• A dialog window always returns a reference to a String


• Therefore, a conversion is required, using static
methods of class String:

43
Summary of the Review

• A Java program is a collection of classes


• The JVM approach enables a Java program written on
one machine to execute on any other machine that has a
JVM
• Java defines a set of primitive data types that are used
to represent numbers, characters, and boolean data
• The control structures of Java are similar to those found
in other languages
• The Java String and StringBuffer classes are used
to reference objects that store character strings

44

You might also like