Sie sind auf Seite 1von 77

Basic Elements of Java

Basic Syntax
Case

Sensitivity -Java is case sensitive, which


means identifierHelloandhellowould 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.
Exampleclass MyFirstJavaClass

Basic Syntax
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.
Examplepublic void myMethodName()

Program

File Name -Name of the program file


should exactly match the class name.

Basic Syntax
public

static void main(String


args[])
-Java program processing starts from

the main() method which is a mandatory


part of every Java program.

Package, Class, Method


A

package is a collection of related


classes
Class is used to create Java
programs
Method is a set of instructions
designed to accomplish a specific
task.
package java.util
class Scanner.

Package, Class, Method


This

and other mathematical


methods are contained in the class
Math.
The name of the package containing
the class Math is java.lang.

Package

Program Structure

Program Structure
To

use named constants and stream


objects in the method main, Java
requires that you declare the named
constants and the input stream
objects with the reserved word
static.

Program Structure

Hello World

A Java Program

Sample Run

Java Class
The

basic unit of a Java program is a


class.
A Java application program is,
therefore, a collection of one or more
classes.
Typically, every Java class consists
of one or more methods.
Roughly speaking, a method is a
sequence of statements or
instructions whose objective is to

Java class

Java Class
The

first line of the program is:


public class ASimpleJavaProgram

ASimpleJavaProgram

is the name of the

Java class.
The

second line of the program consists of


the left brace, which is matched with the
second right brace (the very last brace).
These braces together mark the beginning and

end of (the body of) the class


ASimpleJavaProgram.

Java Class

Method main

Method main
The

basic parts of the method main are


the heading and the body.
The first line of the method main:
public static void main(String[] args)
is called the heading of the method main.
The

statements enclosed between braces


( { and }) form the body of the method
main.

Method main
The

body of the method main contains two


types of statements:
Declaration statements
Executable statements

Declaration

statements are used to declare


things such as variables.

Executable

statements perform calculations,


manipulate data, create output, accept
input, and so on.

Basics of a Java Program


Two

types of Java programs

Java applets - Java applets are programs

designed to run on a Web browser.


Java application programs - Java
application programs do not require a
Web browser.

Basics of a Java Program


To

write meaningful programs, you must


learn the programming languages special
symbols, words, and syntax rules.

The programming languages rules,


symbols, special words, and their meanings
enable you to write programs to solve
problems.

Programming

language: A set of rules,


symbols, and special words used to
construct programs.

Comments
Typically,

comments can be used to


identify the authors of the program, give
the date when the program is written or
modified, give a brief explanation of the
program, and explain the meaning of
key statements in a program.

Comments

compiler.

are for the reader, not for the

Comments
ASimpleJavaProgram,

given in our
example, contains the following comments:

Two

common types of comments

single-line comments
multiple-line comments

Single-line Comments
Single-line

comments begin
with // and can be placed anywhere
in the line.
Everything encountered in that line
after // is ignored by the compiler
You can put comments at the end of
this line as follows:
System.out.println("7 + 8 = " + (7 + 8)); //prints:
7 + 8 = 15

Multiple-line Comments
Multiple-line

comments are enclosed


between /* and */.
The compiler ignores anything that
appears between /* and */.
For example, the following is an example
of a multiple-line comment:
/*
This is my first Java program
*/

Special Symbols
In

Java, commas are used


to separate items in a list.

Semicolons

are used to
end a Java statement.

The

third row consists of


tokens made up of two
characters, but which are
regarded as single
symbols. No character can
come between the two
characters in these
symbols, not even a blank.

Token: smallest individual unit


of a program Java

Reserved Words
(Keywords)
Reserved

words
are also called
keywords.

Reserved

words
cannot be
redefined within
any program;
that is, they
cannot be used
for anything
other than their
intended use.

Identifiers
A

third category of tokens is identifiers. Identifiers


are names of things, such as variables, constants,
and methods, that appear in programs.

Identifier:

A Java identifier consists of letters,


