Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, October 20, 2018

Java Threading

Implement a class that implements IRunnable (requires run() method

// This code can reside inside or outside the class that implements IRunnable
Thread thread = new Thread(<instance of class that implements IRunnable)


thread.start();  // executes the run() method

public class SomeProcess implements Runnable{

Thread runner;

SomeProcess (){
  if (runner == null){
    runner = new Thread(this); // look for Run method in this class
    runner.start();  // executes the Run method
  }
}

public void Run (){
   Thread thisThread = Thread.currentThread();

   // thread terminates when Run() ends
}

OR

// set this.runner to null to terminate the thread by setting 
//  this.runner to null from anywhere else
// 
public void Run (){
   Thread thisThread = Thread.currentThread();
   while (runner == thisThread){

   }
   // thread terminates when Run() ends
}

}

Creating with an anonymous inner class

new Runnable() {
  public void run(){
  }}
}

Creating with a Closure

There is only required method for Runnable so we can define as Closure/lambda
Runnable runner = () ->  { // code for Run method }

Java Data Structures

BitSet -for representing binary data (indexed 0, 1 values)

ArrayList

Stack

HashMap - Dictiionary, key-value pairs

Generics - Create typed type structures
ArrayList<String>
HashMap<String, Float>

Java Access Modifiers


Sunday, June 30, 2013

Standalone Java Application

class <classname>
{
  public static void main(String args[])
 {
    // statements
    System.out.println{"Hello World!");
 }
}

  • The file name must be the same as the class name
  • To compile:  javac <filename.java>
  • Produces byte codes (not native object code).
  • Java Runtime (JRE) translates byte code to machine code at runtime
  • To run: java <filename.java>
To create a Java applet for the browser, create a class that exends JApplet

Saturday, June 29, 2013

Java Comments

// Single line comment

/*
  mutli-line comments
*/

/**
  mutli-line comments that can be harvested Javadoc tool for producing Java documentation
*/

Thursday, June 27, 2013

Java primitive data types

  • byte, bits, -128 to 127
  • short, 16 bits, -32,768 to 32,767
  • int, 32 bits, -2.1 billion to 2.1 billion (approx)
  • long -9E18 to 9E18 (approx)
  • float, 32 bits, precision to about 4 to 5 decimal points
  • double, 64 bits, higher precision than float
  • char, 16 bits, unicode character storage, defaults to \u0000
  • boolean, 1 bit, defaults to false

Tuesday, June 25, 2013

Java Variables, Methods, Classes, Constants, naming and escape sequences

Variables

  • Can start with dollar symbol or underscore
  • Cannot start with a number
  • Cannot be a reserved word
  • No limit on the length of the name
<datatype> <variable name>;
int number = 1;

// array
<dataytpe> [] arrayname = new <datatype> [<number of elements>];
int [] list = new int[10];

// multi-dimensional arrays
int matrix [] [] = new int[4] [5];

Method Names

  • Verbs or verb phrases
  • first letter of the method name is lowercase
  • first letter of subsequent words is capitalized
  • Cannot be reserved word
  • Example: calculateMonthlyPayments

Class and Interface Names

  • Begins with capital letter
  • First letter of each word in the name is capitalized

Constant Names

  • Use all caps
Example: Color.BLUE

Escape sequences

  • \n New line
  • \t Horizontal tab
  • \b Backspace
  • \r Carriage return
  • \f Form feed
  • \\ Backlash
  • \" Double quote
  • \ddd Octal character
  • \xdd Hexadecimal
  • \udddd Unicode characters

Operators

  • <
  • <=
  • == ( for primitives compares values; for reference types compares object identity; for reference types, by convention, equals() method is implemented to compare values contained in the object for determining equality; String class even has equalsIgnoreCase)
  • !=
  • >=
  • >
  • &&
  • ||
  • !

Friday, June 21, 2013

Java Classes and Interfaces

Class declaration

<modifier> class <classname> extends
    <superclass> implements <interface>
{

   // Constructor
   public <classname>(<datatype> someArg)
  {
  }
   // Another constructor
   public <classname>()
  {
    // call the other constructor
    this(someValue);
  }
   // member declarations
  <access specifier> <static/final/transient/volatile> <datatype> <variablename>;

   // method declarations
  <access specifier> <static/final> <return type> <method name> <argument list>
  {
     // method body
  }
}

Interface declaration

interface <interface name>
{
   <return type> <method name> <argument list>;  // no body for the method
}

Wednesday, June 19, 2013

Java Packages


  • Packages are used to group related classes together.
  • The java source directory structure mirrors the package naming.
  • When creating package, the package statement appears as the first statement in source file.
  • The user of a class in a package must import the package.
  • Packages can be compressed into Jar file; to see contents of Jar file use  jar -tvf fileName.jar
  • Jar files may also include directories, subdirectories to represent class and package hierachy
  • If the package is stored inside a jar file, we have to include the jar file with its extension (.jar) in the CLASSPATH. However, if the package is a plain directory, we just put the name of directory into the CLASSPATH.
// search for packages from the current directory as wells as from myclass directory of C drive
set CLASSPATH=.;C:\myclasses;

// to access classes in a JAR file
set CLASSPATH=.;D:\JSDK2.0\lib\jsdk.jar;

Once in a package either use fully qualified class names (e.g. System.Awt.Font) or import the package (then we can simply reference Font).

import.util.Scanner;  // Import a particular class
import java.awt.*;   // Import all classes java.awt
import java.awt.event.*;
import java.javax.swing.*;




Monday, June 17, 2013

Java Keywords

abstract


  • class - contains abstract methods, cannot be instantiated
  • interface - all interfaces are implicitly abstract. Optional.
  • method - Signature is followed by semi-colon but no body. The enclosing class must be abstract.

boolean

break
byte
case
catch
char
class
const
continue
default
do
double
else
extends

final


  • class - cannot be subclassed
  • method - cannot be overridden
  • variable - value can be changed (constant)


finally
float
for
goto
if
implements
import
instanceof
int
interface
long

native


  • method - implemented in a language other than Java such C++. Methods do not have bodies.

new
null
package
private
protected
public
return
short

static


  • method - class method. cannot refer to non-static variables and methods of a class. Method is implicitly final. Invoked through class name.
  • variable - only copy regardless of how many class instances are created. Access through the class name.

super
switch

synchronized


  • method - Only one synchronized method can be run for each class.

this
throw
throws
transient
try
void
volatile
while

Wednesday, June 12, 2013

Frequently used Java Classes

Java API Reference
http://docs.oracle.com/javase/7/docs/api/
  • java.lang.System (System.out.print("some text");)
  • java.lang.Thread
  • java.awt.Button
  • java.awt.Color
  • java.awt.Font
  • java.awt.Graphics
  • java.swing.JPane
  • java.util.Scanner (to process keyboard input)
  • java.net (URL, HttpURLConnection, Socket, ServerSocket)

Thursday, February 14, 2013

Java Flow Control Constructs

if

if (condition)
{
   statements;
}
else
{
   statements;
}

for

for (i=0; i<100; i++)
{
}

while loop

while (condition)
{
   statements;
}

do... While loop

do
{
  statements;
}
while (condition);

switch

switch (variable)
{
  case (v1):
    statements;
    break;
  case (v2):
     statements;
     break;
  default:
     statements;
     break;
}