Download 1basicsOLD - NEMCC Math/Science Division

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

Join-pattern wikipedia , lookup

Class (computer programming) wikipedia , lookup

Abstraction (computer science) wikipedia , lookup

Programming language wikipedia , lookup

Functional programming wikipedia , lookup

Comment (computer programming) wikipedia , lookup

Java syntax wikipedia , lookup

String literal wikipedia , lookup

One-pass compiler wikipedia , lookup

Reactive programming wikipedia , lookup

Name mangling wikipedia , lookup

Falcon (programming language) wikipedia , lookup

String (computer science) wikipedia , lookup

Object-oriented programming wikipedia , lookup

Scala (programming language) wikipedia , lookup

Interpreter (computing) wikipedia , lookup

Structured programming wikipedia , lookup

Go (programming language) wikipedia , lookup

C Sharp syntax wikipedia , lookup

C syntax wikipedia , lookup

C++ wikipedia , lookup

Java (programming language) wikipedia , lookup

Java performance wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Transcript
1.
The Basics
(Just the FAQs, Ma’am)
Introduction to Java
• Java strengths:
–
–
–
–
–
–
A tool for programming well
Portable across platforms that have a JVM interpreter
object-oriented language
A real language, in demand in industry
Built-in GUI/Graphics features
Useful for web applets or stand-alone application
• Java weaknesses:
– Slow: interpreted and OO
– GUI/Graphics via “Least Common Denominator” approach
(due to platform independence)
– Sometimes awkward syntax
Introduction to Programming, Lecture 1
Applications vs. Applets
• Applications
– “normal” computer programs
• Applets
– programs embedded in web pages
Introduction to Programming, Lecture 1
Sample Application
(in a file called “HelloWorld.java”)
public class HelloWorld
{
public static void main(String argv[])
{
System.out.println(“Hello World!”);
}
}
Introduction to Programming, Lecture 1
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 compilers.
Thus, an properly named java file, saved as
"test.java":
public class test
{
...
}
Compiled byte code has the ".class" extension.
Java Portability
The Java Approach:
“Source
Code”
Java
Compiler
*.java
“javac”
Execute
program
OS-specific
“Object
Code”
Introduction to Programming, Lecture 1
Generic
“Byte
Code”
*.class
OS-specific
JVM
Interpreter
“java”
Vocabulary
• Structured (Functional) Programming:
– A programming paradigm in which the actions (or verbs, or
procedures) are emphasized.
• OO Programming:
– A programming paradigm in which the actors (or nouns, or
objects) and their interaction is emphasized.
• Byte Compiler:
– A compiler which translates human-readable source code
into byte code (transportable to various virtual machines)
instead of object code written for a specific kind of machine.
– javac
Introduction to Programming, Lecture 1
Vocabulary (cont’d)
• Byte Interpreter:
– An interpreter which translates byte code into object code for
a particular kind of machine and executes them on that
machine.
• Byte Code:
– An instruction for a virtual machine.
• Java Virtual Machine (JVM):
– The virtual machine (software) for which all Java programs
are compiled. A byte code interpreter is required to translate
from the JVM byte code instructions into to instructions for a
given actual machine.
Introduction to Programming, Lecture 1
Built-in Data Types
• Java: (6 important “primitives” + String)
–
–
–
–
–
–
–
int
long
float
double
char
boolean
String
integer, 2b +/-2G
long integer, 64 bits; +/-9E18; 8XB
real number, 4 bytes
real number, 8 bytes
character, use single quotes: ‘b’, 2b
true/false
(Java is case sensitive: String,
not string; double quotes:
“a string”)
Introduction to Programming, Lecture 1
Default Data Type Values
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
Note: At times, the Java Language Specification refers to void as a primitive,
though other parts (e.g., s. 14.7) say ‘void’ is not a primitive as in C/C++.
One cannot cast to a void type in Java.
Variable Declarations
• Java:
<datatype> <identifier>;
• or
<data type> <identifier> = <init value>;
Introduction to Programming, Lecture 1
Examples
int iCounter;
int iNumStudents = 583;
float fGPA;
double dBatAvg = .406;
char chGender;
char chGender = ‘f’;
boolean bSafe;
boolean bEmpty = true;
String strPersonName;
String strStreetName = “North Avenue”;
Introduction to Programming, Lecture 1
Assignment
• Java allows multiple assignment.
int iStart, iEnd;
int iWidth = 100, iHeight = 45, iLength = 12;
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 fMaxGrade = 100f; // now holds ‘100.0’
double dTemp = 583d;
// holds double precision 583
float fTemp = 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 fMaxGrade = 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 and/or
int iTotal = 100;
float fTemp = iTotal;
(2) explicit casting:
// fTemp now holds 100.0
• When changing type results in a loss of precision, an
explicit ‘cast’ is needed. Place new type in parens:
float fTotal = 100f;
int iTemp = fTotal;
// ERROR! No implicit cast.
int iStart = (int) fTotal;
Operators
• Assignment: =
• Arithmetic: +, -, *, /, % (mod), and others
int iNumLect = 2;
int iNumStudents = 583;
int iStudentsPerLect;
iStudentsPerLect = iNumStudents / iNumLect;
// gives 291 due to integer division
int iNumQualPoints = 30;
int iNumCreditHours = 8;
float fGPA;
fGPA = iNumQualPoints / iNumCreditHours;
// gives 3.0 due to integer division
iVar = iVar * fVar
// gives compile-time error
Introduction to Programming, Lecture 1
Shorthand Operators
•
•
•
•
iCounter
iCounter
iCounter
iCounter
=
=
=
=
iCounter
iCounter
iCounter
iCounter
+
+
*
1;
1;
2;
5;
OR
OR
OR
OR
Introduction to Programming, Lecture 1
iCounter++;
iCounter--;
iCounter+=2;
iCounter*=5;
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.
*/
Introduction to Programming, Lecture 1
Constants
• Java:
– final <type> <Identifier> = <value>;
final int iMIN_PASSING = 60;
final float fPI = (float) 3.14159;
Introduction to Programming, Lecture 1
Printing to Screen
• Java:
System.out.println(<arguments>);
System.out.println( );
// prints blank
line
System.out.println(5);
// prints 5
System.out.println(“Hello World”+5);
// prints Hello World5
– “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
Introduction to Programming, Lecture 1
The Keyboard Class
• NOT part of the Java standard class library
• provided by authors to make reading input
from keyboard easy
• part of a package called cs1
• Copy cs1 folder to your directory (from java)
• contains several static methods for reading
particular types of data
//***********************************************************
// Echo.java
Author: Lewis/Loftus
//
// Demonstrates the use of the readString method of the
// Keyboard class.
//************************************************************
import cs1.Keyboard;
public class Echo
{
//--------------------------------------------------------// Reads a character string from the user and prints it.
//--------------------------------------------------------public static void main (String[] args)
{
String message;
System.out.println ("Enter a line of text:");
message = Keyboard.readString();
System.out.println ("You entered: \"" + message + "\"");
}
}
import cs1.Keyboard;
public class Quadratic
{
//--------------------------------------------------------------// Determines the roots of a quadratic equation.
//--------------------------------------------------------------public static void main (String[] args)
{
int a, b, c; // ax^2 + bx + c
System.out.print ("Enter the coefficient of x squared: ");
a = Keyboard.readInt();
System.out.print ("Enter the coefficient of x: ");
b = Keyboard.readInt();
System.out.print ("Enter the constant: ");
c = Keyboard.readInt();
// Use the quadratic formula to compute the roots.
// Assumes a positive discriminant.
double discriminant = Math.pow(b, 2) - (4 * a * c);
double root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);
System.out.println ("Root #1: " + root1);
System.out.println ("Root #2: " + root2);
}
}
Keyboard Class
• public static String readString ()
– Reads and returns a string, to the end of the line, from standard input.
• public static String readWord ()
– Reads and returns one space-delimited word from standard input.
• public static boolean readBoolean ()
– Reads and returns a boolean value from standard input. Returns false if an
exception occurs during the read.
• public static char readChar ()
– Reads and returns a character from standard input. Returns MIN_VALUE if
an exception occurs during the read.
• public static int readInt ()
– Reads and returns an integer value from standard input. Returns
MIN_VALUE if an exception occurs during the read.
• public static long readLong ()
– Reads and returns a long integer value from standard input. Returns
MIN_VALUE if an exception occurs during the read.
• public static float readFloat ()
– Reads and returns a float value from standard input. Returns NaN if an
exception occurs during the read.
• public static double readDouble ()
– Reads and returns a double value from standard input. Returns NaN if an
exception occurs during the read.
Strings
String s = “doghouse”;
String t = s.substring(0,3);
if (t.equals(“dog”))
System.out.println(s + “has a dog in it”);
System.out.println(s.length());
Documentation
http://math.necc.cc.ms.us/courses/discrete/java/docs/api/java/lang/String.html
Summary
• Java Basics: Summary
– Java Programs
• JVM, applications & applets
• Entry point is main()
– Java Primitives and Operators
• Operators: straightforward except for = and ==
– Your new best friend:
System.out.println( )
Introduction to Programming, Lecture 1