33
Java Programming A Brief Intro

Java Programming A Brief Intro. Overview of Java Java Features How Java Works Program-Driven vs Event Driven Graphical User Interfaces (GUI)

Embed Size (px)

Citation preview

Java ProgrammingJava Programming

A Brief Intro

Overview of JavaOverview of Java

Java FeaturesHow Java WorksProgram-Driven vs Event DrivenGraphical User Interfaces (GUI)

Java FeaturesJava Features

Simple, Object-Oriented, FamiliarRobust and SecureArchitecture Neutral and PortableHigh Performance Interpreted, Threaded, and Dynamic

Simple, OO, FamiliarSimple, OO, Familiar

Its simplicity comes from the fact that there are no explicit pointers in Java. The programmer does not have to manage pointers and

the resultant problems resulting from their use All programs in Java are based on objects Java uses the familiar syntax and the same

fundamental control structures of C/C++ Complex, nuts and bolts Unix operations are

encapsulated in objects that provide easy to use interfaces e.g. Sockets

Robust and SecureRobust and Secure

Robust programs run without crashing due to programming errors, erroneous input, or failure of external devices. Java has many checks at compile-time and provides run-time exception handling to deal with unexpected events.

Security, especially across the internet, requires careful measures, which are implemented in Java

Architecture Neutral and Portable

Architecture Neutral and Portable

Java programs run on a variety of processors using various operating systems

Portability depends not only on architecture but also on implementation. Java specifies the language carefully to reduce implementation dependencies. Not perfectly independent, but better than most Java API includes just about everything

High PerformanceHigh Performance

Java versions continually increase performance capabilities.

In network applications, communication delays usually far exceed performance delays.

Interpreted, Threaded, and Dynamic

Interpreted, Threaded, and Dynamic

Interpreted, not compiled.Threaded – capable of multi_tasking and

concurrent processing, even across the internet

Dynamic linking to library code as it needs it.

Java is ideally suited for general, interactive, and network programming

How Java WorksHow Java Works

JavaJavaSourceSourceCodeCode

JavaJavaCompilerCompiler

JavaJavaByteByteCodeCode

Java InterpreterJava InterpreterFor Processor 1For Processor 1

Java InterpreterJava InterpreterFor Processor 2For Processor 2

Setting up Linux/Unix for JavaSetting up Linux/Unix for Java

Make a directory called java somewhere. Put this java directory in your CLASSPATH in your

environment (.cshrc on Unix)setenv CLASSPATH “.:$home/java:whatever_is_there_already“ this allows packages starting from your java subdirectory

Put your JDK’s bin directory in your path variable (in the .login file?)

Give commands to make the changes effective. These changes should be applied automatically on subsequent logins

Testing ChangesTesting Changes

prompt > java -versionjava version "1.5.0_01"

Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)

Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)

prompt >

Building an ApplicationBuilding an Application

Edit the source file either in your favorite editor, or IDE, and save it as <file>.java

The file name must be the same as the one and only public class name in the file

Compile by giving the command

javac <file>.java

at the command line of a DOS or Unix window. Run the program by giving the command

java <file>

hello.javahello.java

// File: hello.java

// Compiler: Sun javac

// Compile: javac hello.java

// Executable: hello.class

// Execute: java hello

//

// Purpose: Prints usual first

// program

hello.javahello.java

public class hello{ public static void main(String[] args) { int x = 3; System.out.println(“Hello, World!” + “\nx = “ + (x) ); }}

Application ProgramsApplication Programs

The file name must be the same as the one and only public class in the file.

This public class must have a static method called main (Why static??)public static void main( String[] args){ local declarations and statements}

ExerciseExercise

Setup your machine to compile and run a Java Application program. Test it with the HelloWorld program hello.java. The example is in the java/hello subdirectory

on the instructor’s website

Basic Java Programming Basic Java Programming

The C/C++ component Comments – C/C++ style Identifiers and keywords Types, variables, expressions Control structures Functions

