Вы находитесь на странице: 1из 105

Programming

Fundamentals

Java Boot Camp


Module 1
Objectives
 At the end of the lesson, the student
should be able to:
 Identify the basic parts of a Java program
 Differentiate among Java literals, primitive
data types, variable types ,identifiers and
operators
 Develop a simple valid Java program using
the concepts learned in this chapter
Dissecting my First Java
Program
Best Practices
 Your Java programs should always end with the .java
extension.
 Filenames should match the name of your public
class. So for example, if the name of your public class
is Hello, you should save it in a file called
Hello.java.
 You should write comments in your code explaining
what a certain class does, or what a certain method
do.
Java Comments
 Comments
 These are notes written to a code for documentation
purposes.
 These notes are not part of the program and do not
affect the flow of the program.
 3 Types of comments in Java
 C++ Style Comments
 C Style Comments
 Javadoc Comments
Java Comments
 C++-Style Comments
 C++ Style comments start with //
 All the text after // is treated as a comment
 For example:
Java Comments
 C-Style Comments
 C-style comments, also called multiline
comments start with a /* and end with a */.
 All text in between the two delimiters is
treated as a comment.
 Unlike C++ style comments, it can span
multiple lines.
 For example:
Java Comments
 Javadoc Comments
 Javadoc comments are used for generating
HTML documentation for your Java programs.
 You can create javadoc comments by starting
the line with /** and ending it with */.
Java Statements
 Statement
 one or more lines of code terminated by a
semicolon.
Java Blocks
 Block
 is one or more statements bounded by
opening and closing curly braces that group
the statements as one unit.
 Block statements can be nested indefinitely.
 Any amount of whitespace is allowed.
Java Identifiers
 Identifiers
 are tokens that represent names of variables,
methods, classes, and other user-defined
program elements.
 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.
Java Identifiers
 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. We will discuss
more about Java keywords later.
Java Identifiers
Best Practices
 For names of classes, capitalize the first letter of the
identifier. For example:
 ThisIsAnExampleOfClassName

 For names of methods and variables, the identifier


should start with a lower-case letter. For example:
 thisIsAnExampleOfMethodName

 When creating multi-word identifiers, use capital


letters to indicate the start of each word except the
first word. For example,
 charArray, fileNumber
Java Identifiers
Best Practices
 For constants use all capitals and separate words with
underscores. For example:
 EXAMPLE_OF_A_CONSTANT
 Avoid using underscores at the start of the identifier
such as _read or _write.
Java Keywords
 Keywords are predefined identifiers
reserved by Java for specific purposes.
 You cannot use keywords as identifiers
for any user-defined elements such as
variables, methods, classes, and
constants.
 The next slide contains the list of the Java
Keywords.
Java Keywords
Java Literals
 Literals are tokens that do not change -
they are constant.
 The different types of literals in Java are:
 Integer Literals
 Floating-Point Literals
 Boolean Literals
 Character Literals
 String Literals
Primitive Data Types
 The Java programming language defines eight
primitive data types.
 Logical
 boolean
 Textual
 char
 Numerical
 byte
 short
 int
 long (integral)
 double
 float (floating point).
Primitive Data Types:
Logical-boolean
 A boolean data type represents one of two
states: true and false.
 An example is

 The example declares a boolean type


variable named result and assigns it a
value of true.
Primitive Data Types:
Textual-char
 A character data type (char), represents a
single Unicode character.
 It must have its literal enclosed in single
quotes(’’).

 To represent special characters like ' (single


quotes) or " (double quotes), use the escape
character \.
Primitive Data Types:
Textual-char
 The following literals all refer to the same
character:

Hexadecimal
Primitive Data Types:
Textual-char
 String is not a primitive data type, but due to its
very common use we will introduce String in this
section.
 A String is a data type composed of multiple
characters. As such it is not a primitive data type,
it is a class.
 It has its literals enclosed in double quotes(“ ”).
Primitive Data Types: Integral –
byte, short, int & long
 Integral data types have the following ranges:
Primitive Data Types: Integral –
byte, short, int & long
 Integral data types in Java can take values
in three forms – decimal, octal or
hexadecimal.

Integral types have int as default data


type.
 You can define a long value by appending
the letter l or L (upper or lowercase 'L')
Primitive Data Types: Floating
Point – float and double
 Floating-point data types have the
following specs:
type bits accuracy range represented (approximate only)
float 32 6 to 7 significant digits ±1.40e-45 to ±3.40e+38
double 64 14 to15 significant digits ±4.94e-324 to ±1.79e+308

 Though floating-point data types can


represent the exact value of some
integers, as a general practice we never
regard floating-point representations as
exact.
Primitive Data Types: Floating-
Point – float and double
 Floating-point types have double as default data
type.
 Floating-point literals/constants include either a
decimal point or one of the following,
E or e //(add exponential value)
F or f //(float)
D or d //(double)
 Examples:
Casting
 Among integral types, casting is implicit if
from narrow to wide
Casting
 Among integral types, casting is implicit if
from narrow to wide
Casting
 Casting to a narrower datatype requires
