Home Previous Next

CSC110AB::Lecture Note::Week 02
Assignments | Handouts | Resources | Email Thurman {Twitter::@compufoo Facebook::CSzero}
GDT::Bits:: Time  |  Weather  |  Populations  |  Special Dates

Overview Assignment(s) Code HelloWorld.java | HW.java | HelloGoodbyeWorld.java | LongStringLiterals.java
ArithOps.java | Divider.java | MaxMinValues.java | EscapeSequences.java

Java Compilation Process (Introduction)

Executing a java program requires two steps.

The following (ASCII art) diagram summarizes the Java compilation process.

   source         +----------+        class
   file     --->  | compiler |  --->  file    ---+
   (x.java)       +----------+      (x.class)    |
                   (javac)                       |
                                       | Java Virtual Machine |

A Java source file can contain only one public class and the name of that class must be identical to the basename of the file name containing the class definition. All Java source files must end in .java .

   public class MyDate { ... }

      Class  MyDate  must be defined in a file named  MyDate.java

A Java source file is compiled using the javac JSDK command. The command requires at least one argument: the name of a Java source file to be compiled.

   $ javac MyDate.java

      Note:  the  .java  suffix is required.  This example assumes
      our current working directory is the same directory in which
      the source file is located.

The output of a successfully compiled MyDate.java is stored in a file name MyDate.class. ".class" files are in bytecode format -- they are not executable files. In order to execute the MyDate program, its class file must be submitted to the Java interpreter (i.e. the JSDK command java [or the JVM]).

The java command requires one argument: the class name. The name is specified without the ".class" suffix.

   $ java MyDate

      The JVM (Java Virtual Machine) is started and the  
      MyDate  application is executed.

A Java source file can contain multiple classes (but only one of them can be public). When a file containing multiple classes is compiled, a ".class" file is generated for each class defined in the file.

   File:  Testing.java

      public class Testing { ... }
      class X { ... }
      class Y { ... }

   $ javac Testing.java

      Compiling  Testing.java  results in the creation of three
      separate class files.

   $ ls

Multiple Java source files can be compiled at one time.

   $ javac Foo0.java Foo1.java Foo2.java

      Compiles all three  .java   source files.  The compilation
      process stops if any file encounters a compile-time error.
      The  'javac'  command does contain some "makefile"
      capabilities (e.g.  if  Foo0.java  uses the  Foo1  and  Foo2
      classes, then simply compiling  Foo0.java  causes  Foo1.java
      and  Foo2.java  to be compiled [but only if they need to be]).

Unlike C and C++, the Java compilation process does not include a preprocessor, nor does it require a linker/loader.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Java Keywords and Reserved Words

The following are Java keywords.

   abstract     boolean      break       byte          case
   catch        char         class       continue      default       
   do           double       else        extends       false         
   final        finally      float       for           if          
   implements   import       instanceof  int           interface
   long         native       new         null          package
   private      protected    public      return        short
   static       strictfp     super       switch        synchronized  
   this         throw        throws      transient     true          
   try          void         volatile    while

The following Java reserved words.

   byvalue      cast         const       future        generic
   goto         inner        operator    outer         rest

The following (which are method names of the Object class) should not be used as method names, except when overriding an Object method.

   clone        equals       finalize    getClass      hashCode
   notify       notifyAll    toString    wait

# of keywords in C, C++ and Java
C C++ Java
32 74 48

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

About Escape Sequences

Escape sequences are used for the following reasons.

C and C++
  \a  Alert   \b  Backspace   \f  Formfeed
  \n  Newline   \r  Carriage return   \t  Horizontal Tab
  \v  Vertical Tab   \"  Double quote   \'  Single quote
  \\  Backslash   \?  Question Mark   \0  Null Character
There are two types of numeric escape sequences: octal and hexadecimal.
Java Escape Sequences
Java will not compile a source file if it contains invalid escape sequences. [ Example]

  \b  Backspace   \f  Formfeed   \n  Newline
  \r  Carriage return   \t  Horizontal Tab   \"  Double quote
  \'  Single quote   \\  Backslash   \uhhhh  Unicode; 4 hexadecimal digits
  \ooo  C style; 3 octal digits

