HomeJava & J2EE Page 5 - The JSP Files (part 1): Purple Pigs In A Fruitbasket
Putting Two And Two Together - Java
Get to grips with Java Server Pages with this introductorytutorial and find out how to use one of the more powerful server-sidelanguages around. This first part explains the history and basics of JSPdocuments, and also illustrates variables, includes and the String object.
Just as you can create a variable to hold strings, you can create variables of other types too:
int - used to store integers
char - used to store a single character in Unicode format
float and long - used to store floating-point numbers
boolean - used to store "true" and "false" values (note that unlike languages like C and PHP, JSP does not recognize 1 => true and 0 => false)
Let's take a simple example that adds two numbers and displays the result.
<html>
<head>
</head>
<body>
<%!
int alpha = 45;
int beta = 34;
int Sum;
%>
<%
// add the two numbers
Sum = alpha + beta;
// display the result
out.println("The sum of " + alpha + " and " + beta + " is " + Sum);
%>
</body>
</html>
And the output is:
The sum of 45 and 34 is 79
In this case, we've simply defined two variables as
integer values, assigned values to them, and added them up to obtain the sum.
In a similar vein, the next example demonstrates adding strings together:
<html>
<head>
</head>
<body>
<%!
// define the variables
String apples = "The lion ";
String oranges = "roars in anger";
String fruitBasket;
%>
<%
// print the first two strings
out.println("<b>The first string is</b>: " + apples + "<br>");
out.println("<b>The second string is</b>: " + oranges + "<br>");
// concatentate the strings
fruitBasket = apples + oranges;
// display
out.println("<b>And the combination is</b>: " + fruitBasket + "<br>Who
says you can't add apples and oranges?!");
%>
</body>
</html>
And the output is:
The first string is: The lion
The second string is: roars in anger
And the combination is: The lion roars in anger
Who says you can't add apples and oranges?!
In this case, the + operator is used to concatenate two
strings together, which is then displayed via println().