Java tutorial

Revision as of 5 August 2014 15:52 by sannanordgren (Comments | Contribs)

This guide was written to help people with no Java experience get into the more advanced functions offered via the skin interface, for example the ability to write beanshell scripts (interpreted Java). This guide was very kindly written by Laura Seabrook and was previously posted to the forum. It is now presented here as a permanent reference.


glödlampa.png

You can run Java code samples interactively in the "jAlbum console window" available from the help menu.


This guide is broken down into four sections as follows:


Contents

1. Literals, Variables and Expressions

I'm writing this for people who, like me, aren't that familiar with Java as a programming language, but would like to use some of it to customise their jAlbum skins. I'm no expert -- in fact until I downloaded jAlbum I hadn't even looked at ANY Java coding. This is not a full tutorial because I don't know that much, but hopefully it will help you get started. The following has been culled from various books explaining Java, and from other topics in the forums, and repeats information from the help pages as well.

Scriptlets

The first thing to realise is that you can include Beanshell scripts directly on the htt pages. Beanshell is just a "shell" under which Java codes can be written and evaluated directly. To write such code, you need to place it like so...

<%
	CODE GOES HERE;
%>

or

<% CODE GOES HERE %> 

...in the location on the page that you want it to be evaluated. Within the section between the "<%" and "%>", you can place Java statements. Basically you put one statement per line, and end it with a ";", like...

userVar1 = 45;
uservar2 = userVar1 + 6;

If you DON'T put the semicolon at the end of a the statement, you'll probably get an error message when you try to generate an album -- the message will vary depending upon what the next statement is. It's also possible to place code in "blocks" delimited by curly brackets, e.g.

{
      LINE ONE OF CODE;
      LINE TWO OF CODE;
      LINE THREE OF CODE;
}

This comes in handy for IF statements (See PART 2 for details) because then a single IF can activate several lines of code. You can create a label by placing a colon after the label's name, e.g.

section_one:
section_two: STATEMENT;

...these can be handy for later documentation, and also breaking out of loops. You can also comment out bits of code in two ways:

// All code on this line is ignored
/* This is a block of comments that get ignored by Java until it is closed. */

The other important scriptlet to know is the EVAL function. Anything written like...

<%= EXPRESSION %>

...will return whatever value is indicated in the EXPRESSION listed. This might be a simple variable, like "userVar1", or something more complex like "filename.lastIndexOf('.')". This is important because if you're going to create and manipulate variables in a script, you need a way of putting the results into HTML codes.

Literals

Java uses literals and variables to assign and indicate values. A Literal has a fixed value, whereas variables can be changed. There are four types of literals.

Boolean

A boolean literal is either true or false, and is used to test/assign a result. e.g.

  
fileTest = '''false''';

Characters & Strings

A character literal is a single printable character and is indicated by putting single quotes around the character. e.g

   'A'         // The "A" character
   '?'         // The "?" character
   '\u0041'    // The "A" character
   '\u0022'    // The double quote character

...the last two lines show "Unicode" characters. The value (in hex) after the "\u" is a special code for the character. You will need to look up a java reference for a full list of codes. If you use "\" instead of "\u", you can insert an octal (base 8) character as well, for example...

   '\101'      // The "A" character (again)
   '\060'      // The "0" character (zero)

It is also possible to use a "special character escape sequence" which is a special code after the "\" character. The codes are:

   '\\' backslash // Not to be confused with the comments code
   '\"'        double quote
   '\''        single quote
   '\b'        backspace
   '\f'        Form feed
   '\n'        newline
   '\r'        carriage return
   '\t'        horizontal tab

Strings are consist of zero or more characters surrounded by double quotes. Note in the examples below how escape codes can be used in a string:

   ""                            // Gives an empty string of no characters
   "This is a test string"       // Has a value of: This is a test string
   "This is a \"test\" string"   // Has a value of: This is a "test" string
   "The value was \060"          // Has a value of: The value was 0

Numbers