digits, the underscore character (_), and the dollar
sign ($) and must begin with a letter, underscore,
or the dollar sign.

key word cannot be used as an identifier.

Most

importantly identifiers are case sensitive.

Identifiers
The

following are legal identifiers in Java:

first
conversion
payRate
counter1
$Amount

Identifiers
For

names of classes, capitalize the first letter of the


class name
ThisIsAnExampleOfClassName

For

names of methods and variables, the first letter of


the word should start with a small letter. For example:
thisIsAnExampleOfVariable

In

case of multi-word identifiers, use capital letters to


indicate the start of the word except the first word for
variables
charArray, fileNumber, ClassName

Avoid

using underscores at the start of the identifier

Data Types
The

objective of a Java program is to


manipulate data.

Data

type: A set of values together


with a set of operations on those
values.

Primitive data types


The

primitive data types are the


fundamental data types in Java. There are
three categories of primitive data types:
Integral, which is a data type that deals with

integers, or numbers without a decimal part


(and characters)
Floating-point, which is a data type that
deals with decimal numbers
Boolean, which is a data type that deals with
logical values

Integral Data Types


Integral

data types are further classified into


five categories:
char
byte
short
int
long

Which

data type you use depends on how big


a number your program needs to deal with.

Integral Data Types

int Data Types


Positive

integers do not require a +


sign in front of them.

No

commas are used within an


integer.

Recall

that in Java, commas are used


for separating items in a list. Thus,
36,782 is interpreted as two
integers: 36 and 782.

char Data Types


The

main purpose of this data type is to represent


single charactersthat is, letters, digits, and special
symbols.

When

using the char data type, you enclose each


character represented within single quotation marks.
'A', 'a', '0', '*', '+', '$', '&', ' '

Note

that a blank space is a character and is written


as ' ', with a space between

The

data type char allows only one symbol to be


placed between the single quotation marks. Thus, the
value 'abc' is not of type char.

boolean Data Types


The

data type boolean has only two


values: true and false.
true and false are called the logical

(Boolean) values
Default value: false
The

primary purpose of this data type is


to manipulate logical (Boolean)
expression.
An expression that evaluates to true or false

is called a logical (Boolean) expression.

Floating-point Data
Types
To

deal with decimal numbers, Java


provides the floating-point data type.
Java provides two data types to
represent decimal numbers:
float
double

float vs double
float:

The data type float is used in Java to represent


any real number between 3.4E+38 and 3.4E+38. The
memory allocated for the float data type is 4 bytes.

double:

The data type double is used in Java to


represent any real number between 1.7E+308 and
1.7E+308. The memory allocated for the double data
type is 8 bytes.

number

of decimal places

float values is 6 or 7.
double type is typically 15.

class String
String

is a sequence of zero or more


characters.
Strings in Java are enclosed in double
quotation marks (not in single quotation
marks, as are the char data types).
To process strings effectively, Java
provides the class String.
the class String contains various operations to

manipulate a string.
the class String is not a primitive type

String
Null

or empty string - a string that


contains no characters

The

following are examples of


strings. Note that "" is the empty
string.
Liza"
Hello World"

Position in the String


Every

character in a string has a specific position in the string.


The position of the first character is 0, the position of the second
character is 1, and so on.
The length of a string is the number of characters in it.

When

determining the length of a string, you must also count


any spaces contained in the string.
For example, the length of the string "It is a beautiful day." is 22.

Strings and the Operator


+
One

of the most common operations performed


on strings is the concatenation operation,
which allows a string to be appended at the end
of another string.

The

operator + can be used to concatenate (or


join) two strings as well as a string and a
numeric value or a character.

The

associativity of the operator + is from left


to right, so the operator + is evaluated from left
to right.

Strings and the Operator


+
Expression

Evaluation

"Sunny" + " Day"

"Sunny Day"

"Amount Due = $" + 576.35

"Amount Due = $576.35"

"The sum = " + 12 + 26

"The sum = 1226"

"The sum = " + (12 + 26)

"The sum = 38"

12 + 26 + " is the sum"

"38 is the sum"