an explicit cast. Initial bits will be
dropped.
Casting
 Similar rules apply to floating-point
primitives:
Casting
 Integral types can be implicitly cast to
floating-point types.
Casting
 If a floating-point is cast to an integral,
digits after the decimal-point are dropped:

 value of i: 4
Casting
 char can be implicitly cast to int, long or
floating-point types
Casting
 booleans cannot be cast to any other data
type
Variables
 A variable is an item of data used to store
the state of objects.
 A variable has a:
 data type
 The data type determines the type of value that
the variable can hold.
 name
 The variable name must follow rules for identifiers.
Declaring and Initializing
Variables
 Declare a variable as follows:
 <data type> <name> [=initial value];
 Note: Values enclosed in < > are required
values, while those values in [ ] are
optional.
Declaring and Initializing
Variables: Sample Program
Declaring and Initializing
Variables: Best Practices
 It always good to initialize your variables
as you declare them.
 Use descriptive names for your variables.
For example, if you want a variable that
contains a student's grade, give it a name
like grade or englishGrade, and not just
random letters and/or numbers like g1.
Declaring and Initializing
Variables: Best Practice
 Declare one variable per line of code.
 For example, the variable declarations

are preferred over the declaration


Scope of a Variable
 The scope
 determines where in the program a variable is
accessible.
 determines the lifetime of a variable or how long the
variable can exist in memory.
 The scope is determined by where the variable
declaration is placed in the program.

 To simplify, think of the scope as anything


between the curly braces {...}. Areas outside the
curly braces are called the outer blocks, and
blocks enclosed by the curly braces are called
inner blocks.
Scope of a Variable
 A variable's scope is
 Inside the block where it is declared, starting
from the point where it is declared, and in the
inner blocks.
Example 1
 The code we have here represents five scopes
indicated by the boxes and the letters
representing the scope.
 Given the variables i, j, k, m and n, and the five
scopes A, B, C, D and E, we have the following
scopes for each variable:
 The scope of variable i is A.
 The scope of variable j is B.
 The scope of variable k is C.
 The scope of variable m is D.
 The scope of variable n is E.
Example 2
 In the main method, the scopes of the
variables are,
 ages[] – scope A
 i in B – scope B
 i in C – scope C
 In the test method, the scopes of the
variables are,
 arr[] – scope D
 i in E – scope E
Scope of a Variable
 When declaring variables, only one variable with
a given identifier or name can be declared in a
scope.
 That means that if you have the following
declaration,

your compiler will generate an error since you


should have unique names for each variable
within a single block.
Scope of a Variable
 However you can have two variables of
the same name if they are not declared in
the same block. For example,
Outputting Variable Data
 In order to output the value of a certain
variable to console, we can use the
following commands:
Outputting Variable Data:
Sample Program

 The program will output the following text on


screen:
System.out.println() vs.
System.out.print()
 System.out.println()
 Appends a newline at the end of the data
output
 System.out.print()
 Does not append newline at the end of the
data output
System.out.println() vs.
System.out.print()
 Program 1:

Output:

 Program 2:

Output:
Reference Variables vs.
Primitive Variables
 Two types of variables in Java:
 Primitive Variables
 Reference Variables
 Primitive Variables
 variables with primitive data types such as
int or long.
 stores data in the actual memory location of
where the variable is
Reference Variables vs.
Primitive Variables
 Reference Variable
 a variable that stores the address in its
memory location
 points to another memory location where the
actual data is stored.
 When you declare a variable of a certain
class, you are actually declaring only a
reference to a possible instance of that class
(which might not exist yet), and are not
creating the object itself.
Example
 Suppose we have two variables with data
types int and String.
Example
 The picture shown below is the actual
memory of your computer, wherein you
have the address of the memory cells, the
variable name and the data they hold.
Operators
 Different types of operators:
 arithmetic operators
 relational operators
 logical operators
 conditional operators
 These operators follow a precedence that
tells the compiler which operation to
evaluate first when multiple operators are
used in one statement.
Arithmetic Operators
Arithmetic Operators:
Sample Program
Arithmetic Operators:
Sample Program
Arithmetic Operators:
Sample Program
Arithmetic Operators:
Sample Program Output
Pop Quiz
 What is the result of writing this code:
Pop Quiz
 What is the result of writing this code:

 Will not compile!


Arithmetic Operators
 byte, short and char get automatically
promoted to int before any arithmetic
operation.
Arithmetic Operators
 In mixed expressions, all participants get
promoted to datatype of widest participant
 Floating point numbers are always
considered “wider” than integrals.

 all promoted to float


Increment and Decrement
Operators
 unary increment operator (++)
 unary decrement operator (--)
 Increment and decrement operators increase
and decrease a value stored in a number
variable by 1.
 For example, the expression,

is equivalent to
Increment and Decrement
Operators
Increment and Decrement
Operators
 The increment and decrement operators
can be placed before or after an operand.
 When used before an operand, it causes
the variable to be incremented or
decremented by 1, and then the new value
is used in the expression in which it
appears.
Increment and Decrement
Operators
 When the increment and decrement
