Review of Java Concepts 4th Ed. by Wiley Publishing

java script

 

Review of Java Script Concepts 4th Edition

By David Hsu

Wiley presents us with an intro to Java that presents its core concepts in a comprehensive way.; Its author, Cay Horstmann, teaches at San Jose State University. I used it as textbook for my college courses and am happy to have discovered that his book has greatly aided the writing of my Java tutorial. Consisting of  902 pages divided into 19 chapters, Review of Java Concepts is both well-organized and beginner-friendly.
Continue reading

Please like & share:

Generics

Generics are classes, interfaces, methods, or constructors that use special variables called type variables.

ArrayList is an example of a generic class.

 

Type Variables

These are special variables that can be assigned types (the variables we normally use can be called value variables, because they are assigned values).

Purpose is to be used to declare value variables.

Example:

type var; //if type is a type variable, var will be declared with that type

 

Generic Class Definitions

class Class<type>
{
     ...
}

This creates a class with a type variable named type.

Type variables are accessible within the body, like how normal variables are.

Example:

//box that holds contents of a type.
class Box<type>
{
     type contents;
     Box(type contents)
     {
          this.contents = contents;
     }
}

Variables assigned generic class objects are declared and instantiated with angle brackets, having types to be passed to the constructor. Example (try it):

Box<String> stringbox = new Box<String>(“string”);

 

Generic Method Definitions

<type, type2, ...> return-type method()
{
     ...
}

This defines a method with type variables type, type2, ….

To be able to pass types to the method, make parameters preceded by type variables and write those type variables inside angle brackets.

Example:

<type> boolean equals(type a, type b)
{
     return a == b;
}

Modifiers (like static, public, etc.) must go before the angle brackets.

 

Constraining type variables

<type extends another-type>

This constrains what type can be to only types that extend another-type.

Example:

//test whether two Number values are identical.
<type extends Number> void test(type a, type b)
{
     System.out.println(a == b);
}

One can also use the keyword super to limit the type to be parent of another-type:

<type super another-type>

If you do not need to know nor use the passed type, you can change type to ? instead, for simplifying purposes:

<? super another-type> //cannot know ?

 

Naming conventions

I made my own names for type parameters in simplicity, like “type”. But these are the usual names people give to type parameters:

  • E – Element (used extensively by the Java Collections Framework)
  • K – Key
  • N – Number
  • T – Type
  • V – Value
  • S,U,V etc. – 2nd, 3rd, 4th types
Please like & share:

Complex Statements

Statements can vary in complexity, much like English sentences.

Statements can be a method call, variable assignment, or combination of the two, followed by a semicolon.

 

Parentheses

Parentheses indicate priority (think algebra parentheses).

Example:

int x = 3 * (2 + 1); //do 2+1 first, then multiply result by 3

 

Substitution

Returned value of method calls can be assigned to variables.

Example:

int x = Math.pow(2, 2); //assign result to x

Returned value substitution occurs when used in a statement. Example:

x = 1 + Math.pow(2, 2);

will be the same as

x = 1 + 4;

(like algebra substitution).

 

Multiple Assignments

Multiple assignments can be made in a single statement.

Example:

int x = 0;
int y = 1;
int z = 2;
x = y += z *= 10;

 

Side Effects

Assignments inside conditions are called side effects.

Example:

int x, y = 2;
if ((x = 2) == y) //both set x to 2 and test x equal y

 

Anonymous Objects

Anonymous means “unnamed”.

Anonymous objects are simply objects not assigned to variables. So, unnamed.

Purpose is to avoid naming objects.

Example:

toaster.toast(new Bread()); //new Bread() object is unassigned to a variable

 

Anonymous classes

These are classes of a single object, only (“one-of-a-kind”).

You define them when making that single object.

They inherit another class, but are unnamed.

Purpose is avoid naming classes.

Example:

Bread bread = new Bread() // new object of a new class subclassing Bread defined below
{
     String color = “black”;
};

 

Please like & share:

Debugging

cibo00_Debugging

Debugging (ridding of unwanted errors from your code) is often the task you will spend the most time on while programming.

Debugging is done in different ways.

 

Error reports

The console reports errors with an error name, followed by a trace of calls leading up to the error, starting from the most recently called method to the least recent.

Example:

Exception in thread "main" java.lang.ArithmeticException: / by zero
      at Tester.divide(Tester.java:12)
      at Tester.main(Tester.java:7)

Here, the actual error occurred at line 12 in the method divide(). main() had called divide() at line 7 before that.

The entire code containing the error is this:

class Tester
{
 
       public static void main(String[] args)
       {
              divide();
       }
 
       static void divide()
       {
              int x = 1 / 0;
       }
}

 

Common error: believing multiple errors in one

