Java Fund

  • Uploaded by: api-3731415
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Java Fund as PDF for free.

More details

  • Words: 3,338
  • Pages: 63
University of the Philippines Cebu College

Object-Oriented Programming Using JAVA

Java Programming Language

University of the Philippines Cebu College Course Overview This course covers the following areas: • Fundamentals of the Java programming language. • Object-oriented concepts in Java. • Graphical user interface (GUI) programming. • Introduction to Multi-threading.

Java Programming Language

University of the Philippines Cebu College

What is Java?

Java is just a small, simple, safe, object-oriented, interpreted or dynamically optimized, byte-coded, architecture-neutral, garbagecollected, multithreaded programming language with a strongly typed exception-handling mechanism for writing distributed, dynamically extensible programs. Java Programming Language

University of the Philippines Cebu College

Small, simple, safe and garbage collected • C++ minus (pointers and memory management have been omitted; operator overloading and multiple inheritance have been omitted) • garbage collector automatically frees unused memory • strict type checking mechanism (most errors are detected at compile time) Java Programming Language

University of the Philippines Cebu College Interpreted, byte-coded, architecture neutral Java Source filename.java

javac filename.java

Java ByteCode Filename.class

java filename

VM Java

VM Java

VM Java

NT

Unix

OS/2

Java Programming Language

University of the Philippines Cebu College

The Java Virtual Machine • Provides hardware platform specifications • Reads compiled byte codes that are platform independent • Is implemented as software or hardware • Is implemented in a Java technology development tool or a Web browser

Java Programming Language

University of the Philippines Cebu College The Java Virtual Machine • JVM provides definitions for the:  Instruction set  Register set  Class file format  Stack  Garbage-collected heap  Memory area

Java Programming Language

University of the Philippines Cebu College

JVM Class files

Class Loader bytecodes

Execution Engine Native functions/methods

Operating System Java Programming Language

JAVA API Class files

University of the Philippines Cebu College Class Loader

Method Area

Heap

Stack

Registers

Runtime Data Areas

Execution Engine Java Programming Language

Constant Pool

University of the Philippines Cebu College

Two types of Java programs Applets are programs written in Java programming language that reside on WWW servers, are downloaded by a browser to a client’s system, and are run by that browser. Applications are standalone programs that do not require a Web browser to execute. They are typically general-purpose programs that run on any machine where the Java runtime environment (JRE) is installed. Java Programming Language

University of the Philippines Cebu College Sample Java Application public class MyFirst { public static void main(String[] args) { System.out.println("Hello participants!"); } }

Java Programming Language

University of the Philippines Cebu College Sample Java Applet

import java.applet.*; import java.awt.*; public class MyFirstApplet extends Applet {

}

public void paint(Graphics g) { g.drawString("Hello participants!",50,50); }

Java Programming Language

University of the Philippines Cebu College

GETTING STARTED WITH JAVA • The Java Developer’s Kit • The Java API

Java Programming Language

University of the Philippines Cebu College

public class MyFirst { public static void main(String[] args) { System.out.println(“Hello world!”); } }

Java Programming Language

University of the Philippines Cebu College

J ava Tokens I dentifiers Keywords Literals Separators Operators Comments

Java Programming Language

University of the Philippines Cebu College Identifiers - either reserved words or titles given to variables, methods, and component elements of classes. - can be named anything as long as they begin with an alphabet, a dollar sign or an underscore - the more descriptive the identifier, the better - case sensitive.

Java Programming Language

University of the Philippines Cebu College Keywords - are reserved words, meaning they cannot be used in any way other than how Java intends for them to be used. - these special tokens are always in lowercase. - these are used as application flow controls, Reserved Words class in Java declarations, identifiers, and expressions.

Declaration Keywords boolean byte char double Java Programming Language

float int long short

University of the Philippines Cebu College Loop Keywords break continue do for while

Conditional Keywords case else if switch

Exception Keywords catch finally throw try Java Programming Language

University of the Philippines Cebu College Structure Keywords abstract class default extends

implements instanceof interface

Modifier and Access Methods final native new private protected public

Java Programming Language

static synchronized threadsafe transient void

University of the Philippines Cebu College Miscellaneous Keywords false import null package

Byvalue Cast Const Future Generic goto

Java Programming Language

return super this true

inner operator outer rest var

University of the Philippines Cebu College Literals - represent data in Java, and are based on character and number representations. - types of literals : integer, floating-point, boolean, character, and string. - every variable consists of a literal and a data type; the difference between the two is that literals are entered explicitly into the code, while data types are information about how much room will be reserved in memory for such variable, as well as possible value ranges.

