Chapter 2 Java Fundamentals

Using Data Objectives:
1. Some JAVA rules
2. JAVA API - Application Programmer Interface.
3. The Eclipse IDE
4. Using print and println.
5. Variables and Literals
6. Boolean data type
7. The char data type
8. The Math class
9. The data type of a variable
10. Cast operators
11. Concatenation
12. Using the Scanner class for Keyboard Input.
13. Displaying data using the JOptionPane.
14. Using Confirm Dialog Boxes

1. Some JAVA rules
a. Java is case-sensitive language.
b. All java programs must be stored in a file with a name that ends with .java.
c. Comments are ignored by the compiler and begin with //.
d. A .java file may contain many classes, but may only have one public class, and it must have the same name as the file.
e. Every Java application program must have a method named main.
f. For every left brace, or opening brace, there must be a corresponding right brace, or closing brace.
g. Statements are terminated with semicolons. This does not include comments, class headers, method headers, or braces.

Java Special Punctuation Characters





Double Slash

Marks the beginning of a comment

( )

Opening and closing parentheses

Used in method header

{ }

Opening and closing braces

Encloses a group of statements, such as the content of a class or method

" "

Quotations marks

Encloses a string of characters, such as a message that is to be printed on the screen



Marks the end of a complete programming statement


Assignment operator

inttax=income*.03  - assigns the result of the equation to inttax



result = a==b.   - if a and b are equal return true and assigns it to result, if not return false

2. JAVA API - Application Programmer Interface. - Standard library of prewritten classes for performing specific operations.
Code Example:

//this is a simple Java program.  -the two forward slashes designate a comment which is a non-executable line.

public class simple - this line is known as a class header which marks the beginning of a class definition. There must be at least one class definition. public is Java key word, must be lower case and is known as an access specifier. public means open to the public.  class is a java key word, must be lower case, and indicates the beginning of a class. simple is the class  name which is made up by the programmer and can be lowercase, uppercase or a mixture of both. There can be multiple classes but only one public class. The name of the public class must be the same name as the file.

{ - left brace is associated with the beginning of the class definition - every opening brace must have a closing brace. What is contained between the opening brace and closing brace is the body of the class.

    public static void main(string[] args) - method header - every JAVA application must have a method name main.

{ - this opening brace code is for the main method.
system.out.println("Programming is great fun !");  this line displays a message on the screen which is referred to as a string literal. You will notice the ; at the end of the line which marks the end of a statement in Java. Comments, class headers and method headers, and brace characters do not have to end with a semicolon.

} - closing brace code for method
} - closing brace code for class.

3. We will be using eclipse IDE for this course:  click eclipse you will see:
Description: Eclipse opening menu

a. click the new button and select JAVA project  you will see:

Description: New Java Project
Description: Java project name dialog box.
b. Type in the project name of MyName and browse to your chip as the location and click finish.
c. Click the new button again and select class. You will see:
Description: class dialog box
d. Browse to where you saved the project and select MyName/src, in the name type MyName, and in the method click public static void main(String[]args) and click finish you will see:
Description: IDE interface screen

e. Type the following code in the code window:  You will see:

Description: Java code for MyName project

f. Click run on the menu.  You will see:
Description: Run option on menu
g. Since we only have one project at this time just click ok.  You will see in the console window:

Description: Console window with output of program

4. Using print and println.

a. System.out.println("Earl T. Wylie");
b. System is a class that is part of the Java API. It contains objects and methods.
c. Out is one of the objects in system. It has methods such as print and println.
d. Println output to the standard output device. After println display the message it advances the cursor to the beginning of the next line.
e. (   ) contains the text enclosed in quotes to be outputted to the standard output device. Also referred to as the argument.

When using the print instead of println each print sequence is placed on the same line. For example:

    system.out.print("My name is  ");
    system.out.print(" Earl T. Wylie");

will display as one line "My name is Earl T. Wylie"

If I use println instead for example

    system.out.println("My name is ");
    system.out.println("Earl T. Wylie");

will display on two lines:

    My name is
    Earl T. Wylie

If I want to separate line of text while using print I can use escape sequences which are preceded by a \.  For example:

    system.out.print("My address is:\n");    the backslash followed by the n says go to the next line
    system.out.print("\t386 Knoll Dr.\n\tFairfield, Ca\n\t94534-3120"); the \t says go to the next tab stop. It will display as four lines:

My address is
    386 Knoll Dr.
    Fairfield, CA

f. Escape sequences can be used with print and println.

Common escape Sequences

Escape Sequence




New line

Advances the cursor to the next line for subsequent printing


Horizontal tab

Causes the cursor to skip over to the next tab stop



Cause the cursor to backu0p or move left one position