An error report like the above reports only 1 error. To believe that it contains 3 errors can be common with beginners.

Indentation level tells you how many errors there are. When it indents and says “at”, you know it is saying where the error is being caused by, not that there is another one.

 

Debugging by logging

The most common way to debug is using System.out.println() to print values and see where the bug is located.

 

Debugging by debugger

debugging

Using a debugger is recommended and effective, which is a built-in feature of some IDEs that runs your program and analyzes its behavior at the same time.

Three debugging functions of your IDE should be mastered:

  • Single-stepping: a command that executes the current line of code and stops at the next line. Most IDEs have 2 different kinds of single-stepping: step over, which skips going inside method calls, and step into, which goes inside method calls. You should step into a method if it fails, but step over it if it works fine.
  • Inspecting: a feature that shows at the current state of variables in your code, for you to ensure the values are as expected. Some IDEs even allow you to change a variable’s value while it is running, to see what would happen.
  • Breakpoints: markers of lines of your code where the debugger will stop running. Once a breakpoint is reached, execution stops, and you can single-step and inspect your code until it reaches the next breakpoint. Breakpoints stay in effect until removed, so keep them only as needed.

 

Divide-and-Conquer method

This means you use the debugger to deduce where the bug is from the topmost to bottommost level methods.

1. step over each method of main() except the one that fails, and step into that method.

2. step over each method in that method except the failing method within that one, and step into that method.

3. repeat step 2 until you discover the faulty line.

Please like & share:

Loops

Loops are statements that repeat the execution of some statement.

Four loops exist:

  • while
  • do…while
  • for
  • for enhanced

 

While loops

while (condition)
     statement

This checks if condition evaluates to true. If so, run statement. Then check if condition is true again and run statement again if so. Repeat.

If condition is simply true, it will run statement indefinitely (until the break statement is used, explained bottom):

while (true) //run forever
     ;
Common Error: Infinite LoopsThe compiler will report a “Stack Overflow error” when it detects a loop will never stop. However, if it does not detect it for some reason, you can usually command your IDE to terminate the program by some terminate button. But if you cannot do this, you may be able to kill it by pressing ctrl+c or ctrl+break or closing the window.A common reason for infinite loops is forgetting to update the loop control variable, if it has one. For example:


int count = 0;
while (count < 10)
{
	...
}

In this case, count needs to be updated, because it is determines the loop terminate condition. Perhaps like count += 1;

 

Do-while loops

do
    statement
while (condition)

This runs statement, then checks if condition is true. If so, repeat.

This is simply a while loop but that statement is guaranteed to be run at least once.

 

For loops

for (initialization; condition; update)
     statement

This initializes a variable, sets loop condition, and continuously executes and updates expression while condition is true.

It is a shortcut of the following while loop format, since it is so commonly used:

i = start;
while (i <= end)
{
     ...
     i++;
}

The equivalent for-loop is this:

for (i = start; i <= end; i++)
{
     ...
}

Example (try it):

int balance = 0;
for (int year = 0; year <= 9; year += 1)
     balance += 50000;

Note that one of the three parts of a for loop can be replaced by an empty statement if it is not needed:

for (; i <= end; i++) //skip initialization
{
     ...
}
Common Error: Off-by-one errorsLoop conditions are often accidentally set to end 1 iteration too many or too short. Example:


for (int index = 0; index <= array.length; index ++)
{
     array[index] = null;
}

Here, index will end up to be array.length in the last iteration of the loop, which is not what the programmer intended. If the last index is set to the array length, he/she will get an array index out of bounds exception. Instead, the last element should be index array.length – 1. So, the terminating condition should have been index < array.length (or equivalently, index <= array.length – 1, which might be easier for beginners to grasp).

 

Enhanced for loops

for(type variable : elements)
     statement

This repeats statement for every element that exists in elements, setting a variable to the current element during every loop.

Parts:

  • type variable – declare a variable here that will be set to another element in elements every loop.
  • elements – an iterable object that has elements, like arrays or array lists.
  • statement – statement run for every loop.

Purpose is for looping through elements of a sequence to do something with them.

Example (try it):

int[] array = {1, 2, 3};
for (int i : array)
    System.out.println(i); //print 1, 2, 3

 

Break statement

break;

break is a reserved word used to stop running the currently running loop, sometimes to make your code more efficient when more iterations are no longer needed.

Example (try it):

boolean isfull = False;
int gallons = 0;

while (true)
{
    gallons += 1;
    if (isfull)
         break;
}

 

Common Error: Not breaking a loop when it is more efficient

When you have fulfilled your goal in a loop, no need is there to loop again. In loops such as for finding element purposes, traversing over each element is unneeded and inefficient:

