Introduction to Java

concepcionsockSoftware and s/w Development

Aug 15, 2012 (4 years and 10 months ago)

357 views

Introduction to Java

ISYS 350

A Brief History


Sun Microsystems released this language in 1996


Versions: 1.0


1.6


Java Development Kit, JDK


Standard Edition, SE and Enterprise Edition, EE


With versions 1.2 through 1.5, SE and EE were known
as Java 2 Platform, J2SE and J2EE.


Latest version is called Java SE 6 and Java EE 6


Syntax is similar to C++


Both languages are case
-
sensitive


Web
-
based applications

Portability

Java: Write Once Run Anywhere

Java Source Code

Java Byte Code

(Intermediate Code)

Java Byte Code

Java Virtual Machine

(JVM)

Executable Code

How Java compiles and interprets code

source code
(*.java files)
bytecodes
(*.class files)
Text editor
Java compiler
Java interpreter
Java virtual machine (JVM)
Operating system
Download Java SE Development Kit,
SDK


http://java.sun.com/javase/downloads/index.j
sp


JDK 6 Update 14 with JavaFX SDK


Select or Create a folder for downloaded file:


For example. C:
\
JavaDownload


Directories of the JDK


Typical JDK directory:


C:
\
Program Files
\
Java
\
jdk1.6.0_14


Sub Directories:


bin: Java development tools including the Java
compiler (javac)


Jre: Java Runtime Environment needed to run
compiled Java programs


lib: Additional libraries used by the development tools


Note:
http://java.sun.com/javase/6/docs/technotes/tools/w
indows/jdkfiles.html


Testing Java Installation



public class TestApp

{


public static void main(String[] args)


{



System.out.println("Java has been successfully installed. ");


}

}

Demo: Use NotePad to create a Java program:

Save this program

1.
The name of this program must mach the name
of the public class.

2.

It must have an extension “java” in lower case.

3.

In the Save As box, enclose the name in
quotation marks like this:

“TestApp.java”


Start the Command Prompt and Change Path


Start the command prompt:


Start/Run/


Then, run this program:


C:
\
WINDOWS
\
system32
\
cmd.exe


Set the path to the bin folder in order to run java compiler:


Right click
MyComputer

icon and choose Properties


Select the Advanced tab and click on the Environment Variables
button


Use the
Enviroment

Variables dialog box to edit the variable named
Path


Type a semicolon and the path C:
\
Program Files
\
Java
\
jdk1.6.0_14
\
bin
to the far right of the list of paths.


From the Command prompt, change the directory to the program’s
folder:


C: > CD C:
\
Java
\
Examples

Run a Java Program from Command Prompt


Compile the program: javac TestApp.java


If no syntax error, a class with the same name will be
created in the same folder


Run the program: java TestApp



Slide
12

C
ommon compile
-
time error message

C:
\
java
\
examples
\
ch01
\
TestApp.java:1: class testapp is
public, should be declared in a file named testapp.java


public class testapp


^

What it means

The *.java file name doesn’t match the name of the public
class. You
must save the file with the same name as the name that’s coded after
the words “public class”. In addition, you must add the java extension
to the file name.

Solution

Edit the class name so it matches the file name (including
capitalization), or

change the file name so it matches the class name.
Then, compile again.


Slide
13

A common runtime error message

Exception in thread "main" java.lang.NoSuchMethodError: main

What it means

The class doesn’t contain a main method.

Solution

Run a different class that does have a main method, or enter a main
method for the current class.

Integrated Development
Environment, IDE


An
integrated development environment

(IDE)
also known as
integrated design environment

is a
software application that provides
comprehensive facilities to computer
programmers for software development. An IDE
normally consists of:


a source code editor


a compiler and/or an interpreter


build automation tools


a debugger


Examples: NetBeans, Eclipse



NetBeans IDE


A free, open
-
source Integrated Development
Environment for software developers. You get
all the tools you need to create professional
desktop, enterprise, web, and mobile
applications.


Support many languages:


Java, PHP, C++, Ruby


Support many platforms:


Windows, Linux, Mac OS X and Solaris


Download NetBeans IDE


Before you install the IDE, the Java SE
Development Kit must be installed on your
system.


Website:
http://www.netbeans.org/downloads/index.html


Choose All that includes Java, PHP with bundled
servers.


NetBeans IDE 6.7.1 Installation Instructions


http://www.netbeans.org/community/releases/67/ins
tall.html


NetBeans’ Tutorials


From NetBeans home page:



http://www.netbeans.org/


click Tutorials link


Quick Start Guide

Using
NetBeans

to Create the
TestApp

Java Program


1. Start NetBeans


2. Click File/New Project and select Java


3. Name project and specify project folder