Types of Literals 1. Integer Literals - whole numbers such as 8 and 1930. - can either be decimal(base 10), octal (base 8) or Java Programminghexadecimal Language (base 16).

University of the Philippines Cebu College Integer Literal Types a. Decimal Literals - decimal literals cannot start with 0, as in 02364, because numbers beginning with 0 are reserved for octal and hex literals. - decimal literals : any combination from 0-9.

b. Octal Literals - start with 0 and can be followed by any number 0-7.

c. Hex Literals - start with 0x or 0X, followed by one or more hex digits. - letters A-F in hex integer can either be in upper or lower case. - values available : 1-9, A-F, and 1-f. Java Programming Language

University of the Philippines Cebu College

. Floating-Point Literals - represents a number that has a decimal point in it such as 4.8 Single-Precision Floating Point Numbers - consist of a 32-bit space and are designated by uppercase or lowercase f. Double-Precision Floating Point Numbers - consist of a 64-bit space and are designated by uppercase or lowercase d.

- by default, unless specified, compiler assumes double-precisio - therefore 4.8, is a double-precision floating-point number, and 4.8f is a single-precision floating-point number. Java Programming Language

University of the Philippines Cebu College

When to use Single-Precision or Double-Precision Floats ? - it depends on the size of the number, like if there’s a room to grow out of range or there’s a need of greater precision, declare it double. - compile-time errors occur if a nonzero float literal is out of range.

Range : Single-Precision : ±1.40239846e-45f to ±3.40282347e+38f Double-Precision: 4.94065645841246544e-324 to ±1.79769313486231570e+308 - Floating-point numbers can also be expressed using exponents using uppercase or lowercase e, and scientific notations. Example : 2.1e3f = 2100 Java Programming Language

University of the Philippines Cebu College Boolean Literals - either of the words true or false. - unlike other programming language, you cannot alternate numeric values such any nonzero for true and zero(0) for false. - Booleans are used extensively in control flow logic.

Java Programming Language

University of the Philippines Cebu College Character Literals - programmers often use single character as a value, and in Java, this is represented by character literals. - value : character enclosed in single quotes like ‘j’ - values such as a single quote, backslash, or other nonprintable characters are preceded by a backslash(\) to be part of the command. Example : to characterize the single quote --> ‘\’’ Java Programming Language

University of the Philippines Cebu College Specifying Character Literals Description or Escape Sequence

Any character Backspace(BS) Horizontal tab (HT) Linefeed(LF) Formfeed(FF) Carriage return (CR) Double quote Single quote Backslash Octal bit pattern Hex bit pattern Unicode character Java Programming Language

Sequence Output 'y' '\b' '\t' '\n' '\f' '\r' '\"' '\'' '\\' '\ddd' '\xdd' '\udddd'

y Backspace Tab Linefeed Form feed Carriage return " ' \ Octal value of ddd Hex value of ddd Actual unicode character of dddd

University of the Philippines Cebu College String Literals - sequence of characters enclosed in double quotes such as “Hello World !!!”, or even a “” for a null character string. - can be concatenated. Example : “This is the beginning“ -- one string “ of a new relationship.” -- another string “This is the beginning” + “ of a new relationship.”

- As with character literals, the backslash is used to Javadenote Programming Language

University of the Philippines Cebu College Separators - Java uses the following separators : () [] {} ; , . - compiler uses these to divide the code into segments. - can also be used to force arithmetic precedence evaluation within an expression. - as known, these are useful for visual and logical locators for programmers.

Java Programming Language

University of the Philippines Cebu College

Operators - are symbols used for arithmetic and logical operations. - operators except the plus sign (+), are used only for arithmetic calculations. The + operator can be used in strings literal concatenation. Java Arithmetic Operators Operator Operation Example

+ * / % Java Programming Language

Addition Subtraction Multiplication Division Modulus

a a a a a

+ * / %

b b B b b

University of the Philippines Cebu College Java Assignment Operators Operator = += -= *= /= %=

Operation

Example

Assign value Add to current variable Subtract from current Multiply current Divide current Modulus current

a a a a a a

= 8 += b -= b *= b /= b %= b

Meaning a a a a a a

= = = = = =

8 a a a a a

+ * / %

b b b b b

Java Increment and Decrement Operators Operator Operation Example Meaning ++

--

Increment by 1 Decrement by 1

Java Programming Language

a++ or ++a a-- or --a

a = a + 1 a = a - 1

University of the Philippines Cebu College Java comparison operators (which return true or false)

Operator

Operation

Example

== !=

Equal Not equal

A == b A != b

< >

Less than Greater than

A < b A > b

<=

A <= b Less than or equal Greater than or A >= b equal

>=

Java Programming Language

