Title: Intro to Java
1Intro to Java
- Or, CS1 in one week or less!
- (part 1)
2Java 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
3Class 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
4Java 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( )
5Editing 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
- Javas \bin directory needs to be in your PATH
- Javas \lib directory needs to be in your
CLASSPATH
6Compiling 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
7Code 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
8Code 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)
9Code 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
10The 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
11When to use import statements
- A classs 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 classs full name
12When 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)
13Closer 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
14Method 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
15Method 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
16Method 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 outs data
type analogous to operator ltlt, with out
analogous to cout
17More on println method
- Prints one line of output to screen, then moves
cursor to next line - C equivalent would be something like
- stdcout ltlt Obligatory first example ltlt endl
- There is also a print method - works like
println, but doesnt print the end of line
character
18Typical 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
19More 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) objects data member(s)
20Constructor 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
21Test 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.p
rintln(greeting)
22Java 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
23Variable 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
24Variable 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
25Declaring 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
26Characters 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
27Arithmetic operators in Java
- Same as C
- , /, , , -
- same meanings, same precedence, same
associativity - In Java, is defined for floating-point operands
- computes r a - (b q) where integer qlta/b and
with the same sign - for example, 6.9 1.2 .9 because .9 6.9 -
(1.2 5)
28Mixed-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 (, --)
29Type 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 - Cant convert booleans to numbers
30Javas Math class
- Implements several useful mathematical methods
- All methods are static, so they dont 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)
31Relational/Logical Expressions
- Same relational operators as C
- gt, lt, gt, lt, ! and
- Same logical operators
-
-
- !
- Both and use short-circuit evaluation
- Java also has the ternary operator
32Control 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
33Java 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)
34Java vs. C 2
- Java has no pointers (at least none you can
manipulate directly) - You cant overload operators in Java
- You dont have to worry about manual garbage
collection in Java - There are no such things as structs, unions,
enums, typedefs, friend functions, or templates
35Java 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 doesnt have keyword const - can use final
to declare constant data values - final float PI 3.14159
36Intro to Java
- Or, CS1 in one week or less!
- (part 1)