4. Copy and paste the TestApp program’s
statements to the generated Main method.


5. Click Run/Run Main project to test.

Class and Method


Class: When develop a Java application, you code one
or more classes for it.


Access modifier: Control the scope of a class


public: Other classes can access it.


p
rivate: Used only in a project.


Method: A class may contain one or more methods
which are pieces of code that perform tasks.


The “main” method:


A special method that is automatically executed when the
class that holds it is run. It is always declared to be public.

The Syntax for Declaring a Class

public!|or private class ClassName

{


statements

}



public class TestApp

{


public static void main(String[] args)


{



System.out.println("Java has been successfully installed. ");


}

}

main Method Syntax



public static void main(String[] args)


public: Other classes can access it.


static: Other classes can call this method directly
without first creating an object.


void: The method won’t return any values.


The code in the parenthesis lists the arguments
that the method uses. Every main method has an
argument named args which is defined as an array
of strings.

Package and Project


Package: Related classes are organized into
package.


A project may contain one or more packages.


Java Language Tutorials


http://java.sun.com/docs/books/tutorial/java/
TOC.html


Questions and Exercises section at the end of
each topic.


Murach’s

Java SE 6, C1

© 2007, Mike Murach & Associates, Inc.


Slide
24

Java API page:

http://java.sun.com/javase/7/docs/api/

Java Application Program Interface, API

API

is an interface that defines the ways by
which an application program may request
services from libraries.


API
, provides all the classes that are
included as part of the JDK.

You can view the API documentation from
the Java web site, or you can download and
install it on your system.

Basic Coding Skills


Statements: Direct the operation of the program.


Can continue from one line to next line


Spaces


Block of code: { }


Indentation for easy reading


Comments:


Single
-
line comment: //comment


Block comment:



/* comment



comment */


Slide
26

Valid identifiers

InvoiceApp

$orderTotal

i

Invoice

_orderTotal

x

InvoiceApp2

input_string

TITLE

subtotal

_get_total

MONTHS_PER_YEAR

discountPercent

$_64_Valid

The rules for naming an identifier



An
identifier

is any name that you create in a Java program. T
hese
can be the names of classes, methods, variables, and so on.



Start each identifier with a letter, underscore, or dollar sign. Use
letters, dollar signs, underscores, or digits for subsequent
characters.



Use up to 255 characters.



Don’t use Java keywords
.



Remember that Java is a case
-
sensitive language.

Naming an Identifier

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
27

Keywords

boolean

if

interface

class

true

char

else

package

volatile

false

byte

final

switch

while

throws

float

private

case

return

native

void

protected

break

throw

implements

short

public

default

try

import

double

static

for

catch

synchronized

int

new

con
tinue

finally

const

long

this

do

transient

goto

abstract

super

extends

instanceof

null

Definition



A
keyword
is a word that’s reserved by the Java language. As a
result, you can’t use keywords as identifiers.

Write a Program that asks user to enter two
numbers and displays the larger number


Inputs:


two numbers entered via keyboard


Must be able to read the numbers


Must be able to save the numbers in the program


Declare two variables


Process: Compare the two numbers


Output:


Must be able to display the result.


Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
29

Two of the eight primitive data types

Type

Bytes

Description

int

4

Integers from
-
2,147,483,648 to 2,147,483,647.

double

8

Numbers with decimal places that range from

-
1.7E308 to 1.7E308 with up to 16 significant digits.

Variables and data types



A
variabl
e
stores a value that can change as a program executes.



Java provides for eight
primitive data types
that you can use for
storing values in memory.



The
int
data type is used for storing
integers
(whole numbers).



The
double
data type is used for storing num
bers that can have one
or more decimal places.

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
30

How to declare and initialize variables



To
initialize
a variable, you
declare
a data type and
assign
an
initial value to the variable.



An
assignment statement
assigns a value to a variable. This value
can be a literal value, another variable, or an express
ion.



If a variable has already been declared, the assignment statement
doesn’t include the data type of the variable.

Naming recommendations for variables



Start variable names with a lowercase letter and capitalize the first
letter in all words after the f
irst word.



Each variable name should be a noun or a noun preceded by one
or more adjectives.



Try to use meaningful names that are easy to remember.

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
31

How to declare and initialize a variable in one
statement

Syntax

type variableName
=
value
;

Examples

int scoreCounter = 1; // initialize an integer variable

double unitPrice = 14.95; // initialize a double variable

How to code assignment statements

i
nt quantity = 0; // initialize an integer variable

int maxQuantity = 100; // initialize another integer variable


// two assignment statements

quantity = 10; // quantity is now 10

quantity = maxQuantity; // quantity is now 100

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
32

The basic operators for arithmetic expressions

Operator

Name

Description

+

Addition

Adds two operands.

