universidad nacional de colombia facultad de ingeniería departamento de sistemas
DESCRIPTION
C. ertificación en. J. AVA. Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas. 1. LANGUAGE FUNDAMENTALS. Source Files Keywords and Identifiers Primitive Data Types Literals Arrays Class Fundamentals Argument Passing Garbage collection. Source Files. - PowerPoint PPT PresentationTRANSCRIPT
Universidad Nacional de Universidad Nacional de ColombiaColombia
Facultad de IngenieríaFacultad de Ingeniería
Departamento de SistemasDepartamento de Sistemas
ertificación enertificación en
AVAAVA
1. LANGUAGE 1. LANGUAGE FUNDAMENTALSFUNDAMENTALS
Source FilesSource Files
Keywords and IdentifiersKeywords and Identifiers
Primitive Data TypesPrimitive Data Types
LiteralsLiterals
ArraysArrays
Class FundamentalsClass Fundamentals
Argument PassingArgument Passing
Garbage collectionGarbage collection
Source FilesSource Files ““.java” extension .java” extension At most one top-level public class definition At most one top-level public class definition
(unlimited number of non-public class (unlimited number of non-public class definitions)definitions)
Class name= unextended filenameClass name= unextended filename Three top-level elements (None of them Three top-level elements (None of them
required)required)
1.1. Package declarationPackage declaration(package)(package)1.1. import statementsimport statements2.2. Class definitionsClass definitions
Test.javaTest.java
// Package declaration// Package declarationpackage exam.prepguide;package exam.prepguide; // Imports// Importsimport java.awt.Button; // a import java.awt.Button; // a
classclassimport java.util.*; // a packageimport java.util.*; // a package // Class Definition// Class Definitionpublic class Test { ... }public class Test { ... }
Keywords and Keywords and IdentifiersIdentifiers
Keywords and reserved words may Keywords and reserved words may notnot be be used as identifiers!!used as identifiers!!
An identifier An identifier mustmust begin with a letter, a dollar begin with a letter, a dollar sign (‘$’), or an underscore (‘_’); subsequent sign (‘$’), or an underscore (‘_’); subsequent characters may be letters, ‘$’, ‘_’ , or digitscharacters may be letters, ‘$’, ‘_’ , or digits
Identifier :Identifier : word used by a programmer to name a word used by a programmer to name a variable, method, class, or labelvariable, method, class, or label
Primitive Data TypesPrimitive Data Types
BooleanBoolean variablesvariables : : truetrue oror falsefalse 4 signed integral data types:4 signed integral data types:
byte, short, intbyte, short, int andand longlong
TypeType RepresentationRepresentation Minimum Maximum Minimum Maximum (bits)(bits)
• booleanboolean 11• charchar 1616 0 0 221616-1-1• bytebyte 88 -2 -277 2277-1-1• shortshort 1616 -2 -21515 221515-1-1• intint 3232 -2 -23131 223131-1-1• longlong 6464 -2 -26363 226363-1-1• floatfloat 3232• doubledouble 6464
Char:Char: 16-bits encoding
Floating-point types:floatfloat and double double IEEE 754 specification
tt
t[0]t[0] t[1]t[1] t[2]t[2]t[3]t[3] t[4]t[4]
Float.NanFloat.NanFloat.NEGATIVE_INFINITYFloat.NEGATIVE_INFINITYFloat.POSITIVE_INFINITYFloat.POSITIVE_INFINITYDouble.NanDouble.NanDouble.NEGATIVE_INFINITYDouble.NEGATIVE_INFINITYDouble.POSITIVE_INFINITYDouble.POSITIVE_INFINITY
Nan:Nan: Not a numberNot a number
1. double d=-10.0/0.0;1. double d=-10.0/0.0;2. if (d==Double.NEGATIVE_INFINITY) {2. if (d==Double.NEGATIVE_INFINITY) {3.3. System.out.println(“d just exploded”+d);System.out.println(“d just exploded”+d);4. }4. }
LiteralsLiterals
boolean:boolean:
boolean isBig=true;boolean isBig=true;
boolean isLittle=true;boolean isLittle=true;
A value that may be assigned to a A value that may be assigned to a primitive or string variable or primitive or string variable or passed as an argument to a passed as an argument to a
method callmethod call
t[0]t[0] t[1]t[1] t[2]t[2]t[3]t[3] t[4]t[4]
char:char:
char c=´w´;char c=´w´;
char c= ´\u4567´;char c= ´\u4567´;
Unicode Unicode hexadecimalhexadecimal
´́\\n’n’ new linenew line´́\\r’r’ returnreturn´́\\t’t’ tabtab´́\\b’b’ backspacebackspace´́\\f’f’ formfeedformfeed´́\\’ ’’ ’ single quotesingle quote´́\\” ’” ’ double quotedouble quote´́\\\\ ’ ’ backslashbackslash
SPECIAL CHARACTERS SPECIAL CHARACTERS
Literals ...Literals ...
integralintegral2828034034 (octal)(octal) 0x1c0x1c0X1c0X1c0x10x1CC
floating pointfloating point• Decimal point : Decimal point : 1.4141.414• Letter E or e (scientific notation):Letter E or e (scientific notation):
4.23E+214.23E+21• Suffix f or F (float 32 bits)Suffix f or F (float 32 bits)
1.828f1.828f• Suffix D or d (double 64 bits):Suffix D or d (double 64 bits):
1234d1234d(default: double 64 bits)(default: double 64 bits)
String:String:
String s =“Characters in strings are 16 bits”;String s =“Characters in strings are 16 bits”;
Arrays ...Arrays ...
t[0]t[0] t[1]t[1] t[2]t[2]t[3]t[3] t[4]t[4]
An ordered collection of primitives, object references, or other arrays
Homogeneous:Homogeneous: elements of the same typeelements of the same type
1.1. Declaration:Declaration: name and type of its elementsname and type of its elements2.2. ConstructionConstruction3.3. InitializationInitialization
Array declarationArray declarationint ints[];int ints[];
double dubs[];double dubs[];
Dimension dims[];Dimension dims[];
float toDee[] [];float toDee[] [];
[][] can come before or after the array namecan come before or after the array name
myMethod(double dubs myMethod(double dubs [])[])
myMethod(double[] myMethod(double[] dubs)dubs)
double[] double[] anotherMethod()anotherMethod()
double anotherMethod() double anotherMethod() [][]
Arrays...Arrays...
The declarationThe declaration DOES NOTDOES NOT specify the size of specify the size of an array!! Array size is specified atan array!! Array size is specified at runtimeruntime via thevia the newnew keywordkeyword
1.1. int intsint ints[]; // Declaration to the compiler[]; // Declaration to the compiler2.2. ints=new intints=new int[25]; // Run time construction[25]; // Run time construction
1.1. int size=1152*900int size=1152*900;;2.2. int rasterint raster[];[];3.3. rater=new intrater=new int[size];[size];
Size can be specified with aSize can be specified with a VARIABLEVARIABLE
1.1. int intsint ints[][]=new int=new int[25];[25];
Declaration and construction in a single lineDeclaration and construction in a single line
automaticautomatic initialization when an array is initialization when an array is constructedconstructed
ElementElement Initial Initial TypeType ValueValue booleanboolean falsefalse charchar ‘‘\\u0000’u0000’ bytebyte 00 shortshort 00 intint 00 longlong 0L0L floatfloat 0.0f0.0f doubledouble 0.0d0.0d object reference nullobject reference null
Automatic Initialization Automatic Initialization
1.1. float diametersfloat diameters[][]={1.1f, 2.2f, 3.3f, 4.4f, ={1.1f, 2.2f, 3.3f, 4.4f, 5.5f};5.5f};
InitializatioInitializationn
1.1. long squareslong squares[];[];2.2. squares =new longsquares =new long[6000];[6000];3.3. for (int i=0; i<6000; i++)for (int i=0; i<6000; i++)4.4. squaressquares[i]=i*i;[i]=i*i;
Class FundamentalsClass Fundamentals
main() method main() method Entry point for JAVA applications Entry point for JAVA applications Application:Application: class that includesclass that includes main()main() Execution:Execution: java at the command line, java at the command line,
followed by the name of the classfollowed by the name of the class
public static void main(String argspublic static void main(String args[][]))
% java Mapper France Belgium% java Mapper France Belgium
Command lineCommand line
argsargs[1]=“France”[1]=“France”args[2]=“Belgium”args[2]=“Belgium”
Variables and initializationVariables and initialization Member Variable:Member Variable:
When an instance is createdWhen an instance is created Accessible from any method in the Accessible from any method in the
classclass Automatic (Local) Variable:Automatic (Local) Variable:
On entry to the methodOn entry to the method Exists only during execution of the Exists only during execution of the
methodmethod Only accessible within the methodOnly accessible within the method
1.1. class HasVariables {class HasVariables {2.2. int int x=20;x=20;3.3. static int y =30;static int y =30;
public int wrong() {public int wrong() { int i;int i; return i+5;return i+5;}}
public double fourthRoot(double d) {public double fourthRoot(double d) { double result;double result; if (d>=0) {if (d>=0) { result=Math.sqrt(Math.sqrt(d));result=Math.sqrt(Math.sqrt(d)); }} return result;return result;}}
Error: “variable i may not have been initialized”
Error: “variable result may not have been initialized”
public double fourthRoot(double d) {public double fourthRoot(double d) { double result=0.0; // initializedouble result=0.0; // initialize if (d>=0) {if (d>=0) { result=Math.sqrt(Math.sqrt(d));result=Math.sqrt(Math.sqrt(d)); }} return result;return result;}}
Correct Initialization!!Correct Initialization!!
Argument passingArgument passing
AA copycopy of the argument that gets passedof the argument that gets passed
double radians=1.2345;double radians=1.2345;System.out.println(“Sine of”+radiansSystem.out.println(“Sine of”+radians +”=“+Math.sin(radians));+”=“+Math.sin(radians));
Changes to the argument valueChanges to the argument value DO NOTDO NOT affect the original dataaffect the original data
Argument passing ...Argument passing ...
public void bumper(int bumpMe) {public void bumper(int bumpMe) { bumpMe+=15;bumpMe+=15;}}
int xx=12345;int xx=12345;bumper(xx);bumper(xx);System.out.println(“Now xx is”+xx);System.out.println(“Now xx is”+xx);
Object ReferenceObject Reference
Button btn;Button btn;Btn=new Button(“Ok”);Btn=new Button(“Ok”);
When an object is created, a value (bit When an object is created, a value (bit pattern) that identifies the object is pattern) that identifies the object is returnedreturned
Button btn;Button btn;btn = new Button(“Good”);btn = new Button(“Good”);replacer(btn);replacer(btn);System.out.println(btn.getLabel());System.out.println(btn.getLabel()); public void replacer(Button replaceMepublic void replacer(Button replaceMe) {) { replaceMe=new Button(“Evil”);replaceMe=new Button(“Evil”);}}
The string printed out isThe string printed out is ”Good””Good”
TextField tf;TextField tf;tf = new TextField(“Yin”);tf = new TextField(“Yin”);changer(tf);changer(tf);System.out.println(tf.getText());System.out.println(tf.getText()); public void changer(TextField changeMepublic void changer(TextField changeMe) {) { changeMechangeMe.setText(“Yang”);.setText(“Yang”);}}
The string printed out isThe string printed out is ”Yang””Yang”,, notnot ”Yin””Yin”
How to create a Reference to a How to create a Reference to a primitiveprimitive
public class PrimitiveReference {public class PrimitiveReference { public static void main( String args public static void main( String args [])[]) int int [] myValue ={ 1 };[] myValue ={ 1 }; modifyIt(myValue);modifyIt(myValue); System.out.println(“myValue contains “+ System.out.println(“myValue contains “+
myValue[0]);myValue[0]); }} public static void modifyIt(int public static void modifyIt(int [] value) {[] value) { value [0]++;value [0]++; }} }}
Garbage CollectionGarbage Collection
Storage can remain allocated longer than Storage can remain allocated longer than the lifetime of any method callthe lifetime of any method call
releasing the storage when you have releasing the storage when you have finished with it:finished with it:
Corrupted data:Corrupted data: releasing storagereleasing storage too too soonsoon
Memory Shortage:Memory Shortage: forgetforget to release itto release it
Automatic Garbage Collection:Automatic Garbage Collection:The runtime system keeps track of the memory The runtime system keeps track of the memory that is allocated and determines whether it is still that is allocated and determines whether it is still usableusable
Garbage collector:Garbage collector: Low-priority threadLow-priority thread
public Object pop() { public Object pop() { return storage[index--];return storage[index--];}}
public Object pop() {public Object pop() { Object returnValue=storage [index];Object returnValue=storage [index]; storage[index--] =null;storage[index--] =null; return returnValue;return returnValue;}}