Meaning Is a equal to b ? Is a not equal to b? Is a less than b? Is a greater than b? Is a less than or equal to b? Is a greater than or equal to b?

University of the Philippines Cebu College Java Bitwise Operators Operator & | ^ << >> >>> ~ <<= >>= >>>= x&=y X|=y x^=y Java Programming Language

Operation Bitwise AND Bitwise OR Bitwise XOR Left Shift Right Shift Zero fill right shift Bitwise complement Left shift assignment Right shift assignment Zero fill right shift assignment AND assignment OR assignment XOR assignment

University of the Philippines Cebu College Logical Operators !

for NOT

Short circuit boolean operators &&

for AND ((a >=b) && (b>=c))

||

for OR ((a>=b) || (b >= c))

Java Programming Language

University of the Philippines Cebu College

Right­Shift Operators >> and >>> •Arithmetic or signed right shift (>>) is used as follows:  128 >> 1 returns 128/21 = 64 256 >> 4 returns 256/24 = 16 -256 >> 4 returns -256/24 = -16 •The sign bit is copied during the shift.  A logical or unsigned right­shift operator (>>>) is:  •Used for bit patterns.  •The sign bit is not copied during the shift. 

Java Programming Language

University of the Philippines Cebu College

Left­Shift Operator (<<)  •Left­shift works as follows:  128 << 1 returns 128 * 21 = 256 16 << 2 returns 16 * 22 =

Java Programming Language

64

University of the Philippines Cebu College String Concatenation With + •The + operator:  •Performs String concatenation  •Produces a new String:  String salutation = "Dr."; String name = "Pete" + " " + "Seymour"; String title = salutation + " " + name; •One argument must be a String object.  •Non­strings are converted to String objects  automatically. 

Java Programming Language

University of the Philippines Cebu College Comment Indicators

Start /* /** //

Text Text Text Text

Java Programming Language

End Comment */ */ (everything to the end of the line is ignored by the compiler)

University of the Philippines Cebu College Primitive Data Types - can only have one value at a time, they cannot reference other data or indicate sequence in a group of data. Primitive Type Keywords - simplest built-inData forms of data in Java. boolean byte char int float double long short

Java Programming Language

University of the Philippines Cebu College Integer Data Type Ranges Type Length Minimum Value byte short int long

8 bits 16 bits 32 bits 64 bits

-128 -32768 -2147483648 -9223372036854775808

Maximum Value 127 32767 147483647 9223372036854775807

Note : During operations, on special cases Java expands smaller integer to the same length in memory of the larger integer, and the resulting value will follow the format of the larger integer. Java Programming Language

University of the Philippines Cebu College char Data Types - 16 bit unsigned integer that represents a Unicode value. Floating Point Data Types float - 32 bit floating-point number. double - 64 bit floating-point number. boolean Data Types - 1-bit logical quantity. Java Programming Language

University of the Philippines Cebu College Reference Data Types - are sequence or identifiers that point to dynamically allocated objects. Reference vs Primitive Data Type - contains the address of a value, rather than the value itself. Advantage - can contain addresses that point to a collection of other data types. Types 1. Array 2. Class 3. Interface Java Programming Language

University of the Philippines Cebu College

Casting  If information might be lost in an assignment, the  programmer must confirm the assignment with a cast.  •The assignment between long and int requires an explicit  cast.  long bigValue = 99L; int squashed = bigValue; // Wrong, needs a cast int squashed = (int) bigValue; // OK int squashed = 99L; // Wrong, needs a cast int squashed = (int) 99L; // OK, but... int squashed = 99; // default integer literal Java Programming Language

University of the Philippines Cebu College

Promotion and Casting of Expressions  •Variables are automatically promoted to a longer form  (such as int to long).  •Expression is assignment­compatible if the variable type is  at least as large (the same number of bits) as the  expression type.  long bigval = 6; int smallval = 99L; double z = 12.414F; float z1 = 12.414; Java Programming Language

// 6 is an int type, OK // 99L is a long, illegal // 12.414F is float, OK // 12.414 is double, illegal

University of the Philippines Cebu College Expression Evaluation Order - Java evaluates from LEFT to RIGHT Precedence Rules Highest [] -new (type) expression * + << < == & ^ && || ?: = Java Programming Language

Lowest () ! / >> > !=

Op=

~

instanceof

% >>> <=

>=

University of the Philippines Cebu College Sample Declarations Integer types byte short int long

byteVar; shortVar; intVar; longVar;

//8 bits //16 bits //32 bits //64 bits

Floating-Point Types float double

floatVar; doubleVar;

//32 bits //64 bits

Character Types char charVar1; char charVar2 = ‘y’; and assigns y to it

Java Programming Language

//holds one character //declares variable //

