910 likes | 933 Views
Learn the fundamentals of Java programming, including syntax, semantics, and program structure. Explore how Java differs from other languages and how to execute and interpret Java programs.
E N D
Programming • For the next ten weeks you will learn basic programming principles • There is much more to programming than knowing a programming language • When programming you need to use a tool, in this case the tool will be a language • In this course you will use java to explore programming • You will use other languages to program Java
Syntax and Semantics • When using a programming language you must understand both the syntax and the semantics of the language. • Syntax refers to the rules you must follow to form valid statements in the language. • The syntax of a language is like English grammar. • Semantics describe the meaning of a statement in a language. Java
What Is Java? • Java started as a programming language for embedded systems (toasters, microwave ovens, washers, etc.). • needed to be portable. • had to be reliable. • The original language was called oak (rumor has it that Gosling has a large oak tree outside the window of his office). Marketing decided Java was a better name. Java
Sun’s Slant • According to Sun: • Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language • Java is a lot like C/C++ but there are a number of important differences Java
Program Structure • A program in Java consists of one or more class definitions. One of these classes must define a method main( ), which is where the program starts running // A Java Hello World Program public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello World" ); } } Java
How Is Java Different • Java differs from other popular languages: • It is interpreted • Architecture neutral • There are no C/C++ style pointers, only references • Garbage collected • Comes with a sophisticated class library • Includes support for concurrency, networking, and graphics Java
Interpreted Languages • An interpreter translates and immediately executes a program • Someone, who understands German, reads the book in German and translates while reading to English Source Code Execute interpret Java
Executing Java Programs Java Source Program emacs filename.java javac filename.java Java Compiler Java Class File java filename Win98/NT JVM MacOS JVM Solaris JVM Java
Java Environments • There are lots of commercial Java programming environments. • IBM’s Visual Age. • Visual J++. • Semantic Café. • many others (most of which cost money). • Sun provides the JDK (Java development Kit) for free. Java
The JDK • The JDK consists of the following: • The Java development tools, including the compiler, debugger and the Java Interpreter. • The Java class libraries organized as a collection of packages. • A number of demonstration programs. • Various supporting tools and components, including the source code of the classes in the library. • Get it from http://www.java.sun.com. Java
Java Resources • Java Home Page • http://www.java.sun.com (http://www.javasoft.com) • The Java Tutorial • http://www.java.sun.com/docs/books/tutorial • Java Developer Connection • http://developer.java.sun.com • The Swing Connection • http://java.sun.com/products/jfc/tsc Java
Other Resources • RIT Course Pages • http://www.cs.rit.edu/~cs1 • NT-EMACS • http://www.cs.washington.edu/homes/voelker/ntemacs.html • JDE • http://sunsite.auc.dk/jde/ Java
Applications and Applets • Java programs come in two forms: • Applications. • Applets. • Applets typically are downloaded into a browser and are run by the Java Virtual Machine that is part of the browser. • Usually are restricted as to what they can do. • Applications are standalone programs that can do just about anything. Java
Basic Java Syntax • The Java language will be described by working through its features: • variable types and expressions. • selection and iteration. • classes. • exceptions. • Small sample programs will be provided to illustrate how each feature is used. Java
Things & Stuff • Any program that you will write will manipulate things • Numbers • Strings • Objects • … • We need to be able to refer to these sorts of items in a program Java
Identifiers • Identifiers are used in a programming language to refer to things • You can think of an identifier as a shortcut to a memory location somewhere in the computer • Declarations in a program introduce identifiers and the type of thing they will refer to • All identifiers must be declared before they may be used Java
Rules • Identifiers • start with an alphabetic character • can contain letters, digits, or “_” • are unlimited in length • Examples Answer, total, last_total, relativePosition, gridElement Person, Place, Stack, Queue Java
Identifiers • Identifiers in Java are composed of a series of letters and digits where the first character must be a letter. • Identifiers should help to document what a classes, variables, or methods are used for. • Upper and lower case letters are different in Java. • ThisOne is not the same as thisOne. • Identifiers should not include punctuation and can not include spaces. Java
Identifiers • A good programming standard for identifiers composed of multiple words is to capitalize the first character of the additional words. • The case of the first letter of the first word will depend upon the use of the identifier. • For Example, • myCar, or bobAndSusieAreFriends Java
Identifiers • Class names begin with a capital letter. • This standard makes it easier to understand which identifiers represent classes. • In the MyFirstApplication we have two class names: • MyFirstApplication and MainWindow Java
Identifiers • Variable (object names) and method names begin with a lower case letter. • In MyFirstApplication we have one object: • mainWindow • Note that mainWindow is different from MainWindow. • In MyFirstApplication we have one method: • main(…) Java
Creating a Java Program • The first step to creating a Java program is to define a class containing the main method. • The MyFirstApplication program on page 39 of Wu is an example of a Java class containing a main method. • This Java class definition can be thought of as the driver class or the ring leader class. Java
Declaring Variables • The basic syntax for declaring variables is: • typename identifer; • It is possible to declare two or more variables of the same type in a single declaration statement, although this is NOT recommended (See RIT Java Coding Standard). Java
Categories of Variables • There are two categories of variables: • Variables of primitive type which directly contain a representation of a value of a primitive type. • Variables of a reference type which hold a reference to an object or the value null (which is the null reference). • All variables must be declared and initialized before being used. Java
Primitive Types • The primitive types represent the basic, built-in types that are part of the Java language. • Two basic categories: • Boolean - boolean. • Numeric. • Integer - byte, short, int, long, char. • Floating point - float, double. Java
Primitive Data Types • The Java primitive data types each have a set size (# of bits) and value range. • Same on every type of computer (PC, Mac, Sun workstation) that runs Java programs. • This is not true with other programming languages. Java
Primitive Types Note: these types are platform independent Java
Primitive Types Java
Real Values • Real or floating point numbers are represented in scientific notation inside a computer. The number is divided up into two parts the mantissa and the exponent: • The mantissa contains a number between -1.0 and 1.0 • The exponent contains the power of 2 required to scale the number to its actual value. • Value = mantissa * 2exponent Java
Real Values • Real numbers are characterized by their precision and range. • Precision is the number of significant digits that is represented in the number. • Depends upon the number of bits in the mantissa. • Range is the difference between the largest and smallest numbers that can be represented. • Depends upon the number of bits in the exponent. Java
Real Values – Real Data Types • float uses 32 bits and represents the numbers -3.40292347E+38 to 3.40292347E+38 • The mantissa is 24 bits and the exponent is 8 bits. • 6 to 7 decimal digits of precision. • double uses 64 bits and represents the numbers -1.79769313486231570E+308 to 1.79769313486231570E+308. • The mantissa is 53 bits and the exponent is 11 bits • 15 to 16 decimal digits of precision. • The double data type is more precise than float. Java
Real Values – Round-Off Error • When a double is stored as a float, part of the number is lost because a double is much larger than a float. The float cannot represent the same exact number. In this situation, the seven most significant digits are preserved and the rest of the information is lost. • It is important to know which real data type is required for your calculations. Java
Character Values • May be printable and non-printable characters • some printable characters are: 'a', '%' • some non-printable characters are: newline - '\n', tab - '\t', carriage return - '\r‘ • Unicode escapes allow any character to be represented regardless of the editor being used • A Unicode escape stands for a character and is represented using the \u escape sequence followed by the hexadecimal digits of the character code • Examples: \u0343, \u2f4, \uabcd Java
Unicode • An International Standard that defines the representation of characters from a wide range of alphabets. • Unicode stores characters as 16-bit values providing 65,536 different characters. • ASCII happens to be the first 127 characters in the Unicode standard. • Java uses Unicode as opposed to ASCII. Java
Literals Java
Assignment • Declarations associates a type with an identifier • Assignment associates a value with an identifier • Assignment is represented by = sign • An identifier will always be on the left side of the equals sign • The computer will place a copy of the thing on the right into the area named by the identifier on the left • Assignment is not the same as algebraic equality Java
Assignment Statements • The basic syntax of an assignment statement is: • <variable> = <expression>; • The expression is evaluated and the result is assigned to the variable name on the left of the equals sign. • In this case ‘=‘ means assigned and is called an assignment operator. • The expression is any valid combination of constants, variables, parenthesis, and arithmetic or boolean operators. Java
Assignment Statements • An assignment statement can be used to put values into a variable both by simple assignment or by an expression. • zebraCount = 5; • zebraCount = zebraCount + numInHerd * 0.3; Java
Arithmetic Operators This is an integer division where the fractional part is truncated. • The following table summarizes the arithmetic operators available in Java. Java
Things Affecting How Expressions are Evaluated • Operator Precedence • Numeric Promotion • Assignment Conversion • Casting Conversion Java
Precedence and Operators Highest Lowest Java
X = (1 + ( 2 - 4 + 6) * ( 5 + 3 * 5 ) - 16 ) Operator Precedence • First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. • Second all multiplications, divisions, and modulus operations are calculated from left to right. • Third all additions and subtractions are evaluated from left to right. Java
Mixed Mode Expressions • What happens if an expression contains two different types of numbers? • For example, 4 + 5 * .56; • In most cases Java will automatically convert the values in the expression so that it may be evaluated • What kind of variable can we directly store the results of this expression in? Java
Automatic Type Conversion(Numeric Promotion) • Java provides a variety of automatic type conversions. • The following conversions are supported: • Widening (range!) primitive conversions. • byte to short, int, long, float, or double. • short to int, long, float, or double. • int to long, float, or double. • long to float or double. • float to double. Java
Assignment Conversion • Assignment conversion occurs when the result of the expression is a different data type than the data type of the result. • Widening conversion occurs when the result is promoted to a larger data type. • For instance, an integer result is promoted to a double data type because the result is stored into a double data type variable. • Happens automatically in Java Java
Assignment Conversion • Narrowing conversion occurs when the result is demoted to a smaller data type. • For instance, a double result is to be stored in an integer result. • This is not allowed to automatically occur in Java and will result in a compile time error. • This is allowed in Java if a cast operator is used. Java
Casting Conversion • In some situations Java will not perform automatic conversions • int x = 3.1456; • In these cases you can force a conversion by specifying a cast • int x = (int)3.1456; • Here information is lost, but the assignment will take place Java
Casting Conversion • Widening conversion using type casting is legal in Java and can remove any ambiguities as to the resultant value. • Narrowing conversion using type casting is legal in Java but is discouraged because you are loosing value precision when this is done. • int x = (int) 89.99; • x = 89 • int x = (int) 50235645642L; • x = 2147483648 Java
Assignment Operators • We have seen Java’s basic assignment operator, but Java also has some special assignment operators that combine the assignment operator with a binary operator in a single statement. • Such operators can be used to create short cuts in your code. Java