Java supports floating point, integer and byte literals (and variables). There are different types of floating point literals (and variables) but what concerns us here is how to represent them. A floating point number can have an exponent (shown by using "E" or "e") and a type suffix ("F" or "f" for single precision, "D" or "d" for double precision):

   6.5E+3 (or 6.5E3)    // 65000.0 double precision
   7D                   // 7.0 double precision
   .01f                 // .01 single precision

Integers can be shown as a series of digits, followed by an optional suffix ("L" or "l" for long integer types). a prefix of "0x" indicates that the number is hex based (digits 0-9, and letters A-F), and a prefix of "0" indicates that it's octal based (digits 0-8). e.g.

   76       // Integer
   76      // Long Integer
   0x4a     // Hexidecimal number
   057     // Octal number that is a long integer

There is also a short integer type and a byte type, but in practice there's no difference in setting them than with a regular integer (see variables).

Null

A null literal represents no value and is simply listed as null. There is a difference between 0 (zero), "" (no string value) and null. The first two are actual values, whereas null isn't, You can use null in testing to see if a value has been set, e.g.

 
if (newTitle != null) title = newTitle;   // Assign newTitle to title, if it value

Variables

Simple variables (anything not an array or object) have values assigned to them, or re-assigned as needs to be. The variety of variable types matches the type of literals. A variable has to be assigned a value otherwise it has a "null" or "void" value. Assignments are made in the form of...

    TYPE  VARIABLE [, VARIABLE];
or [TYPE] VARIABLE = [VARIABLE = ] VALUE;

...where TYPE is the type of variable to be created (this is optional, hence the brackets), VARIABLE is the name of the variable to be assigned (e.g. userVar1), and VALUE is either a literal or an expression to be evaluated (e.g. userVar2+1 or "default"). All the following assign variables:

 
   boolean test1, fileExists  // Sets boolean variables test1 and fileExists
   userVar = "fred"     // assigns "fred" to a string variable called userVar
   byte   thumbX = thumbY = 0 // assigns 0 to byte variables thumbX and thumbY

If you don't explicitly give the variable a type, it will be assumed to of a type that matches the value assigned to it. e.g.

   userVar = 44      // integer number
   userVar = 44.5    // floating point number
   userVar = 44D     // double precision floating point number
   userVar = 'E'     // character
   userVar = "test"  // string
   userVar = true    // boolean

...however, you can also assign the type with a prefix. e.g.

   boolean limit   = (n>5)             // true if n is greater than 5, otherwise false
   byte    posXRay = -33               // a number between -128 to 127
   char    tabChar = '\t'              // assigns the TAB character to a character variable
   double  energy  = mass*velocity     // a value between +/- 4.9 times 10^324 power
   float   yPos    = 2.0345            // a value between +/- 1.4 times 10^45 power
   int     timeSec = distX-16000       // a value between +/- 2,147,483,647
   long    tempSol = 44.56             // a value between +/- 9 times 10^18 power
   short   userVar = 1533              // a value between +/- 32,767
   String  userVar = preFix + sufFix   // a concatenated value of strings preFix & sufFix

Normally you wouldn't be using more than three types of variables in jAlbum: boolean, integer and String. The other types still exist though. The main different in the types of number variables is how much space each occupies. The short variable only takes up two bytes of storage, whereas a double takes up eight.

Expressions

Assignments are actually a form of expression, where values can be manipulated and checked. Basically expressions will be either numeric, logical, character or string based. Expressions have OPERATORS and OPERANDS. The OPERAND is a value or variable, and the OPERATOR is a symbol that tells you what to do with the OPERANDS. e.g. in...

   userVar1 * 44

...userVar1 and 44 are the OPERANDS and the "*" symbol (for multiplication) is the OPERATOR.

Maths

Basic maths is supported in Java as per the following functions:

 
   testA * testB  // result is testA times TestB
   testA / testB  // result is testA divided by TestB
   testA - testB  // result is testA minus TestB
   testA + testB  // result is testA plus TestB
   testA % testB  // result is remainder of testA divided by TestB

   e.g.  20%6 = 2, 20%7 = 6, and 20%10 = 0