System output Console input

Java is not accommodating to non-GUI input read() method only for characters

Packages

Identifiers and KeywordsIdentifiers and Keywords

A Java identifier must start with a letter, followed by 0 or more letters and/or digits. Java is case-sensitive.

Keywords cannot be used as user-identifiers. See text for a list of keywords.

Style – recommended & preferred; consistency is a must! Class names begin with a capital letter Variable names begin with a lower case letter Function names begin with a verb which is lowercased. Constants are all upper case. Multiple word names are lower case except for the beginning of each

word component.

ExamplesExamples

Request would be a class namemyRequest would be a variable namegetRequest() would be a function

(method) nameTHE_REQUEST would be a constant.The Java standard style convention

should be followed in our programming.

Standard TypesStandard Types

char – ascii or unicodeboolean – true or falseNumerical types – various sizes of

numbers

Numerical TypesNumerical Types

Standard numerical types in Java aretype size least value greatest value________________________________________ byte 8 -128 127short 16 -32768 32767int 32 -2147483648 2147483647long 64 -263 263-1float* 32 ~ -3.4 x 1038 ~ 3.4 x 1038

double* 64 ~ -1.7 x 10308 ~ 1.7 x 10308

* 7 and 15 digit accuracy respectively

Variables and ExpressionsVariables and Expressions

Java follows the syntax of C/C++ for expressions and assignment.

The operators for the standard types are the same as those for C/C++

Remember that = is assignment and== is equal relational operator.

You should NOT use = in a cascading manner.

Control StructuresControl Structures

The control structures are the same as C/C++ if switch for while do – while

Note: unlike C/C++, where a test expression can evaluate to int, a test expression MUST be of type boolean

Functions (Methods)Functions (Methods)

In Java there are no independent functions A function (method) is always a member function of

some class. The syntax is very similar.

modifier(s) resulttype name( <params>) { local declarations and statements } // the modifier is public, private, or protected, and can also

be prefaced static

Methods: ParametersMethods: Parameters

Different rules than C++ technically, all pass is by value objects not passed, their address is

passing address means in method, there are two references to same object

effect is same as pass by reference, as change to object inside method changes caller’s (same) object

simple types can’t be passed by reference must be wrapped in an object

• problem of immutability in java.lang objects

System OutputSystem Output

Output is generated by using streams. The stream classes are defined in the standard Java package java.io.

The class System in the package java.lang contains three different streams for use in Java programs:

System.in the keyboardSystem.out the screenSystem.err the screen

System.out.println( any string)

Examples of OutputExamples of Output

To print an object, the object should have overloaded the method toString that is inherited from the Class Object.

Standard types have this method.System.out.println(“The value of x = “ + x );The + is the concatenation operator for

strings.

System InputSystem Input

System input is quite complicated, so many authors provide a package of IO functions for the standard types.

Dependence on anything proprietary defeats the purpose of Java. A class InputReader is in the public java directory for text input. it uses only pure Java to perform input

More fundamental IO will be discussed later Java is made for GUIs, particularly components

such as TextFields, Menus. etc;

Examples of inputExamples of input

helloYou.javahelloInt.java

java/hello directory on web

Things that are differentThings that are different

String concatenation is the operator + It takes two operands which are “stringable”,

that is any operand that is a string or has the toString method overloaded for that type.

System.out.println(76 + “ trombones”); Beware:

System.out.println(23+45) What is output? 2345, or 68?

PackagesPackages

Java organizes code into packages which correspond to directories in the file system.

Each Java class is contained in a package.The default package is . (the current

directory) Is . In your classpath????

The System class is found in java.langThe Applet class is found in java.applet

CommentsComments

When calling methods of the same class, we do not need to use the class name as a prefix.

When calling methods of another class, we use the class name or an object of that class as a prefix.

Objects Objects

Still declared as a classNo separate sections

Each declaration specified with access public, private, protected

static declarations part of class, but not object

non-static declarations part of instantiated objects only