Introduction To Java
Developing with Java:
Programming
languages are categorized according to their capabilities; they are either
system, application or designed for Artificial Intelligence. C and C++ can be used to develop system
and/or application software, where they provide standard libraries rich with
programming tools. Object oriented
programming is the cutting edge and more and more system and application
software are moving toward object-oriented design. The latest in software development is creating reusable components. With Web coming on scene, software
development is taking a whole new look.
Where does Java fit in all these categories? Java is designed to do all these types of programming categories,
but it may not be the best for some categories. Java is an object oriented programming language that can be use
to develop application, applets, system, reusable components and servlets. We will cover each category briefly and
hopefully they all will be cover extensively in the coming sections.
Application:
An
application is a stand-alone Java program that runs on any computer or
system.
Applet:
An applet is a Java program that
can NOT run by itself, but needs a browser or an applet viewer to run the
applets. Basically, applets are
designed for Java programs that run on the Web.
JavaBeans:
“a
reusable software components that can be manipulated visually in a builder
tool”.
Applications
and applets are user defined Java classes that composed of data objects
(variables), methods, which may include constructors. A JavaBean or a Bean for short is also a user defined class that
is composed of the same thing, but it is designed to be reusable software
components, that can be manipulated visually in a builder tools. A reusable component here means an independent
subprogram that can be added to an existing program.
Servlets:
A server is the service provider on
the Web. For example, a computer
requesting data from a network is a client and computer that is providing the
data is the server. Servlets are Java
programs designed to be part of a Web server.
Servlets are developed using the Java Servlet Application Programming
Interface (API) in addition to the Java classes and packages. Servlets extends the server capabilities by
providing Web services such as communicating with server database resources.
Please note that we will develop application first to cover
the Java language and almost all its features then we will be cover applets and
Beans.
First Program (Application):
We will
start this section by listing the firstProgram.java, which is an example of a
Java application. Example # 1 is a
simple program that prints one message on the monitor. It is composed of a class called
“firstProgram” and has two methods declared within the class. The first method “firstProgram”, which is
known as the class constructor and the second is a “main” method, which is a
static method. The “firstProgram”
class is instantiated to create a class object using the “new” operator. The “firstProgram” class is declared as a
public class. The “java.lang” package
is imported in order to call the “System.out.println” method to print the
"**** First Program ********" message. We will briefly cover some these terms
mentioned in this paragraph hoping to put the reader at ease and not overwhelm
the reader to too many new computer jargon.
Example # 1:
/**************************************************
** This is example of a Java
application to print a message
***************************************************/
import java.lang.*;
public class firstProgram
{
public
firstProgram()
{
System.out.println("**** First Program ********");
}
//------------------------------------------------
public static void
main(String [] args)
{
firstProgram
MyfirstProgram = new firstProgram();
}
}
Output:
**** First Program ********
Java File Name and Directories:
A Java
source file must have the extension “.java”.
The source file name should be the same as the class name declared
within it. For example, firstProgram class
is declared in a source file named firstProgram.java. If there is more than one class declared within a source file,
there should be only one public class declared in that source file and the rest
of the classes should not be public. If
these is more than one class needed to be declared as a public class, then each
public class should has its own source file with the same class name as the
source file name and the extension “.java”.
Directories
do not have to follow the same rules as the source file, but there is a
standard convention for naming directories as the name of the packages or
sub-packages. A package is grouping a
number of programs under one group or package name. For example, if we group all the examples in this section and
put them in a package called “ChapeterTwoExamples”. We can create a directory for each source file with the same as
the source files and place it in a directory called “ChapeterTwoExamples”. The “ChapeterTwoExamples” can be a
sub-package of a directory called “Examples”.
The directory listing of “Examples” directory would as follows:
C:\Examples\
ChapeterTwoExamples\
firstProgram\
firstProgram.java
CommaAndForLoop\
CommaAndForLoop.java
PrimitiveDataType\
PrimitiveDataType.java
IfElseStatements\
IfElseStatements.java
In the above listing, each source directory has the same
name as source file name, which has the same as declared public class within
the source file. The above listing is
not a must, but it is a naming convention adapted by Java developers. This helps group both source file and byte
code file as well as files such as bitmap file in one directory for
organization and quick search.
Java Class:
A Java
class is a type. It is a collection of
data and methods that operate on the data.
The “class” is a reserved word in Java.
A class must be declared before it instantiated to create an
object. For example, the “firstProgram”
class is declared and is instantiated in the static “main” method to create a
class object.
Class Constructor (First Visit):
A constructor is a
class member method that affects the creation of the class object and it has a
unique declaration. A constructor member method is a special member method that
initializes the class object, sets a side memory space and is automatically
called whenever the a class object is created. A constructor is a class member method like any other member
method. A constructor is a class
member method with the following properties:
1.
The
constructor has the same name as the class it is declared in.
2.
A
constructor does not return any value (not even a void).
3.
It may take
a zero or more arguments.
Java Object:
An object is a region of storage
that has a scope and type. Object
oriented programming as well as Java defines an instance of a class as an
object.
Instantiation of Class Object:
A class
is a collection of data and methods, which operate on the data. A class may be created using class handle to
produce an object that is an instance of the class. This process is called “instantiation” of class object. The class handle must be created and equated
to the creation of the object using “new” operator. The following is an example of instantiating a class declared in
Example # 1:
firstProgram MyfirstProgram = new firstProgram();
or
firstProgram MyfirstProgram;
MyfirstProgram = new firstProgram();
Note that “new” operator is used to instantiate a class
after the class handle is declared.
Also note that the open and close parentheses “()” are used with the “new
firstProgram();” since a call to class is actually a call to the constructor of
that class.
Java application:
A Java application is a Java
program that can run on any computer system and it is composed of a public
class that may have the following:
1.
The name of the file that contains the class must be the same
name of the public class that is defined within that file (case sensitive).
2.
Must have a static
“main” method.
3.
Zero or more classes defined within (inner classes) the main
public class.
4.
Zero or more other classes, which are declared outside the
current class and may be located in different classes or packages.
5.
Zero or more constructors
6.
Zero or more Attributes (data objects – variables)
7.
Zero or more methods.
8.
Zero or more “import” statement.
9.
Zero or more “package” statement.
10.
Zero or more Interfaces.
11.
Zero or more Exception handler.
We need to examine Example # 1 and see it qualifies as an
application. Example #1 declares a
firstProgram class as public class. It
is declared within a file called firstProgram.java. It declares one constructor “firstProgram”. It has a static “main” method declared with
the class. It has one import statement
to provide access the “System.out.println()” method, which is a method within
the “java.lang” package. It has zero of
the followings:
1.
Inner classes
2.
Classes declared outside the current class.
3.
Attributes (data objects – variables)
4.
Methods.
5.
“package” statement.
6.
Interfaces.
7.
Exception handler.
The Java firstProgram program qualifies as an application
since it has the two main ingredients, a public class defined within a file
with same name as the class and a static “main” method.
Compiling and Running Application:
Compiling
and running any Java program is will vary greatly from one compiler to
another. The reader should look up the
compiler on-line help or manuals.
Java programs are compiled to “Byte
Code” which is a machine code for an imaginary machine called “Java Virtual
Machine” – (JVM). This byte code is
independent of any plate-form. Most JVM
runtime is an interpreter, which is provided by each plate-form. This interpreter executes the byte code of
JVM within its own private system parameters.
firstProgram.java
firstProgram.class
A Java source file must have the
extension of “.java” and one file may contains more than one Java class. The Java source file will compile and
generate a separate “.class” (JVM byte) file for each class that is declared
within a “.java” source file.
For example, if there is a “.java” source file that contains one class,
it will compile and generate one “.class” (JVM byte) file. If an other “.java” source file which has
two separate classes and each class has tow inner classes which totals up to six classes. This “.java” source file will compile and
generate six “.class” (JVM byte) files; one file for each class. The Java “firstProgram” program will
compile and generate only one “.class” files.
As a practice, the reader should write an application, which
prints his/her name.
Standard Data Type and Statements:
We will cover each of the data type
and statements types briefly with short example. Most programmers and engineers may skip this section or glance
at it and see if there is syntax or semantics of Java that does not look
familiar, which it should be read and the given examples should be
checked. Our objective here is help
beginners learn Java syntax and semantics as quickly as possible using example
programs.
In C
language, different compilers have different size of each data type and there
is signed and unsigned integer types.
For example, an “int” data type on one system can 32 bits and on an
other 16 bits. Java has an explicit
size for all its primitive data types as well as its arithmetic behavior. For
example, the size of an integer “int” in Java is four bytes regardless of which
plate-form. There is no unsigned
integer as in C or C++.
Java
has an implicit size for each data type and does not provide unsigned
integers. In the case of bit-wise
operation of shifting bits using “>>” and “<<” operators, Java has
“>>>” Right Shift operator which shifts the bits to the right without
losing the sign value of the integer being shifted. Java has two new data type which are byte and boolean. Java does not have a String as data type,
but Java has two classes that manipulate strings, which are “String” and
“StringBuffer”
Java Constants:
Most programming
languages provide two types of constants a Literal constants and Escape
sequence Java provides both as follows:
1.
Literal:
Constant Values are known as Literals.
Literals are as follows:
A. Integer
Constants:
An
integer is a number with no fraction which can be:
1.
integer value (short or int) - 12, 32676
2.
long integer - 12L(or l), 989898L
3.
OctalNumber -012,0367(must precede with a Zero)
4.
Hexadecimal - 0XAD7,
0xabc (must precede with Zero and X (or x)
5.
Character - 'A', 'a',
'*', ' ' (blank) A character is an integer constant written within a single
quotes.
B. Float
point constant
A floating point
constant may contain a fraction and or exponent. It has a range far larger than the integer. The following are floating point constants:
1, 2.345, 1.3E+234, 1.3e-234, 123456789098
C. String
constant
A string constant
is a zero or more characters enclosed within double quotes such as "joe
was here", "JOE WAS HERE", "Joe Was Here",
"" (Null string - zero number of characters).
2.
Escape sequence
An escape is a
sequence of two or three characters following the "\" slash character
that represents one character. For
example, "\n" represents new line character. The following is the escape sequence list:
\a, \b, \t, \n, \r, \\, \', \", \v,
\?, \0000 (\0000 = sequence of 4 octal
digit)
boolean:
A
boolean value is not an integer and may not be treated as an integer. A boolean value can not be casted to or from
any other type. A boolean variable can
be assigned to expression that results in True or False value. For example, conversion of an integer value
to boolean can be done as follows:
Boolean TrueOrFalse = false;
int IntHas32Bits = 10;
…
TrueOrFalse = (10 == IntHas32Bits);
if(TrueOrFalse)
System.out.println("SetToTrue = TRUE and IntHas32Bits =\t" + IntHas32Bits);
else
System.out.println("SetToTrue = FALSE and IntHas32Bits =\t" + IntHas32Bits);
System.out.println("TrueOrFalse = \t" + TrueOrFalse);
The above code segment has an expression testing to for 10
equals “IntHas32Bits” and the evaluation of this expression will result in a
true or false value, which will be stored in “TrueOrFalse” boolean
variable. Boolean value can also be
printed as in the last println statement.
char:
C
treats char type as an integer that can be signed and unsigned. Java treat chars as actual characters which
with 16 bits in size. The size of char
(16 bits) gives the ability to store up to 32768 different characters. The Java char type holds what is known as
“Unicode” character. “Unicode” has the
range of “\u0000” to “\uFFFF”. The first 256 char are the ASCII characters
and the remaining (32,768 – 256) can used by any one or any system. This makes a Java char type flexible to be
used as any characters other the ASCII.
This gives room for characters other than English, such as Chinese,
Arabic or Russian.
Java
“Unicode” support all the Java escape sequence such as ‘\n’, ‘\r’. The octal digits in Java are four digits
“\XXXX” and not the three digits “\XXX”
of C. The followings are two major
differences between “Unicode” escape and Java escape characters:
1.
“Unicode” escape char can appear in place in the code, while
the other escape characters can only appear in characters and string quotes.
2.
“Unicode” escape char are processed before the other escape
characters.
byte, short, int and long:
“byte,
short, int and long “ are integer types with specific size. They are unsigned types. The following is a list of each integer type
and their bits sizes:
Byte 8
bits -128
to 127
Short 16 bits -32768
to 32767
int 32 bits
Long 64 bits
Float and double:
These
floating point type are IEEE 754 floating point. Their type and bits sizes are as follows:
float 32
bits
double 64
bits
Example # 2 is a quick Java program to illustrate how to
declare primitive data types, initialize them with some constants and print
them. Note that the String is not a
Java primitive data but a Java class declared as part of the “java.lang.String”
package. We may not need to import the
“java.lang” package since most compilers will imported by default.
Example # 2:
/************************************************
** This Java application is to illustrate
the Primitive data type.
*************************************************/
import java.lang.*;
public class PrimitiveDataType
{
boolean TrueOrFalse = false;
char CharHas16Bits = 'A';
byte ByteHas8Bits = 12;
short ShortHas16Bits = 155;
int IntHas32Bits = 10;
long LongHas64Bits = 1234;
float Float_1 =
(float)3.1; // must be casted
double DoublePrecision = 19.9;
String Title =
"Primitive Data Type";
public
PrimitiveDataType() // constructor
{
System.out.println("\t\t"
+ Title);
System.out.println("\n******************************************\n");
System.out.println("Char16Bits = " + CharHas16Bits);
System.out.println("ByteHas8Bits = " + ByteHas8Bits);
System.out.println("ShortHas16Bits = " + ShortHas16Bits);
System.out.println("IntHas32Bits = " + IntHas32Bits);
System.out.println("LongHas64Bits = " + LongHas64Bits);
System.out.println("Float_1 = " + Float_1);
System.out.println("DoublePrecision = " + DoublePrecision);
if(TrueOrFalse)
System.out.println("SetToTrue = TRUE");
else
System.out.println("SetToTrue = FALSE");
System.out.println("\n******************************************");
}
//***************************************************
public static void
main(String [] args)
{
PrimitiveDataType MyPrimitiveDataType = new PrimitiveDataType();
}
}
Output:
Primitive Data
Type
******************************************
Char16Bits =
A
ByteHas8Bits =
12
ShortHas16Bits = 155
IntHas32Bits =
10
LongHas64Bits =
1234
Float_1 = 3.1
DoublePrecision = 19.9
SetToTrue = FALSE
******************************************
Comments:
Comments
are ignored by the compiler and not included in the executable program. Java provides three types of comments which
identical to C++ comments. The first is
the /*…*/ where the compiler will ignore any statements between /* … */. /*...*/ comment may run for several
lines of statements. The second is
“line” comment which is composed of “//”a double slashes. The compiler will ignore any statements
following the “//” until the end of line (Carriage Return) is encountered.
The
third type of comment is /** DOC … */ “Doc” comment which is similar to C++
documentation comments. “Doc” comment
is processed by the “javadoc” program to produce simple online documentation
from the Java source code.
Note: No nesting of comments are allowed.
Statement:
Like
most languages Java’s statement is a command to the system to execute. Statements can be of the following:
1.
Labeled Statement
A.
case expression:
B.
default:
2.
Expression Statement
A.
Assignment Statement (
Value = 10;)
B.
Method Call
C.
Null Statement – ( ; )
D.
Import Statement
1.
import packages
2.
import Java classes
E. Synchronized Statement
3.
Compound Statement – Block
( {…} )
4.
Selection Statement
A.
if ( expression) statement
B.
if (expression) statement else statement
C.
switch statement
D.
Exception and Exceptional Handling - try {}catch(…){} finally
{}
5.
Jump Statement
A.
No goto Statement
B.
Continue
C.
Break
D.
Return
6.
Iteration Statement
A.
for (initialization expression; terminating expression; update
expression) statement
B.
do statement (expression);
C.
while (expression) statement
We will briefly cover each of each statement with a short
example in the next section.
Language
Syntax and Semantics:
Every
computer language provides rules that govern the construction of a valid
statement (syntax) and another set rules which give the meaning of a statement
(semantics). We will not get too
technical and lose our audience, but we will help the reader learn what is and
is not allowed using actual Java programs.
Selection Statement:
The Selection statement helps with
choosing one of several control flows. It gives the programmer ability to
branch to of number of statements. It
can be one of the following statements:
1.
if statement
if(expression)
statement
2.
if statement else statement
if(expression)
statement
else
statement
3.
Ternary Operator
Expression ? statement: statement;
4.
switch statement
switch(expression)
{
case
constant expression : statement
case
constant expression : statement
default : statement
}
5.
Exception and Exceptional Handling
try
{
statement
}
catch(parameter type identifier)
{
statement
}
The “if”, “if else” and “? : ;” ternary operator require a
boolean expression be evaluated and the result would branch the control
flow to the proper statement. The “if” and “if else” statements can be
nested. The “switch” statement evaluates an expression that will send the
control flow to a label with a constant expression. If there is no label constant that matches the “switch”
statement expression, the control flow will go to the “default” label.
Exception
handling is an attempt to handle known errors by executing the suspected
statement(s) within the “try” block and if an error occurs the control flow
would go to the “catch” block to handle the error, other wise the control flow
will skip the “catch” block.
Example # 3 has code to illustrate
“if”, “if else” and “? : ;” ternary operators, while Example # 4 has the code
for the “switch” statement. Example # 3
declares “IfElseStatements” class that has a constructor and the
“ReadPositiveIntFromKeyBoard()” method.
This method is a simple example of how to read a positive integer from
the keyboard. It has an “IOException”
exception, which handles the known error of getting a character from the
keyboard. If the statement in the “try”
block fails, the control flow will go to the “catch” block and returns a zero
or the “Total”. The code in the
constructor reads three integer numbers and uses nested “if else” statements to
figure out the grade. The code uses
three ternary expression to get the highest score out of the three scores. It prints the output to the screen as given
in the output section of Example # 3.
The logical operators AND "&&" and OR "||"
will be covered in the logical operators section. The difference between the “println()” and “print()” method is
the fact “print()” will not advance the cursor to the next line as the
“println()” method does. The “print()”
method is used to print a prompt for a user input. The “IfElseStatements” class is instantiated in the static
“main” method using the “new” operator to create an “IfElseStatements” class
object.
Example # 3
/*******************************************************
** This program illustrates the if - else statements. It also
illustrates
** the logical operators AND "&&" and OR
"||"
*******************************************************/
import java.lang.*;
public class IfElseStatements
{
public
IfElseStatements()
{
int Test_1, Test_2, Test_3;
int Average;
int HighestTest = 0;
System.out.println("\n\n\nEnter
three test score between 0 - 100");
System.out.print("Please Enter
First test score ====> ");
Test_1 = ReadPositiveIntFromKeyBoard();
System.out.print("Please Enter
Second test score ====> ");
Test_2 = ReadPositiveIntFromKeyBoard();
System.out.print("Please Enter
Thirs test score ====> ");
Test_3 = ReadPositiveIntFromKeyBoard();
if(
(Test_1 > 100) ||
(Test_2 > 100) ||
(Test_3 > 100)
|| (Test_1 < 0) ||
(Test_2 < 0) || (Test_3
< 0)
)
{
System.out.print("Error - No Test
Score should be graeter than");
System.out.println(" 100 or less
than zero");
return;
}
Average = (int)(((Test_1 + Test_2 +
Test_3) / 3.0) / 10);
if(Average < 6)
System.out.println("Failing Grade
with an average = " + Average *
10);
else
if( (Average >= 6) &&
(Average < 7))
System.out.println("You got D
Grade with an average = " + Average * 10);
else
if( (Average >= 7) &&
(Average < 8))
System.out.println("You got C
Grade with an average = " + Average * 10);
else
if( (Average >= 8) && (Average
< 9))
System.out.println("You got
B Grade with an average = " + Average * 10);
else
if( (Average >= 9) &&
(Average < 11))
System.out.println("You
got A Grade with an average = " + Average * 10);
else //* default:
{
System.out.print("This
is the default case, ");
System.out.println("there must be an error");
}
HighestTest = (HighestTest < Test_1)?
Test_1: HighestTest;
HighestTest = (HighestTest < Test_2)?
Test_2: HighestTest;
HighestTest = (HighestTest < Test_3)?
Test_3: HighestTest;
System.out.println("\n\n Highest
Test = " + HighestTest);
}
//****************************************************
public int
ReadPositiveIntFromKeyBoard()
{
int
InputByte;
int
Total = 0;
try
{
InputByte = System.in.read();
// skip carriage return
if(
('\n' == InputByte)
||
('\r' == InputByte)
)
InputByte = System.in.read();
}
catch(IOException MyIOException)
{
return (0);
}
while(
(InputByte >= '0')
&& (InputByte <= '9')
)
{
Total = (Total * 10) + (InputByte - ('0'));
try
{
InputByte = System.in.read();
}
catch(IOException MyIOException)
{
return (Total);
}
}
return(Total);
} // ReadPositiveIntFromKeyBoard
//****************************************************
public static void
main(String [] args)
{
IfElseStatements MyIfElseStatements = new IfElseStatements();
}
}
Output:
Enter three test score between 0 -
100
Please Enter First test score ====> 90
Please Enter Second test score
====> 91
Please Enter Thirs test score ====> 92
You got A Grade with an average =
90
Highest Test = 92
Labeled Statement:
Label
statements may have label prefixes.
Labels are basically an address to jump to or GOTO. Labels have unique names and should not be
duplicated or re-declared. Labels can
be one of the followings:
1.
“goto” Statement
Java does not allow any GOTO
statements.
2.
case expression
3.
default
The “switch” statements uses the
“case” and “default” labels. An integer
type must follow the “case” label.
Example # 4 has code to illustrate the “switch”
statement. It declares
“SwitchStatement” class that has a constructor and the
“ReadPositiveIntFromKeyBoard()” method.
This method is a simple example of how to read a positive integer from
the keyboard. It has an “IOException”
exception, which handles the known error of getting a character from the
keyboard. If the statement in the “try”
block fails, the control flow will go to the “catch” block and returns a zero
or the “Total”. The code in the
constructor reads three integer numbers and uses the “switch” statement to
figure out the grade. Note that “break”
statement is used to end the control flow and sends it the end of the “switch”
statement. The “case” 0 to 4 have no
break and control flow drops from “case 0:” to “case 5” executes the
“println()” statement then it reaches the “break” statements and break out of
the “switch” statement. For example, if
the average of all test scores is equal 2, 3 or 4, the control flow will jump
to that case label. Since there no statements
to be executed, it will drop to next case and so on executing any statement in
its path until it reaches the “break” statement and breaks out of the “switch”
statement.
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 :
System.out.println("Failing
Grade with an average = " +
Average * 10);
break;
The “SwitchStatement” class is instantiated in the static
“main” method using the “new” operator to create an “SwitchStatement” class
object.
Example # 4
/********************************************
** This program illustrates the SWITCH statement. **
********************************************/
import java.lang.*;
public class SwitchStatement
{
public
SwitchStatement()
{
double Test_1, Test_2, Test_3;
int Average;
System.out.println("\n\n\nEnter
three test score between 0 - 100");
System.out.print("Please
Enter First test score ====>
");
Test_1 =
ReadPositiveIntFromKeyBoard();
System.out.print("Please
Enter Second test score ====> ");
Test_2 =
ReadPositiveIntFromKeyBoard();
System.out.print("Please
Enter Third test score ====>
");
Test_3 =
ReadPositiveIntFromKeyBoard();
if( (Test_1 > 100) || (Test_2 > 100) ||
(Test_3 > 100)
|| (Test_1 < 0) ||
(Test_2 < 0) || (Test_3
< 0)
)
{
System.out.print("Error
- No Test Score should be graeter than");
System.out.println("
100 or less than zero");
return;
}
Average =
(int)(((Test_1 + Test_2 + Test_3) / 3.0) / 10);
switch (Average)
{
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 :
System.out.println("Failing
Grade with an average = "
+ Average * 10);
break;
case 6 :
System.out.println("You
got D Grade with an average = "
+ Average * 10);
break;
case 7 :
System.out.println("You
got C Grade with an average = "
+ Average * 10);
break;
case 8 :
System.out.println("You
got B Grade with an average = "
+ Average * 10);
break;
case 9 :
case 10:
System.out.println("You
got A Grade with an average = "
+ Average * 10);
break;
default:
System.out.println("This is the default case, there must
be an error");
} /* end of switch statement */
}
//****************************************************
public int
ReadPositiveIntFromKeyBoard()
{
int InputByte;
int Total = 0;
try
{
InputByte =
System.in.read();
// skip carriage
return
if( ('\n' == InputByte)
||
('\r' == InputByte)
)
InputByte =
System.in.read();
}
catch(IOException
MyIOException)
{
return (0);
}
while( (InputByte >= '0')
&&
(InputByte <= '9')
)
{
Total = (Total *
10) + (InputByte - ('0'));
try
{
InputByte =
System.in.read();
}
catch(IOException
MyIOException)
{
return (Total);
}
}
return(Total);
} // ReadPositiveIntFromKeyBoard
//****************************************************
public static void
main(String [] args)
{
SwitchStatement MySwitchStatement = new SwitchStatement();
}
}
Output:
Enter three test score between 0 -
100
Please Enter First test score ====> 45
Please Enter Second test score
====> 55
Please Enter Third test score ====> 66
Failing Grade with an average = 50
Expression
Statement:
The Expression statement is the workhouse
of the Java language. Most statements
are expression statements. The following is a list of expression statements:
1.
Assignment Statement
An assignment statement must use
one of the assignment operators.
=, *=, /=, %=, +=, -=, >>=,
<<=, &=, ^=, |=
All assignment statements require
a Lvalue, which must be modifiable.
Fore example:
Joe = 10;
XX
+= (10 + 5) /35;
2.
Method Call
Method call is a way to send
control flow to a predefined block of code to be executed and returns the
control flow to the next statement following the method call. Methods may take arguments and return
values.
System.out.println("This
is the default case, there must be an error");
Test_1
= ReadPositiveIntFromKeyBoard();
3.
Null Statement
There are three null things in
most programming languages. They are as
follows:
A.
null statement
no statement is given – empty
block
B.
null string
String myString = “”;
C.
null value
null is a special value, which
indicates that a variable or a reference does not reference any object.
SwitchStatement MySwitchStatement
= null;
SwitchStatement MySwitchStatement_2
= new SwitchStatement();
4.
Import Statement
“import” statement is a way of
making the Java classes of packages available to be called within a
program. A class of an imported package
can be referred to without giving its full name. The “import” statement must appear before any code.
import java.lang.*;
A Java program can import any of
the following:
A.
Entire package
import
java.lang.*;
B.
A class within a package
import java.lang.System;
C.
A method of a class within a package
import java.lang.System.in.read;
import
java.lang.System.out.println;
5.
import packages
Classes can be grouped together to
make a package. There are a number of
advantages of being a part of a package such as sharing values, methods and
constants. To let the compiler know
that a class (within a file) is part of a package, the very first statement of
that class file must be a package statement.
package programmingExamples;
import
java.lang.*;
public class SwitchStatement
{…}
6.
Synchronized Statement
Java supports multithreaded
programming, where a number of threads may be running simultaneously. These threads may share resources such as
objects or arrays. The synchronization
of updating of one of these resources might be critical. The sections of code that should not be
executed simultaneously are called “critical sections”. The synchronized statement is a protection
of the resources, where no other than the specified critical section (code) has access to these resource. Having an exclusive lock for these resources
insures that only the specified critical section has access to these
resources. The following is the syntax
and an example of synchronized statement:
synchronized
(expression) statement
The expression is or returns an
object or an array
The statement is the critical
section of code
synchronized(myObject)
{ //
the critical code which updates myObject.
… // zero or more statements
}
Java has a number of classes such
as “java.lang.Thread”, “java.lang.ThreadGroup” and “java.lang.ThreadDeath”,
which provide support for multiple threads.
Compound Statement – Block
The
compound statement is also known as a “block”, where several statements are
grouped together within “{“ and “}” brackets.
A program or a method is considered a block.
Iteration Statement:
Iteration
Statements are loops. The loop body or
block is executed repeatedly as long as the loop expression remains true. Java has three types of loops as follows:
1.
for statement // it executes zero or more
for(expression1; expression2;
expression3)
statement;
2.
do statement // it executes one or more
expression1;
do
{
statement;
expression3;
}while(expression2);
3.
while statement //
it executes zero or more
expression1;
while(expression2)
{
statement;
expression3;
}
expression1 = initialization loop control variable
expression2 = testing for iteration
expression3 = updating loop control variable
The
execution of any these loops go through the following steps:
1.
Initialize loop control variable
2.
Test for iteration – if true go to step # 3 else exit the loop
3.
Execute the loop body (statement)
4.
Update the loop control variable and go to step # 2
Jump Statement:
Jump
statements transfer control flow unconditionally. Java has the following jump statements:
1.
Continue
The “continue” statement is only
used within a loop. It causes the
control flow to jump to the execution of the loop body step as mentioned
earlier. There should be a test before
executing the “continue” statement otherwise the loop will be an infinite
one. In the case of nested loops, it
continues with the inner most loop.
while(expression)
{
…
if(expression)
continue;
statement;
}
2.
Break
A “break” may appear in any loop
or a “switch” statement. It causes the
loop or the “switch” to terminate. In
the case of a nested loop, it breaks from the most inner loop. There should be a test before executing the
“break” statement otherwise the loop will run once skipping any statements pass
the “break”.
For(; ;)
{
…
if(expression)
break;
…
}
3.
Return
The “return” statement is equal
to the “break” statement with the fact that it returns to the caller of the
method, which the “return” statement is included in. If the method is the “main” method then,r it terminates the
program. There should be a test before
executing the “return” statement otherwise the method or the program will run
up to the “return” statement and then will be terminated.
do
{
…
if(expression)
return;
statement;
}while(expression);
4.
goto Statement
Java does not allow any GOTO
statement.
Example # 5 has code to illustrate the loops and jump
statements. It declares
“BreakContinueReturn” class that has a constructor and the
“ReadCahrFromKeyBoard()” method. This
method is a simple example of how to read a byte from the keyboard. It has extra code to skip the carriage
return. It has an “IOException”
exception, which handles the known error of getting a byte from the
keyboard. If the statement in the
“try” block fails, the control flow will go to the “catch” block and returns a
zero. The code in the constructor
declares three loops, “for”, “do while” and “while”. It prompts the user to enter a char, gets a byte from the
“ReadCahrFromKeyBoard()” method and casts it to a char. The “continue”, “break” and “return”
statements are used with each of the three loops to execute the user
wishes. The three loops are coded to
be infinite and only the “break” and “return” statements can terminate any of
these loops. The “BreakContinueReturn” class is instantiated in the static
“main” method using the “new” operator to create an “BreakContinueReturn” class
object.
Example # 5
/***************************************************************
** This Java program to illustrates BREAK, CONTINUE and RETURN
** Statements within the following loops: for, while and do while
***************************************************************/
import java.lang.*;
public class BreakContinueReturn
{
public
BreakContinueReturn()
{
int LoopCounter
= 0;
char Respondchar
= 'B';
System.out.println("\n*****************
For loop *************\n");
for( ; ; )
{
System.out.println("\nThis
an Infinite FOR Loop");
System.out.println("To
exit out this loop enter any of the following");
System.out.println("\"B\"
or \"b\" or any key to break");
System.out.println("\"C\"
or \"c\" to continue");
System.out.println("\"R\"
or \"r\" to end this program");
System.out.print("Enter
a Char then press ENTER ====> ");
Respondchar =
(char)ReadCahrFromKeyBoard();
if( ('B' ==
Respondchar) || ('b' == Respondchar))
break;
else
if( ('R' == Respondchar) || ('r' ==
Respondchar))
return;
else
continue;
}
System.out.println("\n*****************
While loop *************\n");
while(true)
{
System.out.println("\nThis
an Infinite WHILE Loop");
System.out.println("To
exit out this loop enter any of the following");
System.out.println("\"B\"
or \"b\" or any key to break");
System.out.println("\"C\"
or \"c\" to continue");
System.out.println("\"R\"
or \"r\" to end this program");
System.out.print("Enter
a Char then press ENTER ====> ");
Respondchar =
(char)ReadCahrFromKeyBoard();
if( ('B' ==
Respondchar) || ('b' == Respondchar))
break;
else
if( ('R' == Respondchar) || ('r' ==
Respondchar))
return;
else
continue;
}
System.out.println("\n*****************
Do While loop *************\n");
do
{
System.out.println("\nThis
an Infinite DO WHILE Loop");
System.out.println("To
exit out this loop enter any of the following");
System.out.println("\"B\"
or \"b\" or any key to break");
System.out.println("\"C\"
or \"c\" to continue");
System.out.println("\"R\"
or \"r\" to end this program");
System.out.print("Enter
a Char then press ENTER ====> ");
Respondchar =
(char)ReadCahrFromKeyBoard();
if( ('B' ==
Respondchar) || ('b' == Respondchar))
break;
else
if( ('R' == Respondchar) || ('r' ==
Respondchar))
return;
else
continue;
} while (true);
}
//****************************************************
public int
ReadCahrFromKeyBoard()
{
int InputByte;
int InputByte_2;
try
{
InputByte = System.in.read();
// skip carriage
return
if( ('\n' == InputByte)
||
('\r' == InputByte)
)
InputByte = System.in.read();
}
catch(IOException
MyIOException)
{
return (0);
}
// skip carriage return
InputByte_2 =
InputByte;
while( (InputByte_2 != '\n')
&& (InputByte_2 != '\r')
)
{
try
{
InputByte_2 =
System.in.read();
}
catch(IOException
MyIOException)
{
return (0);
}
}
return(InputByte);
}
//*******************************************************
public static void
main(String [] args)
{
BreakContinueReturn
MyBreakContinueReturn
= new BreakContinueReturn();
}
}
Output:
***************** For loop
*************
This an Infinite FOR Loop
To exit out this loop enter any of
the following
"B" or "b" or
any key to break
"C" or "c" to
continue
"R" or "r" to
end this program
Enter a Char then press ENTER
====> b
***************** While loop
*************
This an Infinite WHILE Loop
To exit out this loop enter any of
the following
"B" or "b" or
any key to break
"C" or "c" to
continue
"R" or "r" to
end this program
Enter a Char then press ENTER
====> B
***************** Do While loop
*************
This an Infinite DO WHILE Loop
To exit out this loop enter any of
the following
"B" or "b" or
any key to break
"C" or "c" to
continue
"R" or "r" to
end this program
Enter a Char then press ENTER
====> R
As a practice, the reader can create the same program, but
nest the loops within one another. For
example, the inner most loop would be the “for”, and most outer would be the
“do while”.
Comma and the “for” Loop:
Java
does not support the comma “,” operator except within the “for” loop
initialization and updating or increment sections. Java does no allow the comma operator in the testing section. Java does not allow variables declared
within the initialization section to have the same name as the variables
declared outside the “for” loop despite the fact that these “for” loop
variables have their scope to be the “for” loop block. Example # 6 code illustrates the comma
operator and “for” loop. The
initialization, and increment sections use the comma operator, while the
testing section does not allow it.
Example # 6
/*******************************************************
** This Java program to illustrates COMMA operator and FOR loop
********************************************************/
import java.lang.*;
public class CommaAndForLoop
{
public
CommaAndForLoop()
{
int LoopCounter_1,
LoopCounter_2,
LoopCounter_3;
Int Count = 0;
System.out.println("Loop
Counter \t\t Loop Counter Value\n");
for( //
initialization section
LoopCounter_1 =
0,
LoopCounter_2 =
0,
LoopCounter_3 = 0
// int
LoopCounter_4 = 0 is not allowed??
; // end of initialization section
// testing
section
(LoopCounter_1 <= 5)
&& (LoopCounter_2 <= 6)
&&
(LoopCounter_3 <= 7)
; // end of testing section
// incrementation
section
LoopCounter_1++,
LoopCounter_2++,
LoopCounter_3++
)
{
Count++;
System.out.println(Count
+ ") LoopCounter_1 \t\t" + LoopCounter_1);
System.out.println(Count
+ ") LoopCounter_2 \t\t" + LoopCounter_2);
System.out.println(Count
+ ") LoopCounter_3 \t\t" + LoopCounter_3 +
"\n");
}
}
//****************************************************
public static void
main(String [] args)
{
CommaAndForLoop
MyCommaAndForLoop = new CommaAndForLoop();
}
}
Output:
Loop Counter Loop Counter
Value
1) LoopCounter_1 0
1) LoopCounter_2 0
1) LoopCounter_3 0
2) LoopCounter_1 1
2) LoopCounter_2 1
2) LoopCounter_3 1
3) LoopCounter_1 2
3) LoopCounter_2 2
3) LoopCounter_3 2
4) LoopCounter_1 3
4) LoopCounter_2 3
4) LoopCounter_3 3
5) LoopCounter_1 4
5) LoopCounter_2 4
5) LoopCounter_3 4
6) LoopCounter_1 5
6) LoopCounter_2 5
6) LoopCounter_3 5
Constants:
A
constant is an identifier that has a value stored it in and this value cannot
be changes. Declaring constants in Java
is very simple. It is basically a
“final” variable. A constant variable
must be initialized with a value in its declaration.
int myInteger;
final int myConstant = 120;
public fnal int myPublicConstant =
myConstant + 10;
public static final
int myPublicStaticFinalConstant = 12;
The last three variables are constant, each variable must be
initialized with a value. The “static”
and “public” modifiers are the setting of the scope and accessibility, which we
will cover in the coming sections.
Several packages have constants that can be used within any Java
program. For example, The “java.awt.Color”
class has a number of constants as follows:
pubic static final Color
black;
pubic static final Color
blue;
pubic static final Color
cyan;
pubic static final Color
darkGray;
pubic static final Color
gray;
pubic static final Color
green;
pubic static final Color
lightGray;
pubic static final Color
magenta;
pubic static final Color
orange;
pubic static final Color
pink;
pubic static final Color
red;
pubic static final Color
white;
pubic static final Color
yellow;
A programmer can set a GUI component’s background color as
follows:
import java.awt.*;
setBackground(Color.blue);
We are using the Color class constant variable or member as
constant. Please note the “java.awt”
package must be imported to make the Color class and its constants visible to
the program.
“null” Value:
“null”
is a reserved keyword with a reserve value.
Its value means NO reference to object or an array of an object. “null” can not be casted to any primitive
type or tested to equal zero.
“true” and “false”:
“true”
and “false” are the only possible value a boolean variable can have. They are constant literal values similar to
an integer or a float literal.