Causes the cursor to go to the beginning of the current line, not the next line



Causes a backslash to be printed


Single quote

Cause a single quotation mark to be printed


double quote

Causes a double quotation mark to be printed.

In GUI environment

\t,\b, and \r

Do not work

5. Variables and Literals -Variables hold one value at a time. A variable is declared only once but may have new values assigned during program execution.
a. is a location in the computerís memory which is comprised of the name and data type and whose contents may or may not change during program execution.

int myAge;    declares a variable named myAge that is an integer: note the ; is required.

b. Literals are values that are written into the code of a program. If working with money literals you cannot embed currency symbol ($) or commas in the literal.
c. Declaring variables - variable names(identifiers)  
    1) must begin with letter, underscore or $.
    2) may use letters, digits, underscore or $ after 1st character
    3) lower case and uppercase do make a difference in the variable name
    4) there can be no spaces
    5) do not use the $ in a variable name
d. Declaring Constants - is a variable whose value is read only and cannot be changed during the program execution. It is preceded by the final key word:

final double INTEREST_RATE=0.069   Constant identifier (name) are done in CAPS.

e. Data types of numeric data

Primitive data types

Data type




1 byte

Integer -128 to 127


2 bytes

integer -32,768 to 32,767


4 bytes

integer -2,147,483,648 to 2,147,483,647


8 bytes

integer -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807


4 bytes

floating point +-3.4 X10-38 to +3.4X10+38      7 digits of accuracy single-precision


8 bytes

floating point +-1.7X10 -308 to 1.7 X10  308              15 digits of accuracy. double-precision



a single character



true or false

6. Boolean data type - can only true or false - and can only used with Boolean variables.
  Boolean bool;
  bool =true:
† boolean isSixBigger =(6>5);
† //value stored in isSixBigger is true.
† boolean isSevenSmallerorEqual =(7<=4);
† //value stored in isSevenSmallerorEqual

7. char data type - can hold one character at a time.
char letter:
letter ='W';   note- when assigning a char to the char data type in must be enclosed in single quote mark.
JAVA uses Unicode - characters are represented by number when stored. For example A is stored as 65.
Char can be any letter - upper or lower case, punctuation mark or digit. Escape sequences can also be stored in a char

char aNewLine='\n';
char aTabchar='\t';

Arithmetic operators








totalcost= price + units;








tax=totalcost * taxrate;




averageage=totalage/number;  if both operands are integers than inter division will be performed.




remainder=number % 2;

Note:  + used in a different context is used for string concatenation.  Example:

system.out.println("The value is " + number):

The value is 5

Relational Operators

An expression that contains a relational operator has a Boolean value.

Less Than


Less than or equal to

Greater than


Greater than or equal to


Equal to


not equal to

Logical Operators       







Assignment operators




combined addition/assignment


combined subtraction/assignment


combined multiplication/assignment


combined division/assignment


combined modulus/assignment

8. The Math class
a. Math.pow method is used for raising a number to a power.   Example: result=Math.pow(4.0, 2.0); Two arguments, raises the 1st argument to the power of the second)   result=4 to the power of two.
b. Math.sqrt method - accepts a double value as its argument and returns the square root of the value.  Example: result=Math.sqrt(16.0); or
c. Combined Assignment Operators


Example of Usage

Equivalent To



x=x+ 5;













9. The data type of a variable determines what value can be put into the variable. Data type ranking.
a. double
b. float
c. long
d. int
e. short
f. byte
g. Widening conversion converts lower rank into upper rank.  Java automatically does this.
h. Narrowing conversion converts higher rank into lower rank.  Java does not automatically do this.

10. Cast operators - lets you manually convert a value even if it is narrowing conversion.

Examples Using Cast Operator


The cast operator enclosed in () converts whatever x is into a short integer and assigns it to y.


Turn 3.7 into a long integer truncating off the mantissa assigning 3 to z


Turns 72.567 into an integer truncating off the mantissa assigning 72 to a


Turns x into a float and assigns the value to h


Turns w into a byte and assigns the value to e


11. Concatenation is combining a string in Java. When a numeric variable is concatenated to a string using the plus sign (+), the entire expression becomes a string. For Example:

public class numbersPrintln
     public static void main(string[] args)
     int billingDate=5:
     system.out.print("Bills are sent on day ");
     system.out.pring\tlin(" of the month");
     system.out.println("Next bill: October " + billingDate);

Bills are sent on day 5 of the month
Next bill: October 5

12. Using the Scanner class for Keyboard Input.