The "=" in assignment determines how the value is assigned to the variable, and there are variants to "=". The following examples show some of these:

   userVar1 += userVar2    // equivalent of userVar1 = userVar1 + userVar2
   userVar1 -= userVar2    // equivalent of userVar1 = userVar1 - userVar2
   userVar1 /= userVar2    // equivalent of userVar1 = userVar1 / userVar2
   userVar1 *= userVar2    // equivalent of userVar1 = userVar1 * userVar2
   userVar1 ^= userVar2    // equivalent of userVar1 = userVar1 ^ userVar2
   userVar1 %= userVar2    // equivalent of userVar1 = userVar1 % userVar2

You can also increase or decrease a variable by 1 using the following:

   userVar1 ++;            // equivalent to userVar1 = userVar1 + 1
   userVar1 --;            // equivalent to userVar1 = userVar1 - 1

If you want more complex mathematic, you have to call a Maths method to do it. Some methods are...

   Math.abs(uVar3)         // returns the absolute value of uVar3
                              e.g. Math.abs(-4)     = 4
   Math.max(uVar1, uVar2)  // returns the maximum of the two values
                              e.g. Math.max(3, -1)  = 3
   Math.min(uVar1, uVar2)  // returns the minimum of the two values
                              e.g. Math.min(3, -1)  = -1
   Math.pow(uVar1, uVar2)  // raises uVar1 to the power of uVar2
                              e.g. Math.pow(2,3)    = 2*2*2 = 8
   Math.sqrt(uVar3)        // equals the square root of uVar3
                              e.g. Math.sqrt(9)     = 3
   Math.round(uVar3)       // results in a rounding of uVar3 to the nearest integer
                              e.g. Math.round(5.321)= 5
   Math.random()           // equals a double precision number between 0 and 1. e.g.
                              int result = (int) (Math.random()*uVar3)+1
                              ...will result in a random integer between 1 and uVar3

There are other methods too, such as "acos", but it's unlikely that you'd need them to create an album.

Parenthesis

You can enclose parts or a whole of an expression in parenthesis, and this will affect the order in which the OPERATORs affect the OPERANDS, otherwise everything gets resolved more or less from left to right, though multiplication (*) and division (/) have a higher precedence than addition (+) and subtraction (-). e.g.

    8 + 3  * 2    // result = 14
   (8 + 3) * 2    // result = 22

Parenthesis are also used to specify an expression for testing, like...

    (userTest > 5) // result is true if userTest is over 5, otherwise is false

See Part 2-- Decision Structures for more detail.

Characters

Characters can be manipulated using Char methods, like...

   cVar = Character.toLowerCase("A") // character cVar is set to "a"
   cVar = Character.toUpperCase("a") // character cVar is set to "A"

Strings

String variables can be concatenated, like...

   userVar = "123" + "ABC"   // results in a value of "123ABC"

They can also be manipulated by using methods:

   sVar = String.toLowerCase("A Test") // character sVar is set to "a test"
   sVar = String.toUpperCase("A Test") // character sVar is set to "A TEST"

A more extensive list of methods you can use is given in Part 3 -- Methods List.

Conditional Operator

This is an operator which can set up alternative results. The form is:

   (CONDITION ? EXPRESSION1 : EXPRESSION2)

Two examples are...

    xPos1 = (xPos>xLimit ? 0 : xPos )

...sets xPos1 to xPos, unless it's over xLimit in which case, set it to 0 (zero), and...

   strVar = (strVal.equals("default") ? "red" : "green")

...sets strVar to "red" if StrVal equals "default", otherwise it is set to "green".

2. Decision Structures

Boolean conditions

if

switch and case

while

do while

for

break

3. Methods

Boolean

Numeric

Character

String

4. Interfacing with jAlbum

Original code

Example one - Tables

Example two - Filters