Download lecture 3 intro_java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Compiler wikipedia , lookup

Library (computing) wikipedia , lookup

String literal wikipedia , lookup

Join-pattern wikipedia , lookup

Object-oriented programming wikipedia , lookup

Class (computer programming) wikipedia , lookup

Interpreter (computing) wikipedia , lookup

Go (programming language) wikipedia , lookup

One-pass compiler wikipedia , lookup

Java syntax wikipedia , lookup

C++ wikipedia , lookup

C syntax wikipedia , lookup

Comment (computer programming) wikipedia , lookup

Scala (programming language) wikipedia , lookup

Name mangling wikipedia , lookup

C Sharp syntax wikipedia , lookup

Java (programming language) wikipedia , lookup

Java performance wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Transcript
Tip #1
Don’t wait until the last minute to get help
Tip #2
Hey, I’ll still pass
if I can get enough
partial credit.
Bad things happen while learning a new skill. You
will probably crash and burn on some programs.
Start early; give yourself time for mistakes.
Tip #3
Don’t be too ambitious with your course load. You
CANNOT slack off (kaytarmak) in this class, even for a
few days.
Tip #4
Watch out for the “big
picture”.
Don’t forget this is a programming course, not a
Java course.
It’s dangerous to hide from the programming part of
the course. You may be crushed on the final.
Bottom Line
• If you’re not adequately prepared for this
course:
• Option 1: Get prepared
• Option 2: Drop Now...Do us both a favor!
• Will have take home quiz to test your
knowledge of the prerequisites.
Additional Resources
Sun also has a
free ~1,000 page
book on Java.
You should
download or
bookmark this
resource.
http://www.javasoft.com/docs/books/tutorial/index.html
Introduction to Java
• What Java is:
– A tool for programming well
– Portable across any hardware platform that has a JVM
interpreter
– Relatively easy to learn if you have a good foundation
– An object-oriented language
• What Java is not:
–
–
–
–
“The Ultimate Programming Language”
HTML or another web-content language
Only useful for web applets
Just Another Vacuous Acronym
Introduction to Java (cont’d)
• Strengths of Java:
–
–
–
–
–
A real language, in demand in industry
Portability
Comparatively easy to learn
Difficult to destroy a machine with it ;-)
Advanced built-in GUI/Graphics features
• Weaknesses of Java:
– Slow: interpreted and OO
– GUI/Graphics via “Least Common Denominator” approach
(due to platform independence)
– Awkward/annoying syntax obscures some concepts and
principles
Java’s Popularity
• Keys to Java’s Popularity:
– An OO language that’s relatively simple.
– Virtual Machine approach, allowing
transportability to various different kinds of
computers (operating systems).
– Presence of JVM as part of Web browsers,
encouraging movement of Java programs
over the Web.
Structure of Java Programs
• Applications (“normal” computer programs):
– Create one or more Java source files
– Compile each source file into a class file
– Thus an application will consist of a bunch of
these class files. [Not a single executable i.e. .exe]
– Send one class file to the Java system
– It must have a method (module) called main:
public static void main(String[ ] argv)
( Get used to weird looking stuff! )
– The main method controls program flow (but the
OO orientation means that it starts a process that
features decentralized control).
Sample Application
(in a file called “HelloWorld.java”)
public class HelloWorld
{
public static void main(String argv[])
{
System.out.println(“Hello World!”);
}
}
Java File Names
Source code files must have the ".java" extension.
The file name should match the class name. This
naming convention is enforced by most reasonable
compilers.
Thus, an improperly named java file, saved as
"myTest.java":
class test { ... }
Compiled byte code has the
".class" extension.
Incorrect
Java File Names
Source code files must have the ".java" extension.
The file name should match the class name. This
naming convention is enforced by most reasonable
compilers.
Thus, a properly named java file, saved as
"Test.java":
class Test { ... }
Compiled byte code has the
".class" extension.
Big Picture Time
HelloWorld.java
public class HelloWorld
{
public static void
main(String argv[]){
System.out.println
(“Hello World!”);
}
}
HelloWorld.class
javac
javac HelloWorld.java
0xCAFEBABE ...
java HelloWorld
Java File Structure
Java Files:
1. Consist of the optional package statement,
2. followed by any necessary import statements
3. followed by the class name,
4. followed by any inheritance
and interface declarations.
5.
Note: if the file defines more than one class or interface, only one can be
declared public, and the source file name must match the public class name.
An Average Java File
Thus:
package fatih.edu.ceng217;
import java.util.*;
import fatih.edu.ceng217.lecturenotes.*;
import netscape.javascript.JSObject;
import netscape.javascript.JSException;
public class SplayTree implements TreeType, TreeConstants
{ ...
}// SplayTree
Note the globally unique
package name. Without a
package specification,
the code becomes part of an
unnamed default package in
the current directory.
Java Portability
The Usual Way:
“Source
Code”
OS-specific
compiler or
interpreter
Execute
program
The Java Approach:
“Source
Code”
Demo.java
Execute
program
OS-specific
“Object
Code”
Java
compiler
javac Demo.java
OS-specific
“Object
Code”
Generic
“Byte
Code”
Demo.class
OS-specific
JVM
interpreter
java Demo
Built-in Data Types
• 4 “atomic data
types” + String
–
–
–
–
–
Num (number)
Char (character)
Boolean
Ptr (pointer)
String
Note: A String is
NOT a primitive
• Java: (6 important
“primitives” + String)
–
–
–
–
–
int (integer)
long (long integer, 2x bits)
float (real number)
double (real number, 2x bits)
char (character, use single
quotes: ‘b’)
– boolean
– String (Java is case sensitive,
so capitalize first letter here:
String, not string; use double
quotes: “a string”)
List of Data Types
Primitive Type
Default Value
boolean
char
byte
short
int
long
float
double
void
false
'\u0000' (null)
(byte) 0
(short) 0
0
0L
0f
0d
N/A
Variable Declarations
• Java:
–
<datatype> <identifier>;
• or (optional initialization at declaration)
–
<data type> <identifier> = <init value>;
Examples
int counter;
int numStudents = 583;
More on
float gpa;
these
double batAvg = .406;
assignment
char gender;
examples...
char gender = ‘f’;
boolean isSafe;
boolean isEmpty = true;
String personName;
String streetName = “North Avenue”;
Questions?
Assignment
• Java allows multiple assignment.
int theStart, theEnd;
int width = 100, height = 45, length = 12;
• This tends to complicate javadoc comments,
however:
/**
* Declare cylinder’s diameter and height
*/
int diameter = 50, height = 34;
Javadoc comment gets
repeated twice in output,
once above each listed
variable!
Examples
• Note that whole integers appearing in your source
code are taken to be ‘ints’. So, you might wish to flag
them when assigning to non-ints:
float maxGrade = 100f; // now holds ‘100.0’
double temp = 583d; // holds double precision 583
float anotherTemp = 5.5; // ERROR!
// Java thinks 5.5 is a double
• Upper and lower case letters can be used for ‘float’ (F
or f), ‘double’ (D or d), and ‘long’ (l or L, but we should
prefer L):
float maxGrade = 100F; // now holds ‘100.0’
long x = 583l;
// holds 583, but looks like 5,381
long y = 583L;
// Ah, much better!
Primitive Casting
• Conversion of primitives is accomplished by (1)
assignment with implicit casting or (2) explicit casting:
int total = 100;
float temp = total;
// temp now holds 100.0
• When changing type results in a loss of precision, an
explicit ‘cast’ is needed. This is done by placing the new
type in parens:
float total = 100f;
int temp = total; // ERROR!
int theStart = (int) total;
• We will see much, much more casting with objects
(later) . . .
Casting: Test Your Knowledge
• Given:
Trick
question
int theStart = 10;
float temp = 5.5f;
temp = temp + (float)theStart;
• What does theStart now hold?
15.5
• Given:
char c = ‘A’;
int x;
x = c;
• Legal?
65
Remember:
Everything’s a number
at some level
Operators
• Assignment: =
• Arithmetic: +, -, *, /, % (mod), and others
int numLect = 2;
int numStudents = 583;
int studentsPerLect;
studentsPerLect = numStudents / numLect;
// gives 291 due to integer division
int numQualPoints = 30;
int numCreditHours = 8;
float GPA;
GPA = numQualPoints / numCreditHours;
// gives 3.0 due to integer division
someIntVar = someIntVar * someFloatVar
// gives compile-time error
Test Your Knowledge
• Here’s the problem:
int iVar = 10;
float fVar = 23.26f;
// gives compile-time error
iVar = iVar * fVar;
3
• Which solution works best?
iVar = iVar * (int) fVar
230
4
1
iVar = (int) (iVar * fVar)
iVar = (int)
((float) iVar * fVar)
232
232
iVar = (int) iVar * fVar
Lesson: write code that’s
easily understood.
2
Same Compile Error
Shorthand Operators
counter
counter
counter
counter
=
=
=
=
counter
counter
counter
counter
+
+
*
1;
1;
2;
5;
//OR:
//OR:
//OR:
//OR:
counter++;
counter--;
counter+=2;
counter*=5;
Last two examples: it’s “op” then “equals”
(e.g., +=2), not “equals” then “op” (e.g., isn’t
=+2)
• We will see examples with recursion where the
shorthand operator potentially causes a problem.
Documentation & Comments
• Three ways to do it:
// Double slashes comment out everything until the end of the
line
/* This syntax comments out everything between the /* and the
*/.
(There are no nested comments as in C++. */
/**
* This is syntax for Javadoc comments (similar to second style
* of commenting, but allows for HTML formatting features.
*/
•
For CENG217, use Javadoc comments
Some Comments on Comments
1. C-style comments with /* */; no nesting
2. C++ style comments beginning //
3. A unique "doc comment" starting with /** ...*/
Fun with comments:
worthless
/*/
/*
// */
Never closed
///////////////////
/* ========= */
Good for blocks
Lesson: Comments should be helpful; don’t worry about
compiler tricks with syntax.
Commenting Factoids
• Watch for comments that open, but never close:
int x, y;
// int z;
/*
* Here, we declare the
* the point coordinates.
*/
Lesson: Java encourages clear code through
the type of operators and comments it allows!
Javadoc
/**
* <PRE>
* Get the name.
* Returns the name at a
* specified array location.
* </PRE>
* @param i the index of the array to
*
be retrieved.
* @return strName the name
* @see Employees#isEmployed() called to
*
verify employment
*/
public String getName (int i)
if (myEmpl.isEmployed())
return myArray[i];
else return "Nada";
} // getName(int)
{
Javadoc (Cont’d)
• You may include HTML tags (but avoid structuring tags, like <H1>,
etc.)
• Javadoc comments should immediately preceed the declaration of
the class, field or method. The first sentence should be a
summary. Use the special javadoc tags--@. When '@' tags are
used, the parsing continues until the doc compiler encounters the
next '@' tag.
@see <class name>
@see <full-class name>
@see<full-class
name#method.name>
@version
@author
@param
@return
@exception
@deprecated
@since
@serial
// jdk 1.1
// jdk 1.1
// jdk 1.2
Constants
• Java:
– public final static <type> <IDer> =
<value>;
– public final static int MIN_PASSING = 60;
– public final static float PI = (float)
3.14159;
• Details on “why this syntax” to come
soon...
Printing to Screen
• Java:
–
–
–
–
System.out.println(<argument>);
System.out.println( ); // prints blank line
System.out.println(5); // prints 5
System.out.println(“Hello World”); // prints Hello
World
– “println” vs. “print” in Java:
• println includes “carriage return” at end, next print
or println on new line
• print causes next print or println to begin at next
location on same line
Printing (cont’d)
• When starting Java, there are at least
three streams created for you:
System.in
System.out
System.err
// for getting input
// for output
// for bad news output
• These are InputStream and PrintStream
objects
•
Note: For Win95/NT System.out is "almost" identical to System.err
they both display to the screen (the one exception is when using
DOS redirect, >, where System.out is redirected, while System.err
is still put to the screen.)
Printing (cont’d)
System.out.println
("This line is printed out")
System.err.println
("This is the error stream's output");
Don’t use (needed for autograder)
These are both instances of the PrintStream class.
There are other methods you might find useful in
these classes:
System.out.flush();
System.out.write(int);
System.out.write(byte[] buf,
int offset, int length);
// eek!
Summary
• Java Basics: Summary
– Java Programs
• JVM, applications & applets
• Entry point is main() or init()
– Java Primitives and Operators
• Primitive data types
• Operators: straightforward except for = and ==
– Your new best friend:
System.out.println( )
Questions