String[] names = {"Mark", "Luke", "John"};
boolean found = false;
for (int i = 0; i <= names.length - 1; i++)
     if (name == "Mark")
          found = true;
          break; //needed for unnecessary element traversal

 

Common Error: Not breaking outer loops as intended

A break statement only breaks out the currently running loop, so if the loop you are in is nested in another one, the outer loop will not be broken out of, only the nested one:

So you need to break out of both in a case like this:

String[] names = {{"Mark", "Luke"}, {"John"}};
boolean found = false;
for (int row = 0; row <= names.length - 1; row++)
     for (int col = 0; col <= names[row].length - 1; col ++)
          if (name == "Mark")
               found = true;
               break;
     break; //another break needed here

 

Continue statement

continue;

continue is a reserved word used to skip to the next iteration of the loop.

Example (try it):

int balance = 0;
int startweek = 5;

for (int week = 0; week <= 9; week += 1)
{
     if (week < startweek)
          continue; //skip 0-4th weeks

     balance += 10;
}
//balance should be 50.

 

Scope

Scope means the accessible variables of an area.

Loops’ variables cannot be accessed from outside of loop.

Example:

while (true) //scope is iLoveCats
{
     boolean iLoveCats = true;
}

//scope is iLoveDogs.
boolean iLoveDogs = false;
Please like & share:

Conditionals

condition

Conditional statements are statements that run a statement if a given condition evaluates to true.

  

If/Else Statements

if (condition)
    statement
else if(condition)
    statement
else
    statement

if – tests a condition. If true, run a statement.

else if – same as above, but runs a statement when a preceding if or else if has failed.

else – runs a statement when all preceding ifs have failed conditions.

else if and else are optional.

Example:

if (x > 0)
     ;
else if (x < 0)
     ;
else
     ;
 Common error: mismatched parentheses

Not to go against the following (quite popular) brace format, but braces are often mismatched with beginners using it:


while(){
	if(){
	}
}

A recommended format for beginners is lining the braces up, making it obvious where the beginning and end braces of a block are:


while ()
{
	if()
	{ 
	}
}

 

Nested if/else Statements

If statements can be nested in one another as so:

if (x > 0)
    if (x < 0)
        ;
Common error: dangling else

An else block is always the else of an immediately preceding if. A common error is to believe that it is not (known as the “dangling else” problem):

if (x > 0)
    if (x < 0)
        ;
else //wrong to assume it like this
    ;

//it should be like:
if (x > 0)
    if (x < 0)
        ;
    else    
	;

Blocks can be placed to indicate which if that the else belongs to, to fix it:

if (num > 0)
{
    if (num <)
        ;
    else
        ;
}

 

Switches

switch(variable)
{
     case value:
           statements
 
     case value:
           statements
 
     ...
}

A switch is a shorter way to write a group of ifs that compare values.

A switch compares variable to value for each case and runs that case’s statements if it matches.

break can be inserted into statements to prevent the switch from comparing the next case.

Example ( try it):

char direction = 'W';
String destination = "Fremont";
 
switch(destination)
{
   case "LA":
   direction = 'S';
   break;
 
   case "Fremont":
   direction = 'E';
   break;
 
   case "San Jose":
   direction = 'N';
   break;
}

 

Selection operator

condition? to-return-if-true : to-return-if-false

This is a shortcut for returning a value if true, else return another value.

Example (try it):

boolean purchased = true;
int money = purchased? 0 : 100;
Please like & share:

Operators

 

calculator

Operators are symbols that create operations.

The left and right side of the operators used in the operation are called arguments.

  

Arithmetic Operators

Operator Meaning Example
+ Add 2 + 1 // result: 3
Subtract 2 – 1 // result: 1
* Multiply 2 * 1 // result: 2
/ Divide 2 / 1 // result: 2
% Modulo (division remainder) 2 % 1 // result: 0

These do arithmetic on numbers to produce a result of the type of the given numbers’ type.

Example (try it):

int x = 1 + 1; //result: 2

When one number is a whole number and the other is a real number, the result is a value of double.

Example (try it):

double x = 1 + .1; //result: 1.1

/ discards remainder when applied to two whole numbers.

Example (try it):

int x= 5 / 4; //result: 1

But not when adding a decimal point to one of them, making it a real number.

Example (try it):

double x = 5 / 4.0; //result: 1.25

+ also is used for joining Strings.

 

Assignment operators

Operator Example Equivalent
= x = y x = y
+= x += y x = x + y
-= x -= y x = x – y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
++ x++ x = x + 1
x– x = x – 1

Assignment operators set a variable (left of operator) to a value (right of operator) and can be shortcuts to equivalent expressions.

The ++ and — operators are for incrementing a variable or decrementing. Used in expressions, they can be placed before a variable or after a variable:

y = x++;
y = ++x;

