Week 2 - Java Basics

Week 2 - Java Basics

Java Basics I EE422C - Software Design and Implementation II (Thanks to Edison Thomaz) Java Basics History and Language Characteristics Hello World

Program Structure Java API and Hierarchy Compilation and VM Primitive Data Types Control Statements Variable Storage Models Garbage Collection Week 1 Recitation Installing Java 8 Getting started with Java development setup

Code and run a simple HelloWorld program Open Github account Questions of what we covered in class Development started in June 1991 Sun Microsystems (acquired by Oracle in 2009) Designed for interactive television Released in 1995/1996 5 primary goals for creating a new language simple, object-oriented, and familiar robust and secure architecture neutral and portable high-performance interpreted, threaded and dynamic James Gosling Inventor of Java programming language

HelloWorld.java filename must match public class name public class HelloWorld { public static void main(String[] args) { // Display a greeting in the console window System.out.println("Hello, World!"); } } Program Run: Hello, World!

The Structure of a Simple Program Classes are the fundamental building blocks of Java programs: public class HelloWorld starts a new class and defines a blue-print for HelloWorld Every source file can contain at most one public class The name of the public class must match the name of the file containing that class: Source code for class HelloWorld must be contained in a file named HelloWorld.java Every Java application contains a class with a main method When the application starts, the instructions in the main method are executed public static void main(String[] args) { . . . }

declares a main method which can take an array of Strings as an argument (usually file names for late binding) The Structure of a Simple Program: Statements Syntax is just like C: free format, tokens and delimeters same The body of the class and of the main method contains statements inside the curly brackets ({}) Each statement ends in a semicolon (;) Statements are executed one by one Our example program has a single executable statement: System.out.println("Hello, World!"); which prints a line of text on the standard output device (console): Hello, World!

The Guts of a Simple Program: e.g. Method Calls System.out.println("Hello, World!"); is a method call of the form object.methodName(parameter-arguments); An instance method (not static) call requires: 1. The object that you want to use (in this case, System.out) specifically the out object found in the System class (which is defined to be the standard output device, i.e. the console/screen) 2. The name of the method you want to use (in this case, println) a method which prints out a string of text followed by a new line character 3. Parameter arguments enclosed in parentheses (()) containing any other information the method requires (in this case the String, "Hello, World!") Arguments

Objects - Example Object: an instance of a class and can contain data elements and methods (e.g., System.out belongs to the class PrintStream) System.out printf Methods Method: sequence of instructions that accesses the data elements of an object You manipulate objects by calling its related methods Class (as the blue print of an object), determines the legal methods for that object: String greeting = "Hello, World!"; greeting.println() // Error,no println method in String

System.out.println(greeting); // OK greeting.length() // OK 2 different kinds of methods: static and instance static methods work just like C functions called by name Instance methods require an object reference, e.g. above Methods Static or class methods Called as in -> [Classname.]method(arguments); All method arguments are passed to their formal parameters by call-by-value Primitive types: value is passed to the method Method may modify local copy but will not affect callers value Object reference: address of object is passed

Change to reference variable does not affect caller But operations can affect the objects state, visible to caller Simple static methods - summary public class MinTest { public static void main( String [ ] args ) { int a = 3; int b = 7; System.out.println( min( a, b ) ); } // method definition public static int min( int x, int y ) { return x < y ? x : y;

} } Another analogy a class public class Car wheels engine headlights tires accelerate() brake() turnOnLights() turnOffLights() Another analogy an object myCar = new Car(); myCar.turnOnLights()

myCar.accelerate() Java Organizing Concept Java API Libraries Packages Classes Methods Statements Tokens Made of symbols from Java alphabet Grouping Classes: The Java API API = Application Programming Interface A package consists of some related Java

classes: Swing: a GUI (graphical user interface) package AWT: Abstract Window Toolkit (more GUI) util: utility data structures (important to us) 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 an application program) Accessibility Specifications access specifiers (public, private, and protected) are placed on each definition for each member of a class (rather then on a block of members as in C++) as well as the class itself The class, and each variable or method within the class

(that is not inside a method), has an access specifier to determine whether its visible outside the file or class that it is in Without an explicit access specifier, a class member defaults to "friendly," which means that it is accessible to other elements in the same package (a package is a collection of classes being friends) Inside of methods - variables, etc. are treated as usual (local) Portability Java is (an interpreted) write once, run anywhere language. Uses a virtual machine (VM) concept Write once, run everywhere (nearly) NEVER works with C/ C++, but does (nearly) ALWAYS work with JAVA. The biggest potential stumbling block is speed:

Interpreted Java runs in the range of 20 times slower than C. But: nothing prevents the Java language from being compiled and there are just-in-time (JIT) compilers that offer significant speed-ups. Running a program 1. Write it. code or source code: The set of instructions in a program. 2. Compile it. compile: Translate a program from one language to another. byte code: The Java compiler converts your code into a format named byte code that runs on many computer types. 3. Run (execute) it. output: The messages printed to the user by a program. source

code compile byte code output run 20 Running a program 21 Primitive Java is just like C (within methods)

Syntax free form, case sensitive, punctuation same Comments Primitive data types same except char Constants

Declaration and initialization statements Basic operators Relational, equality, logical operators Type conversions Conditional statements Iteration statements Break and continue statements Conditional operator ? Static methods (=> C functions) java: differences from C/C++

no typedefs, no #defines, No preprocessor no structures, unions no functions (~= static methods) no multiple inheritance no goto http://www.cs.utexas.edu/~EWD/ewd02xx/EWD215.PDF no operator overloading no pointer data type, no pointer arithmetic 23 Reserved Words in JAVA(58) abstract boolean break byte case

cast catch char class const continue default do double else extends false final finally float for

future generic if implements import inner instanceof int interface long native new null operator outer package

private protected public rest return short static super switch synchronized this throw throws transient true try

var void volatile while Identifiers Identifier: name of a variable, method, or class Rules for identifiers in Java: Can be made up of letters, digits, underscores (_) and dollar signs ($) Cannot start with a digit

Cannot use other symbols such as ? or % Spaces are not permitted inside identifiers You cannot use reserved words such as public They are case sensitive By convention, variable names start with a lowercase letter Camel case: Capitalize the first letter of a subsequent word in a compound name such as farewellMessage By convention, class names start with an uppercase letter Should not use the $ symbol at the beginning of your names intended for names that are automatically generated by tools Identifier names must be meaningful and explainable to someone else These are very strong conventions! Identifiers legal:_myName

TheCure ANSWER_IS_42 bling$ illegal: me+u 49ers side-swipe Ph.D's double my Name 26 Comments are almost like C /* This kind of comment can span multiple lines of text as many as you need */ // This kind is to the end of the line only

/** * This kind of comment is a special * javadoc style comment which we will * use for API style auto documentation */ Data Types All values have a type Primitive types Represent numbers, characters, boolean values Integers: byte, short, int, and long

Real numbers: float and double Characters: char Truth values: boolean (true or false) Non primitive types are objects, aka Reference types (not really pointers no arithmetic), class instances java: type safety strongly typed language there cannot be any type errors when the program runs automatic storage management no dangling pointers array index bounds checking

29 Primitive Data Types Type Description int The integer type, with range -2,147,483,648 . . . 2,147,483,647 4 bytes byte The type describing a single byte, with range -128 . . . 127

1 byte short The short integer type, with range -32768 . . . 32767 2 bytes long The long integer type, with range -9,223,372,036,854,775,808 . . . 9,223,372,036,854,775,807 8 bytes double

Size The double-precision floating-point type, with a range of about 10308 and 8 bytes about 15 significant decimal digits float The single-precision floating-point type, with a range of about 1038 and about 7 significant decimal digits 4 bytes char The character type, representing code units in the Unicode encoding

scheme 2 bytes boolean The type with the two truth values false and true 1 bit Operators/Precedence 1. subscript [ ], method 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 | 10. logical (sequential) and && 11. logical (sequential) or || 12. conditional cond ? true-expr : false-expr 13. assignment =, compound assignment += -= *= /= <<= >>= >>>= &= |= Use ( ) to force a specific order of expression evaluation Type Compatibility and Conversions Compatible types converted automatically e.g. int to long Incompatible would be like double to byte, or char to boolean Incompatible types must use cast

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 without loss of information byte to short to int to long int kind to float to double Narrowing conversion Must case, result with be modulo smaller type range The Class Math 33 Math Methods Use

Called using the form Math.methodname (x , y); A math method call becomes a value as a result. These can be used in any arithmetic expression. These methods are in the standard Java.lang library that gets included automatically with all programs. You dont need to import it. // for example, double x, y; y = 179.66; x = Math.sqrt (y) + 15.33;

The Char Data Type char firstLetter = A; //example char variable declaration Used for readable text and keyboard symbols A character is stored in 16 bit Unicode representation, the rightmost 8 bits is ASCII for English language symbols e.g. the letter A is 00000000 01000001 (in binary) which is 65 in decimal see Unicode web site for the definition of all represented character symbols http://www.unicode.org/ chars can be compared using relational operators For Example:( assume the usual program plumbing exists) char letter1 = b, letter2 = Z; if (letter1 < letter2) System.out.println (1st letter smaller);

ASCII Character Subset ASCII Character Set is a subset of the Unicode from \u0000 to \u007f \u means unicode First digit Second digit Unicode Format - escapes Description Escape Sequence Backspace \b

\u0008 Tab \t \u0009 Linefeed \n \u000a Carriage return \r

\u000d Unicode(hex) Casting between char and Numeric Types Automatic conversions done as in C int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97;

Control statements are like C if (x < y) smaller = x; if (x < y){ smaller=x; sum = sum + x;} else { smaller = y; sum = sum + y; } BUT: the conditions must be boolean ! while (x < y) { y = y - x; } do { y = y - x; } while (x < y) for (int i = 0; i < max; i++) sum =sum + i; break; continue; work like C Control statements/2

Conditional operator ? short hand for simple if-else int x, y, minVal; // . . . minVal = x<=y ? x : y; Switch statement switch( someCharacter ) { case '(': case '[: case '{': // Code to process opening symbols break; case ')': case ']': case '}': // Code to process closing symbols break;

case '\n': // Code to handle newline character break; default: // Code to handle other cases } Could also be an integer expression Variable Storage Modes variables that are declared inside the body of a method are local (automatic storage) created when the method body is executed and disappear when the method body terminates. A variable declared outside the body of a method is global to the whole class.

Its scope outside the class is determined by its access specifier (public, private, protected, blank) A static variable is allocated once, and remembers static final variables are used as symbolic constants. E.g. static final double PI = 3.1416; symbolic constants are defined in uppercase. If several words are needed they are separated by the underscore character, e.g. MAX_INT_VALUE. The static modifier A static variable is a class level variable, not an instance variable; in effect shared by all objects if not inside a method A static method is a class level method, not an instance method Encapsulates some computation task Cannot refer to this or super

A static block in a class can be declared to initialize static variables; it is run once when the class is loaded static { // static variable inits here } The final Modifier The final class cannot be extended (no subclasses): final class Math {...} The final variable is a constant: final static double PI = 3.1416; The final method cannot be modified by any

subclasses. Garbage Collection When a constructed object is no longer referenced by any object variable, the memory it consumes will automatically be reclaimed. No delete or destructors. The JVM runtime system guarantees that as long as it is possible to access an object by a reference, or a chain of references, the object will never be reclaimed. Once the object is unreachable by a chain of references, it can be reclaimed at the discretion of the runtime system if memory is low. It is possible that if memory does not run low, the

virtual machine will not attempt to reclaim these objects. Garbage Collection Garbage collection means memory leaks are much harder to cause in Java, but not impossible. If you make native (non Java) method calls that allocate storage, these are typically not tracked by the garbage collector. The garbage collector is a huge improvement over C+ +, and makes a lot of programming problems simply vanish. It might make Java unsuitable for solving a small subset of problems that cannot tolerate a garbage collector, but the advantage of a garbage collector seems to greatly outweigh this potential drawback.


Recently Viewed Presentations



    OUR FOCUS. Student Involvement & Success. Social Justice. Service. Leadership. Dig deeper… What do our programmatic areas support? While we have 9 programmatic areas ranging from Fraternity & Sorority Life to Women's Programs, our main focuses are: Leadership, Service, and...
  • Organizational Behavior - Western Oregon University

    Organizational Behavior - Western Oregon University

    Organizational Behavior Organizational Citizenship Behavior ... Justice Input Structure Organizational Citizenship Behavior Altruism Conscientiousness Courtesy Sportsmanship Civic Virtue Determinants of OCB Big 5 Personality Traits Organizational Culture A system of shared meanings that result ...
  • A kínai tőzsdepánik - Pécsi Tudományegyetem

    A kínai tőzsdepánik - Pécsi Tudományegyetem

    The Guanxi - ChineseSchool of IR. A type of social connections in traditional Chinese society - long forming period and very flexible. The generalized form of xiao (孝) - the most important connection of the Chinese family. Based on Confucian...
  • La rgionalisation de limmigration et la  fabrication  de

    La rgionalisation de limmigration et la fabrication de

    La régionalisation de l'immigration et la « fabrication » de l'élève immigrant Diane Farmer Université de Toronto 78e Congrès de l'Acfas
  • Assessment in Reception - Greysbrooke Primary School

    Assessment in Reception - Greysbrooke Primary School

    Until last year the way teachers did this varied, last year the government introduced 3 standardised Baseline testing providers (this may change again). At Greysbrooke this year we have used the CEM (Centre for Evaluating and Monitoring) baseline test from...
  • Literary Device - Allusion

    Literary Device - Allusion

    Literary Device - Allusion. An allusion is a reference or mention to a figure or event from an outside source, factual or fictitious. Most literary allusions hinge on references to religious or mythological tales, other published literary works, and historical...
  • 2. Discussion question It has been suggested that

    2. Discussion question It has been suggested that

    Exclusion or exemption clauses can be included when unusual situations are expected. Once agreed, get developers and sponsors to sign the project scope statement. 3. Project charter Used to get authorization for a project and includes: project title project sponsors...
  • COM/BLM 376 Computer Architecture

    COM/BLM 376 Computer Architecture

    However,many systems allow addressing at the byte level. In any case, the relationshipbetween the length in bits . A . of an address and the number . N . of addressableunits is 2. A = N. Unit . of transfer:...