All of the Java escape sequences -- except for Unicode \u -- can only be used within string and character literals.

   String doubleQuote = "\"";
   char singleQuote = '\'';
   char bestGrade = '\u0041';    // set to 'A'
   char worstGrade = '\106';     // set to 'F'

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Defining Variables

A variable is a location in the computer's memory where a value can be stored for use by a program.

Variables have the following characteristics:

Variables must be defined before or at the time they are first used. A variable is defined by giving it a type and a name.

Variable names must begin with either an underscore _, dollar sign $, or a letter. The rest of the variable name, if any, can be any combination of letters and numbers. Letters can be either uppercase or lowercase and they include dollar sign ($) and underscore (_). By convention, Java variables have meaningful names, often made up of several words combined. The first word is lowercase, but all following words have an initial uppercase letter.

There is no difference between defining and declaring a variable; therefore, the two terms can be used inter-changeably.

There are three categories of variables: class, instance and local. These categories are detailed later in the course.

Notes on style:

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Primitive Data Types

The size of the Java primitive types are fixed across all JVMs. As a consequence, the language does not have (nor does it need) a sizeof() operator.

boolean 1-bit (true or false)
byte 8-bits
char 16-bits (unsigned -- unicode)
short 16-bits
int 32-bits
long 64-bits
float 32-bits (single-precision)
double 64-bits (double-precision)

The minimum and maximum values that can be stored in a variable is dependent on its type. These min/max values can be found from the "wrapper" classes that exist for each type.

All types are signed (except char, which is unsigned). Java does not have the signed and unsigned keywords.

Assigning a variable of a larger type to a variable of a smaller type requires the use of type cast.

   short s;
   int i;
   s = (short)i;   //the typecast is required; otherwise, syntax error

When you define long and short variables, the keyword int cannot be used.

   long int li;   //syntax error
   short int si;  //syntax error

The following items help make Java programs portable.

Some more differences between Java and C/C++.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


An integral (whole number) value by default is treated as an int.

An integral value suffixed with an ell (either lowercase or uppercase) is treated as type long.

A floating-point (real number) value by default is type double.

A floating-point value suffixed with an eff (either lowercase or uppercase) is treated as type float.

A floating-point value suffixed with a dee (either lowercase or uppercase) is treated as type double.

An integral value prefixed with a zero indicates octal representation being used (e.g 034 is octal for the decimal value 28). An integral with 0x or 0X prefix implies hexadecimal notation used.

Floating-point values can be expressed using exponential notation. For example.

   3.14e0    3.14 times 100
   1e+3      1.0 times 103
   2.99e-5   2.99 times 10-5 

A character enclosed in single quotes is type char.

A sequence of zero more more characters enclosed in double quotes is a string literal and results in an object of type String.

   i = 200;     //200 is an  int
   l = 200L;    //200 is type long
   f = 200.0f;  //200 is a float
   d = 200.0;   //200 is a double
   c = 'A';     //'A' is type char
   s = "200";   //2000 is a String

The type of a constant is important when they are used in mixed-mode expressions (EXPRs). In a nutshell, Java does the following.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Define Terms: Expression, Operand, Operator

An expression is a combination of operands and operators that yields (expresses) a single value. Let EXPR be short for expression.

An operand is a constant or variable that is manipulated in the EXPR. Let OP stand for operand. Each OP of an EXPR is also an EXPR, since it represents a single value.

An operator specifies how the operand or operands of an EXPR are manipulated. Let OPER represent operator.

When an EXPR is evaluated, the resulting value depends on the relative precedence of OPERs in the EXPR and on "sequence points" and "side effects," if any. The precedence of OPERs determines how OPs are grouped for evaluation (i.e. how operands bind with operators). Side effects are changes caused by the evaluation of an EXPR.

OPs include constants, identifiers, function calls and so on.

The result every EXPR has a type. For example, an EXPR may evaluate to an int.

OPERs take either one OP (unary), two OPs (binary) or three OPs (ternary).

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


An operator specifies how the operand or operands of an expression are manipulated.

Java has many of the same operators as does C and C++ with similar precedence and associvity.

Operators are usually represented using symbols (+ - * / %).

Operators and operands form the atomic unit of an expression.