University of the Philippines Cebu College

Arrays char myCharArray[]; char twoDimArray[][]; int integerArray[]; int[]integerArray;

Java Programming Language

//one-dimensional array //two-dimensional array //one-dimensional array of integers //equivalent to integerArray[];

University of the Philippines Cebu College Sample Operations Unary Operations myHeight++; //myHeight is incremented by 1 myWeight--; //myWeight is decremented by 1

Assignment Operations a = 5; a -= 7; a +=8 a /=4

//assigns 5 to a //assigns a-7 to a //assigns a+8 to a //assigns a/4 to a

Binary Operations c = b + 5;

// b+5 is the binary operation

Arithmetic Operations a = c / b + (45*a/d) - 283

Java Programming Language

University of the Philippines Cebu College Control Flow - instructs the program how to make a decision and how further processing should proceed based on the decision. Building Blocks of Control Flow ( , ) , if , while , do, for, switch - each of these can be used to control how your program executes by determining the result of your conditional expression.

Java Programming Language

University of the Philippines Cebu College

Blocks and Statements Statement - is a line of code ending in a semicolon. - can either be an expression, a method call, or an declaration. Block - is a group of statements that form a single compound stmt. - { } collects statements into one group

Java Programming Language

University of the Philippines Cebu College Conditional Expressions - are used to evaluate whether a condition is true or false and will branch out to different sections of code on the basis of the answer.

if construct if (expression) statement; if (expression) { statement(s); } Java Programming Language

University of the Philippines Cebu College

Sample if Statement int number=10; if ( (number % 2) == 0) { System.out.println(“even”); } else { System.out.println(“odd”); }

Java Programming Language

University of the Philippines Cebu College

switch construct - a variation of the if statement is the switch statement, which performs a multi-way branch instead of a simple binary branch. Form : switch (expression) { case value : statement(s); break; case value : statement(s); break; . . . . . . . default : statement(s); break; } Java Programming Language

University of the Philippines Cebu College Sample switch Statement static void ParseChar (char KeyboardChar) { switch (KeyboardChar) { case ‘l’: System.out.println(“left”); break; case ‘r’: System.out.println(“right”); break; case ‘q’: //note no break here, falls through case ‘\n’: break; case ‘h’ : //note no break here either

}

default : System.out.println(“Syntax: (l)eft, (r)ight, (q)uit”); System.out.println(“Please enter a valid character”); break; }

Java Programming Language

University of the Philippines Cebu College Looping Expressions - generally continues to loop through a section of code until a certain condition is met. - conditions are checked before or after executing code sections depending on the loop construct used.

while loops Form: while ( expression ) statement; or while ( expression ) { statement(s); } Java Programming Language

University of the Philippines Cebu College

Sample while loop public static long factorial(int n) { long prod = 1; int i = 1; while ( i <= n ) { prod *= i++; } return prod; }

Java Programming Language

University of the Philippines Cebu College do-while loops Form: do statement; while ( expression) ; or do { statement(s); }while (expression) ;

Java Programming Language

University of the Philippines Cebu College

Sample do-while loop public static long factorial(int n) { long prod = 1; int i = 1; do { prod *= i++; } while ( i <= n); return prod; }

Java Programming Language

University of the Philippines Cebu College

for loops Form: for (initialization; expression; modification) statement; or for (initialization; expression; modification) { statement(s); }

Java Programming Language

University of the Philippines Cebu College

Sample for loop public static long factorial(int n) { long prod = 1; for (int i=1; i <= n; i++) { prod *= i; } return prod; }

Java Programming Language

University of the Philippines Cebu College break - used to break out of the middle of for, while, or do loop. Sample Code : for (int index=0; index < ArraySize; index++) { if (Array[index] < 0) { System.out.println(“ERROR: Negative number, index =“ + ix); break; } ProcessArray(Array[index]); }

Java Programming Language

University of the Philippines Cebu College

continue - can be used to short-circuit parts of a for, do, or while loop.

Sample Code :

for (int index=0; index < ArraySize; index++) {

if (Array[index] < 0) { System.out.println(“ERROR: Negative number, index =“ + ix); continue; } ProcessArray(Array[index]); } Java Programming Language

University of the Philippines Cebu College Using break with labels: 

Using continue with labels: 

outer: do { statement; do { statement; if (boolean expression) { break outer; } statement; } while (boolean expression); statement; } while (boolean expression);

test: do { statement; do{ statement; if (condition is true) { continue test; } statement; } while (condition is true); statement; } while (condition is true);

Java Programming Language

Related Documents

Java Fund
November 2019 0
Java Java
June 2020 44
Java
November 2019 24
Java
November 2019 26
Java
December 2019 27
Java
November 2019 23