2
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
3
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
4
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( )
5
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
6
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
7
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
8
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++)
9
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
10
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
11
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
12
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)
13
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 classdefinition, as there would be in C++
14
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
15
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
16
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
17
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
18
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
19
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)
20
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
21
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);
}}
22
Java data types and their C++ counterparts
• Javabyte (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)voidString
• C++char (sort of)int, shortlong, intlongboolchar (sort of - 8 bit ASCII)floatdoublevoidstring
Note: string type is not primitive, built-in type in either language
23
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++
24
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
25
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
26
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
27
Arithmetic 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
q<=a/b and with the same sign– for example, 6.9 % 1.2 = .9 because .9 =
6.9 - (1.2 * 5)
28
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 (++, --)
29
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
30
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 xMath.pow(x,y) returns xy (where x, y and
result are all type double)
31
Relational/Logical Expressions
• Same relational operators as C++: >, <, >=, <=, != and ==
• Same logical operators:– &&– ||– !– Both && and || use short-circuit evaluation
• Java also has the ternary operator
32
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
33
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)
34
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
35
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;