The former statement is called postincrementing x and increments the variable x after setting y to it.

The latter statement is called preincrementing x and increments the variable x before setting y to it.

 

Comparison Operators

Operator Meaning Example
== Equals? 0 == 1 //false
!= Not equals? 0 != 1 //true
< Less than? 0 < 1 //true
> Greater than? 0 > 1 //false
<= Less than or equals? 0 <= 1 //true
>= Greater than or equals? 0 >= 1 //false

 These compare what is left to what is right of operator.

Result is a boolean (true or false).

Example (try it):

boolean result = true == true; //result: true

== is irregularly used for different value types. See below why.

 

Comparing Primitives

== tests if two primitives have similar values (no two primitives are ever identical).

1.0 == 1 evaluates to true.

Example (try it)::

boolean result = 1 == 1; //true
boolean result = 1.1 == 1; //false

 

Comparing Objects

== tests if two variables refer to the same exact object.

equals() uses the defined equals() method of an object to test if it is equal to another.

Example (try ti):

Object o1 = new Object();
Object o2 = new Object();
Object o3 = o2;
 
boolean result;
result = o2 == o3; //true
result = o1 == o2; //false
result = o1.equals(o2); //false

== is also used for testing if an object variable is set to any object at all. This is done by comparing a variable to null.

Example (try it):

Object o = null;
boolean result = o == null; //true

 

 Logical Operators

Operator Meaning Example
&& Both are true? true && false //false
|| One or the other is true? true || false //true
! Opposite of !true //false

Logical operators take two boolean expressions, evaluate them, and apply operation on them to yield a boolean result.

Example (try it):

boolean result;
result = true && false; //false
result = false ++ true; //true

 

Bitwise Operators

Operator Meaning
& AND
| OR
~ NOT
^ XOR
<< Left shift
>> Right shift

These apply logical operations on whole numbers (int,  byte,  long,  short).

The numbers are converted to base-2 first, applied the operator, and result is converted to whole number.

Example (try it):

int x = 1 & 5; // 0001 & 0101, result 0001, which is 1

 

Instanceof Operator

object instanceof class

This is a special operator used for checking if an object’s class is or inherits another class.

Result is a boolean.

Example (try it):

Object obj = new Object();
boolean inherits = obj instanceof Object; //true

 

Order of Precedence

Priority Operators Associativity
1 ()  []  . Left to right
2 ++  — ! ~ Right to left
3 * / % Left to right
4 + – Left to right
5 >> << Left to right
6 > >= < <= Left to right
7 == != Left to right
8 & Left to right
9 ^ Left to right
10 | Left to right
11 && Left to right
12 || Left to right
13 ?: Right to left
14 = += -= *= /= %= >>= <<= &= ^= |= Right to left
15 , Left to right

This shows the order in which operators are evaluated.

Arithmetic operations follow the same order of operations as found in algebra.

Please like & share:

Comments

 

Bubble_talk

Comments are remarks made by you for other human beings, to help them understand your code.

Comments are ignored by the compiler. That is, not executed.

 

Single Line

// comment

All from // to end of the line are ignored.

Example (try it):

x = 0; //all up to ; are compiled

 

Multiple Line

/* comment */

All from /* to */ are ignored.

Example (try it):

/*
     This is not compiled
 */

 

Documentation

/** comment */

All from /** to */ are ignored.

This is used by a utility called javadoc to document classes, interfaces, and methods.

See javadoc for more.

Please like & share:

Setup

Steps of setting up your computer to be able to follow this tutorial are here.

 

1. Install JDK

JDK (Java Development Kit) is the kit needed for you to write your own Java programs.

JDK can be downloaded from here. Select the proper one based on your operating system and open the file to install.

 

2. Install IDE

An IDE is an Integrated Development Environment: a program for developing your own programs.

You must install an IDE that knows the language of Java. Recommended free IDEs:

(I like Eclipse).

 

3. Make project

After installing your IDE, make a new project with whatever name you choose (like “tutorial”, usually by going file->new project from the menu bar).

How to do it with Eclipse.

 

4. Make file

Make a file called Tester.java (usually by going file->new file) and write this inside it:

class Tester
{
     public static void main(String[] args
     {
          //write here
     }
}

You may write the examples inside the brackets {} where it says “write here” and ignore all else for now.

Run the file from your IDE to test them (usually by going run->execute in the menu bar).

The rest of the parts will be understood in the sections Methods and Static.

 

Using println to see results

System.out.println(thing);

This writes things to the console (place that the compiler reports things to the user), meaning print thing on a line.

Change thing (marked green above) and press execute to print that thing.

Example (try it):

System.out.println(2); //print 2

You can also print things on the same line using System.out.print(thing) instead.

Please like & share: