Sie sind auf Seite 1von 27

History

 In the early 1990's, putting intelligence into home appliances was thought to be the next "hot"
technology.
 Examples of intelligent home appliances:
o Coffee pots and lights that can be controlled by a computer's programs.
o Televisions that can be controlled by an interactive television device's programs.
 Anticipating a strong market for such things, Sun Microsystems in 1991 funded a research project
(code named Green) whose goal was to develop software for intelligent home appliances.
 An intelligent home appliance's intelligence comes from its embedded processor chips and the
software that runs on the processor chips.
 Appliance processor chips change often because engineers continually find ways to make them
smaller, less expensive, and more powerful.
 To handle the frequent turnover of new chips, appliance software must be extremely portable.
 Originally, Sun planned to use C++ for its home appliance software, but they soon realized that
C++ was less than ideal because it wasn't portable enough and it relied too heavily on hard-to-
maintain things called pointers.
 Thus, rather than write C++ software and fight C++'s inherent deficiencies, Sun decided to
develop a whole new programming language to handle its home appliance software needs.
 Their new language was originally named Oak (for the tree that was outside project leader James
Gosling's window), but it was soon changed to Java.
 When the home appliance software work dried up, Java almost died before being released.
 Fortunately for Java, the World Wide Web exploded in popularity and Sun realized it could
capitalize on that.
 History of Java
 Web pages have to be very portable because they can be downloaded onto any type of
computer.
 What's the standard language used for Web pages?
 Java programs are very portable and they're better than HTML in terms of providing user
interaction capabilities.
 Java programs that are embedded in Web pages are called
applets.
 Although applets still play a significant role in Java's current
success, some of the other types of Java programs have
surpassed applets in terms of popularity.
 In this course, we cover Standard Edition (SE) Java
applications. They are Java programs that run on a standard
computer – a desktop or a laptop, without the need of the
Internet.
James Gosling, architect and
designer of the compiler for the Java
technology

1|Page
Getting Started with NetBeans
Assume that you have successfully installed NetBeans on your machine. Start NetBeans from Windows, Linux, Mac
OS X, or Solaris. The NetBeans main window appears, as shown in Figure 1.

Figure 1
The NetBeans main window is the command center for the IDE. The NetBeans main window contains menus,
toolbars, project pane, files pane, runtime pane, navigator pane, and other panes.

1.1 The Main Menu

The main menu is similar to that of other Windows applications and provides most of the commands you need to
use NetBeans, including those for creating, editing, compiling, running, and debugging programs. The menu items
are enabled and disabled in response to the current context.

1.2 The Toolbar

The toolbar provides buttons for several frequently used commands on the menu bar. The toolbars are enabled
and disabled in response to the current context. Clicking a toolbar is faster than using the menu bar. For many
commands, you also can use function keys or keyboard shortcuts. For example, you can save a file in three ways:

 Select File, Save from the menu bar.


 Click the "save" toolbar button ( ).
 Use the keyboard shortcut Ctrl+S.

TIP: You can display a label known as ToolTip for a toolbar button by pointing the mouse to the button without
clicking.

1.3 Workspaces

A workspace is a collection of windows that are pertinent to performing certain types of operations, such as
editing, execution, output, or debugging. The workspace windows can be displayed from the Window menu.

2|Page
2. Creating a Project

A project contains information about programs and their dependent files, and it also stores and maintains the
properties of the IDE. To create and run a program, you have to first create a project.

Here are the steps to create a demo project:

1. Choose File, New Project to display the New Project dialog box, as shown in Figure 2.
2. Select General in the Categories section and Java Application in the Projects section and click Next to
3. display the New Java Application dialog box, as shown in Figure 3.
4. Type demo in the Project Name field and c:\michael in Project Location field.
5. (Optional) You can create classes after a project iscreated. Optionally you may also create the first class
when creating a new project. To do so, check the Create Main Class box and type a class name, say First,
as the Main Class name.
6. Click Finish to create the project. The new project is displayed, as shown in Figure 4.

Figure 2
The New Project dialog box enables you to specify a project type.

Figure 3
The New Java Application prompts you to enter a project name, location, and a main class name.

3|Page
Figure 4
A new demo project is created.

3. Creating a Class
You can create any number of classes in a project. Here are the steps to create Welcome.java in Listing 1.1 from
Chapter 1 of the text in the demo project.

1. Right-click the top demo node in the project pane to display a context menu, as shown in Figure 5. Choose
New, Java Class to display the New Java Class dialog box, as shown in Figure 6.
2. Type Welcome in the Class Name field and select the Source Packages in the Location field. Leave the
Package field blank. This will create a class in the default package. (Note that it is not recommended to use
the default package, but it is fine to use the default package to match the code in the book. Using default
package is appropriate for new Java students. Section 10, “Using Packages,” will introduce how to create a
class in a non-default package.)
3. Click Finish to create the Welcome class, as shown in Figure 7. The source code file Welcome.java is placed
under the <default package> node, because you did not specify a package name for the class in Figure 6.
4. Modify the code in the Welcome class to match Listing 1.1, as shown in Figure 8.

4|Page
Figure 5
You can create a new class in a project.

Figure 6
The New Java Class dialog box enables you to specify a class name, location, and package name to create a new
class.

5|Page
Figure 7
A new Java class is created in the project.

Figure 8
The source code for Welcome.java is entered.

TIP You can show line numbers in the Source Editor by choosing View, Show Line
Numbers from the main menu.

NOTE The source file Welcome.java is stored in c:\michael\demo\src.

4. Compiling a Class
To compile Welcome.java, right-click Welcome.java to display a context menu and choose Compile File, or simply
press F9, as shown in Figure 9.

The compilation status is displayed in the Output pane, as shown in Figure 10. If there are no syntax errors, the
compiler generates a file named Welcome.class, which is stored in c:\michael\demo\build\classes.

6|Page
Figure 9
The Compile File command in the context menu compiles a source file.

Figure 10
The compilation status is shown in the output pane.

NOTE: When you compile the file, it will be automatically saved.

NOTE: The icon for Java source code is . A Java source code may have an additional icon ,
which indicates that the file is not compiled. If the class has a main method, the
icon is after the class is compiled.

TIP: You can get descriptions of the node icons from NetBeans Help. Choose Help, Help
Contents from the main window, and type Node Icons under the Search tab to
display the descriptions for the icons, as shown in Figure 11.

5. Running a Java Application


To run Welcome.java, right-click Welcome.java to display a context menu and choose Run File, or simply
press Shift + F6, as shown in Figure 12. The output is displayed in the Output pane, as shown in Figure 13.

7|Page
Figure 12
The Run File command in the context menu runs a Java program.

Figure 13
The execution result is shown in the Output pane.

8|Page
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.

Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.

Class Names - For all class names the first letter should be in Upper Case. If several words are used
to form a name of the class, each inner word's first letter should be in Upper Case.
Example class MyFirstJavaClass

Method Names - All method names should start with a Lower Case letter. If several words are used
to form the name of the method, then each inner word's first letter should be in Upper Case.
Example public void myMethodName()

Program File Name - Name of the program file should exactly match the class name. When saving
the file, you should save it using the class name (Remember Java is case sensitive) and append
'.java' to the end of the name (if the file name and the class name do not match your program will
not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'

public static void main(String args[]) - Java program processing starts from the main() method
which is a mandatory part of every Java program..

Java Comments
Comments are notes written to a code for documentation purposes. Those text are not part of the
program and does not affect the flow of the program. Java supports three types of comments: C++-
style single line comments, C-style multiline comments and special javadoc comments.

C++-Style Comments
C++ Style comments starts with //. All the text after // are treated as comments. For
example,

// This is a C++ style or single line comments

C-Style Comments
C-style comments or also called multiline comments starts with a /* and ends with a */. All text in
between the two delimeters are treated as comments. Unlike C++ style comments, it can span
multiple lines. For example,

/* this is an exmaple of a
C style or multiline comments */

Special Javadoc Comments


Special Javadoc comments are used for generating an HTML documentation for your Java programs.
You can create javadoc comments by starting the line with /** and ending it with */. Like C-style
comments, it can also span lines. It can also contain certain tags to add more information to your
comments. For example,
/**
This is an example of special java doc comments used for \n
generating an html documentation. It uses tags like:
@author Florence Balagtas
@version 1.2
*/

9|Page
Java Statements and blocks
A statement is one or more lines of code terminated by a semicolon. An example of a single statement
is,

System.out.println(“Hello world”);

A block is one or more statements bounded by an opening and closing curly braces that groups the
statements as one unit. Block statements can be nested indefinitely. Any amount of white space is
allowed. An example of a block is,

public static void main( String[] args ){


System.out.println("Hello");
System.out.println("world");
}

Java Identifiers
Identifiers are tokens that represent names of variables, methods, classes, etc. Examples of
identifiers are: Hello, main, System, out.

Java identifiers are case-sensitive. This means that the identifier: Hello is not the same as hello.
Identifiers must begin with either a letter, an underscore “_”, or a dollar sign “$”. Letters may be
lower or upper case. Subsequent characters may use numbers 0 to 9.

Identifiers cannot use Java keywords like class, public, void, etc.

Coding Guidelines:
1. For names of classes, capitalize the first letter of the class name. For names of methods and variables, the
first letter of the word should start with a small letter. For example:
ThisIsAnExampleOfClassName
thisIsAnExampleOfMethodName
2. In case of multi-word identifiers, use capital letters to indicate the start of the word
except the first word. For example, charArray, fileNumber, ClassName.
3. Avoid using underscores at the start of the identifier such as _read or _write.

All Java components require names. Names used for classes, variables and methods are called
identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 After the first character identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value
 Examples of illegal identifiers: 123abc, -salary

10 | P a g e
Java Keywords
Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot use
keywords as names for your variables, classes, methods …etc. Here is a list of the Java Keywords.

We will try to discuss all the meanings of these keywords and how they are used in our Java
programs as we go along the way.
Note: true, false, and null are not keywords but they are reserved words, so you cannot use them as
names in your programs either.

BASIC DATA TYPES


Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store integers, decimals, or
characters in these variables.

There are two data types available in Java:


 Primitive Data Types
 Reference/Object Data Types

Primitive Data Types:


There are eight primitive data types supported by Java. Primitive data types are
predefined by the language and named by a keyword. Let us now look into detail about
the eight primitive data type.

byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an int.
 Example: byte a = 100 , byte b = -50

11 | P a g e
short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int.
 Default value is 0.
 Example: short s = 10000, short r = -20000

int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless there is a
concern about memory.
 The default value is 0.
 Example: int a = 100000, int b = -200000

long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example: long a = 100000L, int b = -200000L

float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example: float f1 = 234.5f

double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values, generally the
default choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example: double d1 = 123.4

boolean:
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example: boolean one = true

char:
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letterA ='A'

12 | P a g e
Reference Data Types:
Reference variables are created using defined constructors of the classes. They are used to access
objects. These variables are declared to be of a specific type that cannot be changed.

For example, Employee, Puppy etc.

Class objects, and various type of array variables come under reference data type.

Default value of any reference variable is null.

A reference variable can be used to refer to any object of the declared type or any compatible type.

Example: Animal animal = new Animal("giraffe");

Variables
A variable is an item of data used to store state of objects. A variable has a data type and a name.
The data type indicates the type of value that the variable can hold. The variable name must follow
rules for identifiers.

Declaring and Initializing Variables


To declare a variable is as follows,
<data type> <name> [=initial value];

Note: Values enclosed in <> are required values, while those values enclosed in [] are optional.

Here is a sample program that declares and initializes some variables,

public class VariableSamples


{
public static void main( String[] args ){
//declare a data type with variable name
// result and boolean data type
boolean result;
//declare a data type with variable name
// option and char data type
char option;
option = 'C'; //assign 'C' to option
//declare a data type with variable name
//grade, double data type and initialized
//to 0.0
double grade = 0.0;
}
}

Coding Guidelines:
1. It always good to initialize your variables as you declare them.
2. Use descriptive names for your variables. Like for example, if you want to have a variable that contains a grade
for a student, name it as, grade and not just some random letters you choose.
3. Declare one variable per line of code. For example, the variable declarations,
double exam=0;
double quiz=10;
double grade = 0;
is preferred over the declaration,
double exam=0, quiz=10, grade=0;

13 | P a g e
Outputting Variable Data
In order to output the value of a certain variable, we can use the following commands,
System.out.println()
System.out.print()

Here's a sample program,


public class OutputVariable
{
public static void main( String[] args ){
int value = 10;
char x;
x = ‘A’;
System.out.println( value );
System.out.println( “The value of x=“ + x );
}
}

The program will output the following text on screen,


10
The value of x=A

System.out.println() vs. System.out.print()


What is the difference between the commands System.out.println() and System.out.print()? The first
one appends a newline at the end of the data to output, while the latter doesn't. Consider the
statements,

System.out.print("Hello ");
System.out.print("world!");

These statements will output the following on the screen,


Hello world!

Now consider the following statements,


System.out.println("Hello ");
System.out.println("world!");

These statements will output the following on the screen,


Hello
world!
Operators
In Java, there are different types of operators. There are arithmetic operators, relational
operators, logical operators and conditional operators. These operators follow a certain
kind of precedence so that the compiler will know which operator to evaluate first in case
multiple operators are used in one statement.

The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:

14 | P a g e
The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20, then:

15 | P a g e
The Logical Operators:
The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:

The Assignment Operators:


There are following assignment operators supported by Java language:

Operator precedence defines the compiler’s order of evaluation of operators so as to


come up with an unambiguous result.

Given a complicated expression,


6%2*5+4/2+88-10
we can re-write the expression and place some parenthesis base on operator precedence,
((6%2)*5)+(4/2)+88-10;
Coding Guidelines
16
To|avoid
P a g confusion
e in evaluating mathematical operations, keep your expressions simple and use parenthesis.
Decision Control Structures
Decision control structures are Java statements that allows us to select and execute
specific blocks of code while skipping other sections.

There are two types of decision control statements in Java. They are:
 if statements
 switch statements

The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.

Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.

Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}

This would produce the following result:


This is if statement

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");

17 | P a g e
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
This is else statement

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement. When using if , else if , else statements there
are few points to keep in mind. An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else. Once an else if succeeds,
none of the remaining else if's or else's will be tested.

Syntax:
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
Value of X is 30

Nested if...else Statement:


It is always legal to nest if-else statements which means you can use one if or else if statement
inside another if or else if statement.

Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true

18 | P a g e
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
This would produce the following result:
X = 30 and Y = 10

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.

Syntax:
The syntax of enhanced for loop is:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:

The variable used in a switch statement can only be a byte, short, int, or char. You can have any
number of case statements within a switch. Each case is followed by the value to be compared to
and a colon. The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal. When the variable being switched on is equal to a case, the
statements following that case will execute until a break statement is reached. When a break
statement is reached, the switch terminates, and the flow of control jumps to the next line following
the switch statement. Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached. A switch statement can have an
optional default case, which must appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed in the default case.

Example:
public class Test {
public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)

19 | P a g e
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Compile and run above program using various command line arguments. This would produce the
following result:

Well done
Your grade is a C

JAVA LOOPS - FOR, WHILE AND DO...WHILE


There may be a situation when we need to execute a block of code several number of times, and is
often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the
following
three loops:
while Loop
do...while Loop
for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested
and the result is false, the loop body will be skipped and the first statement after the while loop will
be executed.

Example:
public class Test {
public static void main(String args[]) {

20 | P a g e
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.

Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17

21 | P a g e
value of x : 18
value of x : 19

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times. A for loop is useful when you know how many times a task is to
be repeated.
Syntax:
The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:


 The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
 Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute and flow of control jumps to the next
statement past the for loop.
 After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank, as long as a semicolon appears after the Boolean expression.
 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.

Example:

public class Test {


public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Enhanced for loop in Java:


As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:

22 | P a g e
for(declaration : expression)
{
//Statements
}

Declaration: The newly declared block variable, which is of a type compatible with the elements of
the array you are accessing. The variable will be available within the for block and its value would be
the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be an array
variable or method call that returns an array.

Example:

public class Test {


public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}

This would produce the following result:


10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any loop
or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of
code after the block.

Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:

23 | P a g e
10
20

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump
to the update statement.
In a while loop or do/while loop, flow of control immediately jumps to the
Boolean expression.

Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:
10
20
40
50

24 | P a g e
Getting Input from the Keyboard
Now that we've studied some basic concepts in Java and we've written some simple programs, let's
make our programs more interactive by getting some input from the user. In this section, we'll be
discussing two methods of getting input, the first one is through the use of the BufferedReader class
and the other one involves a graphical user interface by using JOptionPane.

Using BufferedReader to get input


In this section, we will use the BufferedReader class found in the java.io package in order to get
input from the keyboard.

Here are the steps to get input from the keyboard:


1. Add this at the top of your code:
import java.io.*;
2. Add this statement:
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
3. Declare a temporary String variable to get the input, and invoke the readLine() method to get
input from the keyboard. You have to type it inside a try-catch block.
try{
String temp = dataIn.readLine();
}
catch( IOException e ){
System.out.println(“Error in getting input”);
}

Here is the complete source code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
BufferedReader dataIn = new BufferedReader(new
InputStreamReader( System.in) );
String name = "";
System.out.print("Please Enter Your Name:");
try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
System.out.println("Hello " + name +"!");
}
}

Now let's try to explain each line of code:


The statements,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

indicate that we want to use the classes BufferedReader, InputStreamReader and IOException which
is inside the java.io package. The Java Application Programming Interface (API) contains hundreds of
predefined classes that you can use in your programs. These classes are organized into what we call
25 | P a g e
packages.
Packages contain classes that have related purpose. Just like in our example, the java.io package
contains classes that allow programs to input and output data. The statements can also be rewritten
as,
import java.io.*;
which will load all the classes found in the package, and then we can use those classes inside our
program.

The next two statements,

public class GetInputFromKeyboard


{
public static void main( String[] args ){

were already discussed in the previous lesson. This means we declare a class named
GetInputFromKeyboard and we declare the main method.

In the statement,
BufferedReader dataIn = new BufferedReader(new
InputStreamReader( System.in) );

we are declaring a variable named dataIn with the class type BufferedReader. Don't worry about
what the syntax means for now. We will cover more about this later in the course.

Now, we are declaring a String variable with the identifier name,


String name = "";
This is where we will store the input of the user. The variable name is initialized to an empty String
"". It is always good to initialize your variables as you declare them.

The next line just outputs a String on the screen asking for the user's name.
System.out.print("Please Enter Your Name:");

Now, the following block defines a try-catch block,

try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}

This assures that the possible exceptions that could occur in the statement
name = dataIn.readLine();

will be catched. We will cover more about exception handling in the latter part of this course, but for
now, just take note that you need to add this code in order to use the readLine() method of
BufferedReader to get input from the user.

Now going back to the statement,


name = dataIn.readLine();
the method call, dataIn.readLine(), gets input from the user and will return a String value. This value
will then be saved to our name variable, which we will use in our final statement to greet the user,
System.out.println("Hello " + name + "!");

26 | P a g e
Using JOptionPane to get input
Another way to get input from the user is by using the JOptionPane class which is found in the
javax.swing package. JOptionPane makes it easy to pop up a standard dialog box that prompts users
for a value or informs them of something.

Given the following code,

import javax.swing.JOptionPane;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
String name = "";
name = JoptionPane.showInputDialog("Please enter your
name");
String msg = "Hello " + name + "!";
JOptionPane.showMessageDialog(null, msg);
}
}

This will output,

The first statement,


import javax.swing.JOptionPane;

indicates that we want to import the class JOptionPane from the javax.swing package.
We can also write this as,
import javax.swing.*;

The statement,
name = JOptionPane.showInputDialog("Please enter your name");

creates a JOptionPane input dialog, which will display a dialog with a message, a textfield and an OK
button as shown in the figure. This returns a String which we will save in the name variable.

Now we create the welcome message, which we will store in the msg variable,
String msg = "Hello " + name + "!";
The next line displays a dialog which contains a message and an OK button.
JOptionPane.showMessageDialog(null, msg);

27 | P a g e

Das könnte Ihnen auch gefallen