Download Intro to 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
no text concepts found
Transcript
Intro to Java
Or, CS1 in one week or less!
(part 1)
1
Java Classes
• In Java, everything is encapsulated
– no such thing as a “non-member function ”
– Java program consists of a series of class
descriptions
• A class is a blueprint for an object
– member fields (aka attributes, variables) store
data
– methods (functions) specify operations
2
Class interactions
• A function call in Java is called a message
• One object interacts with another by
sending and receiving messages
– sender is the client
– receiver is the server
3
Java Code Example
import java.lang.*;
public class ProgEx1
{
public static void main(String [] args)
{
System.out.println (“Obligatory first example”);
}
}
Outer set of brackets enclose the definition of class ProgEx1
Inner set enclose the definition of method main( )
4
Editing & compiling Java code
• Save file with a .java extension
– can use any text editor (e.g. NotePad)
– An IDE provides richer editing tools – can use one
specifically for Java, or use generic or different
language editor (e.g. dev)
• Set up environment:
– Java’s \bin directory needs to be in your PATH
– Java’s \lib directory needs to be in your
CLASSPATH
5
Compiling & executing Java code
• To compile example from previous
slide, type javac ProgEx1.java - if
compilation is successful, will create
ProgEx1.class
• To run the compiled code, type java
ProgEx1
6
Code organization
• Java source code files have .java suffix;
public classes must be in a file with the
same name
• Compiled code has .class suffix
• No header files: class methods are defined
within the class definition, and import
statements bring in classes from the Java
API
7
Code organization
• A program consists of one or more classes
in one or more files
• Can organize source code files into
packages, which can be imported
(analogous to, but different from, #include
and libraries in C++)
8
Code organization
• Files can use classes from another file in 2
different ways:
– import class from another package - can then
use name of class without prefix
– can use class directly (without import) by
prefixing class name with package name
9
The big picture: Java API
• The Java API, or Application Programming
Interface, is analogous to the standard
libraries of C++
• The statement import java.lang.* makes
a package from the API (java.lang) visible
to the class description that follows it
• This line requests that the code in
java.lang be treated as part of this
program
10
When to use import statements
• A class’s full name consists of its package
name followed by its class name;
examples from the Java library include:
– java.util.ArrayList (ArrayList is a class in the
java.util package)
– javax.swing.JOptionPane (JOptionPane is a
class in the javax.swing package)
• We use import statements to minimize the
necessity of using a class’s full name
11
When to use import statements
• For example, to use the ArrayList class in a
program without its prefix, include the statement:
import java.util.ArrayList; // or
import java.util.*;
• Second example above imports all classes from
the java.util package
• Classes from the java.lang packages (including
String and Math) can be used without prefix or
import statement (so import java.lang.*; is really
unnecessary and rarely used)
12
Closer look at Java code
Class definition consists of header:
public class ProgEx1
And body:
{
// data fields & methods
}
Note there is no semicolon at the end of the class
definition, as there would be in C++
13
Method definition: header
public static void main (String [] args)
– public and static are modifiers
– public is an access modifier, meaning this
method can be seen by other objects - other
options include private and protected
– static is a lifetime modifier: static means only one
instance of this method exists, and it is shared by
all objects of this class - since it is independent of
class instances, it exists even if there are none
14
Method definition: header
public static void main (String [] args)
– void is the return type, main is the method
name
– the argument list is in parentheses; the
standard argument list for main is shown
• allows for command-line arguments
• args is an array of strings; can access individual
arguments using [] notation
• number of arguments is stored in attribute
args.length
15
Method definition: body
System.out.println(“Obligatory first program”);
– System is the name of one of the classes defined in
the Java API (in package java.lang)
– out is a static variable defined in System: outside
their classes, static variables can be accessed by
preceding them with class name
– println is a method associated with out’s data type;
analogous to operator <<, with out analogous to cout
16
More on println method
• Prints one line of output to screen, then
moves cursor to next line
• C++ equivalent would be something like:
std::cout << “Obligatory first example” << endl;
• There is also a print method - works like
println, but doesn’t print the end of line
character
17
Typical structure of Java
application
• Consists of collection of classes
• One class has main() method
– actually, any and all classes can have a
main(), but only one per program is actually
executed
– can include main() in any class for testing
purposes
18
More typical example
public class Greeter
{
public Greeter (String aName)
{
name = aName;
}
public String sayHello()
{
return “Hello, ” + name + “!”;
}
private String name;
}
Class features:
Constructor:
creates new
instances of class
Method(s):
algorithm(s)
applied to class
objects
Field(s): object’s
data member(s)
19
Constructor in Java
• Invoked using operator new (unlike C++,
where declaration automatically invokes
constructor)
– new returns a reference to a newly-created
object, which is an instance of the class
– can use a variable to store the reference
20
Test program for Greeter class
public class GreeterTest
{
public static void main(String[] args)
{
Greeter worldGreeter = new Greeter(“world”);
// invokes constructor, stores resulting object reference
String greeting = worldGreeter.sayHello();
System.out.println(greeting);
}
}
21
Java data types and their C++
counterparts
• Java
byte (signed, 8 bits)
short (signed, 16 bits)
int (signed, 32 bits)
long (signed, 64 bits)
boolean (true/false)
char (16 bits, Unicode)
float (32 bits)
double (64 bits)
void
String
• C++
char (sort of)
int, short
long, int
long
bool
char (sort of - 8 bit ASCII)
float
double
void
string
Note: string type is not primitive, built-in type in either language
22
Variable declaration in Java
• Variables can be declared classwide or
local to a method
• Identifiers follow similar rules as C++
– name must start with a letter
– in Unicode, the symbol ‘$’ is considered a
letter, so names can start with this
• Primitive type variables similar to variables
in C++
23
Variable declaration in Java
• Object & array variables work differently
– they are references (think pointers) to the
data-type-sized memory they can be
associated with
– have to allocate memory before you can
assign a value to them - this is done using the
new operator with the constructor, as seen
previously
24
Declaring & manipulating simple
variables
• Looks exactly like C++ - examples:
int x, y;
x = 10;
y = x + 4;
• Unless declared static, data variables are
instance members
– tied in with individual instances of class or
method
– every instance of the class has its own copy
25
Characters in Java
• Use 16-bit Unicode instead of 8-bit ASCII;
much richer character set (see
www.unicode.org)
• Escape sequences similar to those in C++;
e.g. ‘\n’ is newline character, ‘\t’ is
horizontal tab, ‘\b’ is backspace, ‘\\’ is
backslash character
• Can use ‘\uxxxx’ where x is a hex digit to
denote an arbitrary Unicode character
26
Arithmetic operators in Java
• Same as C++:
*, /, %, +, – same meanings, same precedence,
same associativity
• In Java, % is defined for floatingpoint operands
– computes r = a - (b * q) where integer
q<=a/b and with the same sign
– for example, 6.9 % 1.2 = .9 because
.9 = 6.9 - (1.2 * 5)
27
Mixed-type expressions
• Similar to C++:
– “lower” types are promoted, result is “highest”
type of operand in expression
– explicit cast is required to “demote” a data
type
• Java also retains the combination
arithmetic/assignment operators (+=, etc.)
and pre and post increment and
decrement (++, --)
28
Type conversions
• If no information loss is involved (converting
short to int, for example), no explicit cast
required
• Can convert char to int
• Can convert all integer types to float or double
(even though information loss may be possible)
• Conversion of any floating point type to any
integer type requires explicit cast
• Can’t convert booleans to numbers
29
Java’s Math class
• Implements several useful mathematical
methods
• All methods are static, so they don’t
operate on objects, and must be invoked
by referencing the class name
• Examples:
Math.sqrt(x) returns square root of double
argument x
Math.pow(x,y) returns xy (where x, y and result
are all type double)
30
Relational/Logical Expressions
• Same relational operators as C++:
>, <, >=, <=, != and ==
• Same logical operators:
– &&
– ||
–!
– Both && and || use short-circuit evaluation
• Java also has the ternary operator
31
Control Structures
• Syntax for while, for, do/while, if, if/else
and switch are identical to the same
structures in C++
• As in C++, brackets are required around
blocks of code that contain more than one
statement
32
Java vs. C++: 1
• Java classes look different because:
– methods are defined inside class definitions
(not in separate implementation file)
– everything is a class - including the driver
class, which contains main( )
• Java programs can contain multiple
instances of main() (but only one will
execute)
33
Java vs. C++: 2
• Java has no pointers (at least none you
can manipulate directly)
• You can’t overload operators in Java
• You don’t have to worry about manual
garbage collection in Java
• There are no such things as structs,
unions, enums, typedefs, friend functions,
or templates
34
Java vs. C++: 3
• There is no default type for Java methods
(unlike C++, where functions are assumed
to return int unless otherwise specified)
• Explicit casts are required to convert from
int to char
• Modulus works on floating-point numbers
• Java doesn’t have keyword const - can
use final to declare constant data values:
final float PI = 3.14159;
35
Intro to Java
Or, CS1 in one week or less!
(part 1)
36