operators are placed after the operand,
the old value of the variable will be used in
the expression where it appears.
Increment and Decrement
Operators: Best Practice
 Always keep expressions containing
increment and decrement operators
simple and easy to understand.
Relational Operators
 Relational operators compare two values and
determines the relationship between those values.
 The output of evaluation are the boolean values
true or false.
Relational Operators:
Sample Program
Relational Operators:
Sample Program
Relational Operators:
Sample Program
Relational Operators:
Sample Program Output
Logical Operators
 Logical operators have one or two
boolean operands that yield a boolean
result.
 There are six logical operators:
 && (short-circuit logical AND, binary)
 & (logical AND, binary)
 || (short-circuit logical OR, binary)
 | (logical inclusive OR, binary)
 ^ (logical exclusive OR, binary)
 ! (logical NOT, unary)
Logical Operators
 The basic expression for a logical
operation is,
x1 op x2
where,
x1, x2 - can be boolean expressions,
variables or constants
op - is either &&, &, ||, | or ^ operator.
 The truth tables that will be shown next,
summarize the result of each operation for
all possible combinations of x1 and x2.
Logical Operators: &&(logical)
and &(boolean logical) AND
 Here is the truth table for && and &
Logical Operators: &&(logical)
and &(boolean logical) AND
 The basic difference between && and &
operators :
 && supports short-circuit evaluations (or partial
evaluations), while & doesn't.
 Given an expression:
exp1 && exp2
 && will evaluate the expression exp1, and
immediately return a false value is exp1 is false.
 If exp1 is false, the operator never evaluates exp2
because the result of the operator will be false
regardless of the value of exp2.
 In contrast, the & operator always evaluates
both exp1 and exp2 before returning an answer.
Logical Operators: &&(logical)
and &(boolean logical) AND
Logical Operators: &&(logical)
and &(boolean logical) AND
 The output of the program is

 Note, that the j++ on the line containing


the && operator is not evaluated since the
first expression (i>10) is already equal to
false.
Logical Operators: || (logical) and
| (boolean logical) inclusive OR
 Here is the truth table for || and |,
Logical Operators: || (logical) and
| (boolean logical) inclusive OR
 The basic difference between || and I operators :
 || supports short-circuit evaluations (or partial
evaluations), while | doesn't.
 Given an expression:
exp1 || exp2
 || will evaluate the expression exp1, and
immediately return a true value is exp1 is true
 If exp1 is true, the operator never evaluates exp2
because the result of the operator will be true
regardless of the value of exp2.
 In contrast, the | operator always evaluates both
exp1 and exp2 before returning an answer.
Logical Operators: || (logical) and |
(boolean logical) inclusive OR
Logical Operators: || (logical) and
| (boolean logical) inclusive OR
 The output of the program is,

 Note, that the j++ on the line containing


the || operator is not evaluated since the
first expression (i<10) is already equal to
true.
Logical Operators: ^ (boolean
logical exclusive OR)
 Here is the truth table for ^,

 The result of an exclusive OR operation is TRUE,


if and only if one operand is true and the other is
false.
 Note that both operands must always be
evaluated in order to evaluate the result of an
exclusive OR.
Logical Operators: ^ (boolean
logical exclusive OR)
Logical Operators: ^ (boolean
logical exclusive OR)
 The output of the program is
Logical Operators: !
(logical NOT)
 The logical NOT takes in one argument,
wherein that argument can be an
expression, variable or constant.
 Here is the truth table for !,
Logical Operators: !
(logical NOT)

 The output of the program is


Logical Operators:
Conditional Operator (?:)
 The conditional operator ?:
 is a ternary operator.
 This means that it takes in three arguments that together
form a conditional expression.
 The structure of an expression using a conditional
operator is
exp1?exp2:exp3
 exp1 - is a boolean expression whose result must either be
true or false
 Result:
 If exp1 is true, exp2 is the value returned.
 If it is false, then exp3 is returned.
Logical Operators:
Conditional Operator (?:)

 The output of this program will be


Logical Operators:
Conditional Operator (?:)
Operator Precedence
Operator Precedence
 Given a compound expression,

6%2*5+4/2+88-10

we can re-write the expression and place


some parentheses based on operator
precedence,

((6%2)*5)+(4/2)+88-10
Operator Precedence:
Best Practice
 To avoid confusion in evaluating
mathematical operations, keep your
expressions simple and use parentheses.
Summary
 Java Comments (C++-Style Comments, C-
Style Comments, Special Javadoc
Comments)
 Java statements, blocks, identifiers,
keywords
 Java Literals (integer, floating point,
boolean, character, String)
 Primitive data types( boolean, char, byte,
short, int, long, float, double)
 Casting
Summary
 Variables (declare, initialize, output)
 Scope of a variable
 System.out.println() vs. System.out.print()
 Reference Variables vs. Primitive
Variables
 Operators (Arithmetic operators,
Increment and Decrement operators,
Relational operators, Logical operators,
Conditional Operator (?:), Operator
Precedence)

Вам также может понравиться