Beruflich Dokumente
Kultur Dokumente
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.
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.
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:
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.
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.
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: 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.
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,
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 */
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,
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.
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.
Class objects, and various type of array variables come under reference data type.
A reference variable can be used to refer to any object of the declared type or any compatible type.
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.
Note: Values enclosed in <> are required values, while those values enclosed in [] are optional.
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()
System.out.print("Hello ");
System.out.print("world!");
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:
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");
}
}
}
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
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
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
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 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
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
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
Example:
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:
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");
}
}
}
23 | P a g e
10
20
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
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.
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 +"!");
}
}
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.
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.
The next line just outputs a String on the screen asking for the user's name.
System.out.print("Please Enter Your Name:");
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.
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.
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);
}
}
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