-

Subtraction

Subtracts the right operand from the left.

*

Multiplication

Multiplies the right and left operands.

/

Division

Divides the right operand in
to the left. If both
are integers, the result is an integer.

How to code arithmetic expressions



An
arithmetic expression
consists of one or more
operands
and
arithmetic operators
.



When an expression mixes int and double variables, Java
automatically
casts

the int types to double types. To keep the
decimal places, the variable that receives the result must be a
double.

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
33

Statements that use simple arithmetic expressions

// integer arithmetic

int x = 14;

int y = 8;

int result1 = x + y; // result1 = 22

int result2 = x
-
y; // result2 = 6

int result3 = x * y; // result3 = 112

int result4 = x / y;
// result4 = 1


// double arithmetic

double a = 8.5;

double b = 3.4;

double result5 = a + b; // result5 = 11.9

double result6 = a
-
b; // result6 = 5.1

double result7= a * b; // result7 = 28.9

double result8 = a / b; // re
sult8 = 2.5

Using Java Classes


To develop Java applications, we need to use
many different Java classes.


Groups of related Java classes are organized
into packages.


To use a class from a package we use the
“import” statement to import the class.

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
35

Common Java packages

Package name

Description

java.lang

Provides classes fundamental to Java, including
classes that work with primitive data types,
strings, and math functions.

java.text

Provides classes to handle text, dates, and
numbers.

java.util

Provi
des various utility classes including those for
working with collections.

java.io

Provides classes to read data from files and to
write data to files.

java.sql

Provides classes to read data from databases and
to write data to databases.

java.applet

An olde
r package that provides classes to create
an applet.

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
36

Common Java packages (continued)

Package name

Description

java.awt

An older package called the
Abstract Window
Toolkit
(AWT) that provides classes to create
graphical user interfaces.

java.awt.event

A package that provides classes necessary to
handle event
s.

javax.swing

A newer package called
Swing
that provides
classes to create graphical user interfaces and
applets.

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
37

How to import Java classes



All classes stored in the java.lang package are automatically
available to all Java programs.



To use classes that aren’t in the java.lang
package, you can code
an
import statement
.



To import one class from a package, specify the package name
followed by the class name. To import all classes in a package,
specify the package name followed by an asterisk (*).

Reading Data Entered from Keyboard


Need utilities:


Class Scanner: A simple text scanner which can parse
primitive types and strings


java.util.Scanner



Methods: nextDouble, nextInt



Must import the Scanner class to program.


import java.util.Scanner;


System.in


The "standard" input stream. This stream is already open
and ready to supply input data. Typically this stream
corresponds to keyboard input.


Example:


Scanner sc = new Scanner(System.in) ;


double num1 = sc.nextDouble();


1.

C
reate an object from a class

Syntax

ClassName objectName
=

new

ClassName(arguments)
;

Examples

Scanner sc = new Scanner(System.in);


// creates a Scanner object named sc

2.

C
all a method from an object

Syntax

objectName.methodName(arguments)

Examples

double subtotal =
sc.nextDouble()
;


// get a double entry from the console

String currentDate =
now.toString()
;


// convert

the date to a string

How to use Java classes

Murach’s Java SE 6, C2

© 2007, Mike Murach & Associates, Inc.


Slide
40

How to call a static method from a class

Syntax

ClassName.methodName(arguments)

Examples

String sPrice =
Double.toString(price)
;

// convert a double to a string

double total =
Double.parseDouble(userEntry)
;

/
/ convert a string to a double

A static method of a class can be called
directly without first creating an object from
the class.

The larger of two numbers

max method of the Math Class


The max method is declared as static (see Java
API)


public static float
max
(float

a, float

b)


Example:


Math.max(num1,num2)


Other methods:


public static double
pow
(double

a, double

b)


a raises to the power of b


Math.pow(a, b);


Display Result


System.out Class


System.out.println(data)


System.out.print(data)


System.out.println("The larger number is: " +
Math.max(num1,num2));

Code Example



import java.util.Scanner;

public class Test2 {


public static void main(String[] args) {




Scanner sc = new Scanner(System.in) ;


System.out.println("enter the first number: ");


double num1 = sc.nextDouble();


System.out.println("enter the second number: ");


double num2 = sc.nextDouble();


System.out.println("The larger number is: " + Math.max(num1,num2));


}

}

Formula to Expression

CD
B
A
D
C
AB
CD
B
A



AB
A
A
B
2
2

D
C
AB
CD
B
A
B
A
X
X
Y
X








Date Class

java.util.Date


The class Date represents a specific instant in
time, with millisecond precision.


Date myDate = new Date();


System.out.println("Today is: " + myDate.toString());



Note: import java.util.Date;


Note: import java.util.*;