Sample Program

Output of the Program

Allocating Memory with Named


Constants and Variables
When

you instruct the computer to allocate memory,


you tell it what names to use for each memory
location and what type of data to store in those
locations.
Named constant: A memory location whose content
is not allowed to change during program execution.
To

allocate memory, we use Javas declaration


statements. The syntax to declare a named constant
is:

Named Constant

Variables
In

Java, memory cells whose contents can be


modified during program execution are called
variables.

Variable:

A memory location whose content


may change during program execution.
The syntax for declaring one variable or
multiple variables is:

Variable Types
There

are three kinds of variables in

Java:
Local variables
Instance variables
Class/static variables

Local vs Instance vs
Class

Local vs Instance vs
Class

Sample Program: Local


Variable

Sample Program

In

this example:

side1,side2areinstance variables. Any

method inTwoSidescan access these


variables directly.
side1Squared,side2Squared,

andhypSquared
are local variables
intestRightTriangle. They are only
valid intestRightTriangle.

Variables
Initialize

your variables as you


declare them.
Use descriptive names for your
variables.
For naming variables, the first
letter of the word should start
with a small letter
In case of multi-word, use capital
letters to indicate the start of the
word

Declaring and Initializing


Variables

Putting Data into


Variables
The

two common ways to place data


into a variable are:
1. Use an assignment statement.
2. Use input (read) statements.

Assignment Statement

Assignment Statements

SAMPLE
PROGRAM

Output of the Program

Assignment Statements

Values of the Variables


num1, num2, and num3

Values of the Variables


num1, num2, and num3

Assignment Statement

Output Statements
In

Java, output on the standard output


device is accomplished by using the
standard output object System.out.
The object System.out has access to two
methods, print and println, to output a
string on the standard output device.
The syntax to use the object System.out
and the methods print and println is:

Output Statements
System.out.println();

or System.out.print("\n");

only positions the insertion point at the beginning of the next

line.

Commonly Used Escape


Sequences
In

Java, \ is called the escape character and \n is called


the newline escape sequence

Programming Style and


Form
Every

Java application program must


satisfy certain language rules.
It must also satisfy the syntax rules,
which, like grammar rules, tell what is
correct and what is incorrect, and what
is legal and what is illegal in the
language.
Other rules give precise meaning to the
language; that is, they support the
languages semantics semantic rules

Syntax
Errors

in syntax are detected during compilation. Consider


the following Java statements:
int x;

//Line 1

int y
//Line 2
double z; //Line 3
y = w + x; //Line 4
When

these statements are compiled, a compilation error


will occur at Line 2and Line 4

Note

that compilers not only discover syntax errors, but


also provide hints and sometimes tell the user where the
syntax errors are and how to fix them.

USE OF SEMICOLONS,
BRACES, AND COMMAS
In

Java, a semicolon is used to terminate a


statement. The semicolon is also called a
statement terminator.
Note that braces, { and }, are not Java
statements. Braces are delimiters
because they enclose the body of a
method and set it off from other parts of
the program.
Commas are used to separate items in a
list

Semantics
The

set of rules that gives meaning to a language is


called semantics.

For

example, the following two expressions are both


syntactically correct expressions, but they have
different meanings:
2+3*5
(2 + 3) * 5

If

you substitute one of these expressions for the


other in a program, you will not get the same results
even though the numbers are the same, the
semantics are different.

Prompt Lines
Prompt

lines are executable


statements that inform the user
what to do.
Consider the following Java
statements, in which num is an int
variable:
System.out.println("Please enter a
number:);
num = console.nextInt();

Form and Style


The

program should be easier to


read
The program that you write should
be properly indented and formatted
To document the variables,
programmers typically declare one
variable per line
Always put a space before and after
an operator

DebuggingCode Walkthroughs
As

you write programs, you will


create unintentional bugs.
Every programmer creates bugs.
Bugs are aspects of programs that
cause the programs to do other than
what you intended.
To detect the inconsistency between
what you intended to code and what
you actually coded.

Das könnte Ihnen auch gefallen