Operators take either one operand (unary), two operands (binary) or three operands (ternary).

When multiple operators are used in an expression, then precedence and associativity is used to bind (or group) operands with operators.

Java evaluates expressions unconditionally left-to-right. [This is not true in C or C++.]

Arithmetic Operators

All of the arithmetic operators are binary operators (i.e. they take two operands).

   +   addition
   -   subtraction
   /   division
   *   multiply
   %   modulus (remainder)

The arithmetic operators work with integral and floating-point values except for the modulus (%) operator which works only on integral operands.

If both operands are integral data types, then the result is integral and an integer division occurs (i.e. any reminder is dropped (truncated) from the result). Examples.

    3 / 2  equals  1
    7 / 3  equals  2
   11 / 3  equals  3

An integer division by 0 causes an Exception. Example: The expression 2002 / 0 causes a program to abnormally terminate. Floating-point division by 0 results in the value infinity without an Exception.

If one operand is integral and other is a floating-point, then a floating-point division is executed. The result is the type of the floating-point operand.

If both operands are floating-point, then the type of the result is the type of the "largest" operand. Example.

   float f = 1.9;
   double d = 1.9;

   f / d   results in a  double
   d / f   results in a  double

The + addition operator can be applied to String objects. If only one operand is a String, then the other is converted to a String. The addition operator when applied to String objects performs a concatentation of the value of the left-hand operand with the value of the right-hand operand. The concatenation results in the creation of a third (new) String object that stores the result of the concatentation. [This is Java's only overloaded operator. Java does not support operator overloading.]

Relational Operators

Relational operators are binary operators that are used to compare the value of two expressions.

   ==  equality
   !=  not equal
   >   greater than
   >=  greater than or equal to
   <   less than
   <=  less than or equal to

Relational operators evaluate to boolean values (i.e. true or false).

   int a = 10;
   int b = 15;

   a == b        evaluates to false
   a != b        evaluates to true
   a > b         evaluates to false
   a < b         evaluates to true

If the operands are not the same type, then the value of the type smallest type is promoted to the larger type before the comparison is executed.

Logical Operators

The binary logical operators are use to test if two expressions, when combined, are either true or false. The unary logical operator is used to reverse the outcome of an expression that evaluates to a boolean values.

   &&  and
   ||  or
   !   not (unary)

The operands of logical operators must evaluate to type boolean values.

Java uses short-circuit evaluation (i.e. an EXPR is evaluated only until the truth or falsehood of the entire EXPR can be unambigously determined).

Bit-wise Operators
   ^  exclusive or
   &  and
   |  or
   >> right shift (sign extension)
   << left shift
   ~  one's complement

   Java also has a  >>>  right shift operator (0 extension).
Miscellaneous Operators
   ++  increment (both prefix and postfix)
   --  decrement (both prefix and postfix)
   ?:  conditional
   +   unary plus
   -   unary minus
   ()  typecast
   compound assignment  (e.g. +=, -=, /=, %=, *=, &=, |=, ^=, 
                              <<=, >>=, >>>=)
Java does not the following operators:
   sequence (i.e. comma)

   Note:  the sequence operator is supported when used with the
          for()  repetition control statement.
The following Java operators will be covered later:
   ()  /* method call */
   []  /* array */
   .   /* dot */
Operator precedence and associativity:

[]   .    ()(method call) left-to-right
!   ~   ++   --   +(unary)   -(unary)  ()(cast)   new right-to-left
*   /   % left-to-right
+   - left-to-right
<<   >>   >>> left-to-right
<   <=   >   >=   instanceof left-to-right
==   != left-to-right
& left-to-right
^ left-to-right
| left-to-right
&& left-to-right
|| left-to-right
?: left-to-right
= compound assignment operators right-to-left

In Java, the order in which EXPRs are evaluated is always a strict left-to-right. Recall, in C and C++, the order of EXPR evaluation is implementation-dependent. Having the order of EXPR evaluation be well-defined helps make Java portable. Here is an example:

   Given the following EXPR:  f() + g()

   In Java, you are guaranteed that  f()  will be called before  g().
   In C, on some systems  f()  may be called first, but on others it
   might be called after  g()  has been invoked.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Home Previous Next