import java.util.scanner:
public class GetUserInfo
       public static void main(String[] args)
          string name;
          int age;
          Scanner inputDevice= new Scanner(;  declares object type scanner named inputDevice and creates a scanner object that is connected to the default input device.
          System.out.print("Please enter your name>>  ");
          System.out.print("Please enter your age >>  ");
          System.out.println("your name is  " + name + " and your are " + age + " years old.");

Do not put the input of a string after the input of a number. If you do then put inputDevice.nextLine(); to clear the keyboard buffer.




Retrieves input as a double


Retreives input as in int


Retrieves the next line of data and returns it as a string-can be used to retrieve a char along with charAt()


Retrieves the next complete toke as a string


retrieves the input as a byte


retrieves input as float


retrieve input a long


retrieves input as short

13.1 Displaying data using the JOptionPane

import javax.swing.JOptionPane;
public class NumbersDialog
    public static void main(String[] args)
        int creditDays=30;
       JOptionPane.showMessageDialog(null, "" + creditDays);
       JOptionPane.showMessageDialog(null, "Every bill is due in " + creditDays + " days");

13.2  Input and output data using JOptionPane


import javax.swing.JOptionPane;
public class guiinput2 {
†††† public static void main(String[] args) {
†††† String result;
†††† result=JOptionPane.showInputDialog(null, "What is your name?");
†††† JOptionPane.showMessageDialog(null, "Hello, " + result + "!");
†††† }

a. Run the program you will see:

Description: JOptionPane show message

b. Enter your name and click ok.  You will see:
Description: Outp of message

c. An additional argument describing the type of dialog box can be added:

d. The showInputDialog() returns a string.  If you need it to be a number you must use parse.
For Example:

import javax.swing.JOptionPane;
public class SalaryDialog {
public static void main(String[] args)
†††† String wageString, dependentsString;
†††† double wage, weeklyPay;
†††† int dependents;
†††† final double HOURS_IN_WEEK=37.5;
†††† wageString=JOptionPane.showInputDialog(null,"Enter employes hourly wage",
†††† "Salary dialog 1",JOptionPane.INFORMATION_MESSAGE);
†††† weeklyPay=Double.parseDouble(wageString)*HOURS_IN_WEEK;       This line converts the string wageString into double weeklyPay
†††† dependentsString=JOptionPane.showInputDialog(null,"How many dependents?",
†††† "Salary dialog 2",JOptionPane.QUESTION_MESSAGE);
†††† dependents=Integer.parseInt(dependentsString);      This line converts the string dependentsString into the integer dependents
†††† JOptionPane.showMessageDialog(null,"Weekly salary is $" +
†††† weeklyPay + "\nDeductions will be made for " +
†††† dependents + " dependents");
†††† }

Run the program, you will see:
Description: salary dialog box 1

    1. Click Ok you will see:
Description: dependents dialog box

    2. Enter 2, click ok  you will see:
Description: ouy puy of program

14. Using Confirm dialog Boxes - displays the options yes, no, and cancel and are created using the showConfirmDialog()_method. In the JOptionPane class and returns an integer value. 

a. For Example:

import javax.swing.JOptionPane;
public class confirmDialogBox
†††† public static void main(String[] args)
†††† {
††††††††† // confirm dialog box code
††††††††† int selection;
††††††††† boolean isYes;
††††††††† selection=JOptionPane.showConfirmDialog(null, "Do you want to upgrade to super size?");
††††††††† isYes=(selection==JOptionPane.YES_OPTION);
††††††††† JOptionPane.showMessageDialog(null,"You responded " + isYes);
†††† }

a. run the program you will see:
Description: Confirm Dialog box

b. Click one of the options  You will see:
Description: confirm option yes

c. The showConfirmDialog can have five arguments.
    1. The parent component which can be null.
    2. The prompt message
    3. The title to be displayed in the title bar
    4. An integer that indicates which option button will be shown. YES_NO_CANCEL_Option or YES_NO_OPTION
For example:

import javax.swing.JOptionPane;
public class doomsday
†††† /**
†††† * @param args
†††† */
†††† public static void main(String[] args)
†††† {
††††††††† // doomsday
††††††††† JOptionPane.showConfirmDialog(null,"You are about to destroy the planet earth. Continue?",
†††††††† †"Input error, input error", JOptionPane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE);
†††† }

You will see:
Description: error option dialog



Typical use in Java

Alternate names



Follows method names as in println()

Parentheses can be called round brackets, but such usage is unusual.



A pair surrounds a class body, a method, and a block of code;  and also used for a list of array values.

Curly braces might also be called curly brackets


Square brackets

A pair signifies an array;

Square brackets might be called box brackets or square braces


Angle brackets

Surrounds HTML tags. In Java, a pair also is used with generic arguments in parameterized classes.

When angle brackets appear with nothing between them they are called a chevron.