Programming
Fundamentals

Java
Fundamentals

MELJUN CORTES
MELJUN P. CORTES

1
Objectives
At the end of the lesson, the student should
be able to:
 Identify the basic parts of a Java program
 Differe...
Dissecting my First Java
Program
1
2
3
4
5
6
7
8
9

public class Hello {
/**
* My first Java program
*/
public static void...
Dissecting my First Java
Program
1
2
3
4

public class Hello{
/**
* My first Java program
*/

 indicates the name of the ...
Dissecting my First Java
Program
1
2
3
4

public class Hello {
/**
* My first Java program
*/

 The next line which conta...
Dissecting my First Java
Program
1
2
3
4

public class Hello{
/**
* My first Java program
*/

 The next three lines indic...
Dissecting my First Java
Program
1
2
3
4
5

public class Hello {
/**
* My first Java program
*/
public static void main( S...
Dissecting my First Java
Program
1
2
3
4
5
6

public class Hello {
/**
* My first Java program
*/
public static void main(...
Dissecting my First Java
Program
1
2
3
4
5
6
7

public class Hello {
/**
* My first Java program
*/
public static void mai...
Best Practice
1. Your Java programs should always end with the
.java extension.
2. Filenames should match the name of your...
Dissecting my First Java
Program
1
2
3
4
5
6
7
8
9

public class Hello {
/**
* My first Java program
*/
public static void...
Java Comments
 Comments

These are notes written to a code for
documentation purposes.
 Those texts are not part of the ...
Java Comments
 C++-Style Comments

C++ Style comments starts with //
 All the text after // are treated as comments
 Fo...
Java Comments
 C-Style Comments

C-style comments or also called multiline
comments starts with a /* and ends with a
*/.
...
Java Comments
 Javadoc Comments
 Javadoc comments are used for generating
an HTML documentation for your Java
programs.
...
Java Statements
 Statement


one or more lines of code terminated by a
semicolon.

System.out.println(“Hello world”);

M...
Java Blocks
 Block

is one or more statements bounded by an
opening and closing curly braces that
groups the statements a...
Java Statements and Blocks
Best Practice
You should indent the next statements four
spaces after the start of a block. For...
Java Identifiers
 Identifiers

are tokens that represent names of
variables, methods, classes, etc.
 Examples of identif...
Java Identifiers
 Identifiers must begin with either a letter,

an underscore “_”, or a dollar sign “$”.
Letters may be l...
Java Identifiers
Best Practice
1. For names of classes, capitalize the first letter of the
class name. For example,
ThisIs...
Java Identifiers
Best Practice
3. In case of multi-word identifiers, use capital
letters to indicate the start of the word...
Java Keywords
 Keywords are predefined identifiers

reserved by Java for a specific purpose.
 You cannot use keywords as...
Java Keywords

MELJUN P. CORTES

24
Java Literals
 Literals are tokens that do not change -

they are constant.
 The different types of literals in Java are...
Java Literals: Floating
Point
 Represents decimals with fractional parts


Example: 3.1416

 Can be expressed in standa...
Java Literals: Boolean
 Boolean literals have only two values, true or

false.

MELJUN P. CORTES

27
Java Literals: Character
 Character Literals represent single Unicode

characters.
 Unicode character

a 16-bit characte...
Java Literals: Character
 To use a character literal, enclose the

character in single quote delimiters.
 For example

t...
Java Literals: Character
The following literals all refer to the same
character:
char c = ‘P’;
char d = 80;
char g = ‘u005...
Java Literals: String
 String literals represent multiple characters

and are enclosed by double quotes.
 An example of ...
Primitive Data Types

 The Java programming language defines

eight primitive data types.
boolean (for logical)
 char (f...
Primitive Data Types:
Logical-boolean
 A boolean data type represents two states:

true and false.
 An example is,

bool...
Primitive Data Types:
Textual-char
 A character data type (char), represents a single

Unicode character.
 It must have ...
Primitive Data Types:
Textual-char
 Although, String is not a primitive data type (it is a

Class), we will just introduc...
Primitive Data Types: Integral
– byte, short, int & long
 Integral data types in Java uses three forms – decimal, octal

...
Primitive Data Types: Integral
– byte, short, int & long
 Integral data type have the following

ranges:

MELJUN P. CORTE...
Primitive Data Types: Floating
Point – float and double
 Floating point types has double as default data type.
 Floating...
Primitive Data Types: Floating
Point – float and double
 Floating-point data types have the following

ranges:

MELJUN P....
Casting
 Among integral types, casting is implicit if from

narrow to wide:
byte b; short s; int i; long l;
s = b;
i = b;...
Casting
 Among integral types, casting is implicit if from

narrow to wide:
byte b; short s; int i; long l;
b = l;
s = i;...
Casting
 Casting to a more narrow datatype requires an

explicit cast. Initial bits will be dropped.
byte b; short s; int...
Casting
 Similar rules for floating-point primitives:

float f; double d;
d = f;
f = d;
f = (double) d;

MELJUN P. CORTES...
Casting
 Integral types can be implicitly cast to floating-

point types.
byte b; short s; int i; long l; float f; double...
Casting
 If a floating-point is cast to an integral,

digits after the decimal-point are dropped:
double d = 4.7;
int i =...
Casting
 char can be implicitly cast to int, long or

floating-point types
char c;
int i = c;
float f = c;
short s = c;
s...
Casting
 booleans cannot be cast to any other datatype

boolean b;
int i = b;
int j = (int) b;
double d = (double) b;
sho...
Variables
 A variable is an item of data used to store

the state of objects.
 A variable has a:


data type




The ...
Declaring and Initializing
Variables
 Declare a variable as follows:

<data type> <name> [=initial value];
 Note: Values...
Declaring and Initializing
Variables: Sample Program
1
2
3
4
5

public class VariableSamples {
public static void main( St...
Declaring and Initializing
Variables: Best Practice
1. It always good to initialize your variables
as you declare them.
2....
Declaring and Initializing
Variables: Best Practice
3. Declare one variable per line of code. For
example, the variable de...
Scope of a Variable
 The scope






determines where in the program the variable is
accessible.
determines the lifeti...
Scope of a Variable
 A variable's scope is


inside the block where it is declared,
starting from the point where it is ...
Example 1

MELJUN P. CORTES

55
Example 1
 The code we have here represents five scopes

indicated by the lines and the letters representing the
scope.
...
Example 2

MELJUN P. CORTES

57
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
...
Scope of a Variable
 When declaring variables, only one variable with a given

identifier or name can be declared in a sc...
Scope of a Variable
 However, you can have two variables of the

same name, if they are not declared in the
same block. F...
Outputting Variable Data
 In order to output the value of a certain

variable, we can use the following
commands:
System....
Outputting Variable Data:
Sample Program
1
2
3
4
5
6
7
8
9

public class OutputVariable {
public static void main( String[...
System.out.println() vs.
System.out.print()
 System.out.println()


Appends a newline at the end of the data
output

 S...
System.out.println() vs.
System.out.print() Examples
 Program 1:
System.out.print(“Hello”);
System.out.print(“World”);

O...
Reference Variables vs.
Primitive Variables
 Two types of variables in Java:

Primitive Variables
 Reference Variables
...
Reference Variables vs.
Primitive Variables
 Reference Variables
 variables that stores the address in the
memory locati...
Example
 Suppose we have two variables with data

types int and String.
int num = 10; // primitive type
String name = "He...
Example
 The picture shown below is the actual

memory of your computer, wherein you
have the address of the memory cells...
Operators
 Different types of operators:

arithmetic operators
 relational operators
 logical operators
 conditional o...
Arithmetic Operators

MELJUN P. CORTES

70
Arithmetic Operators:
Sample Program
1 public class ArithmeticDemo {
2
public static void main(String[] args){
3
//a few n...
Arithmetic Operators:
Sample Program
15
16
17
18

//subtracting numbers
System.out.println("Subtracting...");
System.out.p...
Arithmetic Operator s:
Sample Program
29
30
31
32
33

//computing the remainder resulting from dividing
// numbers
System....
Arithmetic Operators:
Sample Program Output
Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + ...
Pop Quiz
 What is the result of writing this code:
byte x = 4;
byte y = 3;
byte z = x * y;

MELJUN P. CORTES

75
Pop Quiz
 What is the result of writing this code:
byte x = 4;
byte y = 3;
byte z = x * y;
 Will not compile!

MELJUN P....
Arithmetic Operators
 byte, short and char get automatically

promoted to int before any arithmetic
operation.
byte x = 4...
Arithmetic Operators
 In mixed expressions, all participants get

promoted to datatype of widest participant
 Floating p...
Increment and Decrement
Operators
 unary increment operator (++)
 unary decrement operator (--)
 Increment and decremen...
Increment and Decrement
Operators

MELJUN P. CORTES

80
Increment and Decrement
Operators
 The increment and decrement operators can

be placed before or after an operand.
 Whe...
Increment and Decrement
Operators
 When the increment and decrement

operators are placed after the operand, the
old valu...
Increment and Decrement
Operators: Best Practice
 Always keep expressions containing

increment and decrement operators s...
Relational Operator s
 Relational operators compare two values and determines

the relationship between those values.
 T...
Relational Operators:
Sample Program
1 public class RelationalDemo{
2
public static void main(String[] args){
3
//a few nu...
Relational Operators:
Sample Program
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

//greater than or equal to
System.out.p...
Relational Operators:
Sample Program
31
32
33
34
35
36
37
38
39
40

//equal to
System.out.println("Equal to...");
System.o...
Relational Operators:
Sample Program Output
Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j = false
j > i = ...
Logical Operators
 Logical operators have one or two boolean

operands that yield a boolean result.
 There are six logic...
Logical Operators
 The basic expression for a logical operation

is,
x1 op x2
where,
x1, x2 - can be boolean expressions,...
Logical Operators: &&(logical)
and &(boolean logical) AND
 Here is the truth table for && and &,

MELJUN P. CORTES

91
Logical Operators: &&(logical)
and &(boolean logical) AND

 The basic difference between && and & operators :


&& suppo...
Logical Operators: &&(logical)
and &(boolean logical) AND
1 public class TestAND {
2
public static void main( String[] arg...
Logical Operators: &&(logical)
and &(boolean logical) AND
 The output of the program is,

0
10
false
0
11
false
 Note, t...
Logical Operators: || (logical) and
| (boolean logical) inclusive OR
 Here is the truth table for || and |,

MELJUN P. CO...
Logical Operators: || (logical) and |
(boolean logical) inclusive OR
 The basic difference between || and I operators :

...
Logical Operators: || (logical) and |
(boolean logical) inclusive OR
1 public class TestOR {
2
public static void main( St...
Logical Operators: || (logical) and |
(boolean logical) inclusive OR
 The output of the program is,

0
10
true
0
11
true
...
Logical Operators: ^ (boolean
logical exclusive OR)
 Here is the truth table for ^,

 The result of an exclusive OR oper...
Logical Operators: ^ (boolean
logical exclusive OR)
1 public class TestXOR {
2
public static void main( String[] args ){
3...
Logical Operators: ^ (boolean
logical exclusive OR)
 The output of the program is,

false
true
false
true

MELJUN P. CORT...
Logical Operators: !
(logical NOT)
 The logical NOT takes in one argument,

wherein that argument can be an
expression, v...
Logical Operators: !
(logical NOT)
1
2
3
4
5
6
7
8

public class TestNOT {
public static void main( String[] args ){
boole...
Logical Operators:
Conditional Operator (?:)
 The conditional operator ?:






is a ternary operator.
 This means th...
Logical Operators:
Conditional Operator (?:)
1 public class ConditionalOperator {
2
public static void main( String[] args...
Logical Operators:
Conditional Operator (?:)

MELJUN P. CORTES

106
Operator Precedence

MELJUN P. CORTES

107
Operator Precedence
 Given a complicated expression,

6%2*5+4/2+88-10
we can re-write the expression and place
some paren...
Operator Precedence: Best
Practice
 To avoid confusion in evaluating

mathematical operations, keep your
expressions simp...
Summary
 Java Comments (C++-Style Comments, C-






Style Comments, Special Javadoc
Comments)
Java statements, block...
Summary
 Variables (declare, initialize, output)
 Scope of a variable
 System.out.println() vs. System.out.print()
 Re...
Upcoming SlideShare
Loading in …5
×

MELJUN CORTES Java Programming Fundamentals

586 views

Published on

MELJUN CORTES Java Programming Fundamentals

Published in: Technology, News & Politics
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
586
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
24
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

MELJUN CORTES Java Programming Fundamentals

  1. 1. Programming Fundamentals Java Fundamentals MELJUN CORTES MELJUN P. CORTES 1
  2. 2. 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 MELJUN P. CORTES 2
  3. 3. Dissecting my First Java Program 1 2 3 4 5 6 7 8 9 public class Hello { /** * My first Java program */ public static void main( String[] args ){ //prints the string Hello world on screen System.out.println(“Hello world”); } } MELJUN P. CORTES 3
  4. 4. Dissecting my First Java Program 1 2 3 4 public class Hello{ /** * My first Java program */  indicates the name of the class which is Hello  In Java, all code should be placed inside a class declaration  The class uses an access specifier public, which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). We will be covering packages and access specifiers later. MELJUN P. CORTES 4
  5. 5. Dissecting my First Java Program 1 2 3 4 public class Hello { /** * My first Java program */  The next line which contains a curly brace { indicates the start of a block. MELJUN P. CORTES 5
  6. 6. Dissecting my First Java Program 1 2 3 4 public class Hello{ /** * My first Java program */  The next three lines indicates a Java comment. MELJUN P. CORTES 6
  7. 7. Dissecting my First Java Program 1 2 3 4 5 public class Hello { /** * My first Java program */ public static void main( String[] args ){  indicates the name of one method in Hello which is the main method.  The main method is the starting point of a Java program.  Make sure to follow the exact signature. MELJUN P. CORTES 7
  8. 8. Dissecting my First Java Program 1 2 3 4 5 6 public class Hello { /** * My first Java program */ public static void main( String[] args ){ //prints the string “Hello world” on screen  The next line is also a Java comment MELJUN P. CORTES 8
  9. 9. Dissecting my First Java Program 1 2 3 4 5 6 7 public class Hello { /** * My first Java program */ public static void main( String[] args ){ //prints the string “Hello world” on screen System.out.println(“Hello world”);  The command System.out.println(), prints the text enclosed by quotation on the screen. MELJUN P. CORTES 9
  10. 10. Best Practice 1. Your Java programs should always end with the .java extension. 2. 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. 3. You should write comments in your code explaining what a certain class does, or what a certain method do. MELJUN P. CORTES 10
  11. 11. Dissecting my First Java Program 1 2 3 4 5 6 7 8 9 public class Hello { /** * My first Java program */ public static void main( String[] args ){ //prints the string “Hello world” on screen System.out.println(“Hello world”); } }  The last two lines which contains the two curly braces is used to close the main method and class respectively. MELJUN P. CORTES 11
  12. 12. Java Comments  Comments These are notes written to a code for documentation purposes.  Those texts are not part of the program and does not affect the flow of the program.   3 Types of comments in Java  C++ Style Comments C Style Comments  Special Javadoc Comments  MELJUN P. CORTES 12
  13. 13. Java Comments  C++-Style Comments C++ Style comments starts with //  All the text after // are treated as comments  For example: // This is a C++ style or single line comments  MELJUN P. CORTES 13
  14. 14. Java Comments  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 */  MELJUN P. CORTES 14
  15. 15. Java Comments  Javadoc Comments  Javadoc comments are used for generating an HTML documentation for your Java programs.  You can create javadoc comments by starting the line with /** and ending it with */. /** This is an example of special java doc comments used for n generating an html documentation. It uses tags like: @author Florence Balagtas @version 1.2 */ MELJUN P. CORTES 15
  16. 16. Java Statements  Statement  one or more lines of code terminated by a semicolon. System.out.println(“Hello world”); MELJUN P. CORTES 16
  17. 17. Java Blocks  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.  public static void main(String[] args ){ System.out.println("Hello"); System.out.println("world”); } MELJUN P. CORTES 17
  18. 18. Java Statements and Blocks Best Practice You should indent the next statements four spaces after the start of a block. For example: public static void main(String[] args ){ System.out.println("Hello"); System.out.println("world"); } MELJUN P. CORTES 18
  19. 19. 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. MELJUN P. CORTES 19
  20. 20. 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. MELJUN P. CORTES 20
  21. 21. Java Identifiers Best Practice 1. For names of classes, capitalize the first letter of the class name. For example, ThisIsAnExampleOfClassName 2. For names of methods and variables, the first letter of the word should start with a small letter. For example, thisIsAnExampleOfMethodName MELJUN P. CORTES 21
  22. 22. Java Identifiers Best Practice 3. 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. 4. Avoid using underscores at the start of the identifier such as _read or _write. MELJUN P. CORTES 22
  23. 23. 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.  The next slide contains the list of the Java Keywords. MELJUN P. CORTES 23
  24. 24. Java Keywords MELJUN P. CORTES 24
  25. 25. 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  MELJUN P. CORTES 25
  26. 26. Java Literals: Floating Point  Represents decimals with fractional parts  Example: 3.1416  Can be expressed in standard or scientific notation  Example: 583.45 (standard), 5.8345e2 (scientific) MELJUN P. CORTES 26
  27. 27. Java Literals: Boolean  Boolean literals have only two values, true or false. MELJUN P. CORTES 27
  28. 28. Java Literals: Character  Character Literals represent single Unicode characters.  Unicode character a 16-bit character set that replaces the 8-bit ASCII character set.  Unicode allows the inclusion of symbols and special characters from other languages.  MELJUN P. CORTES 28
  29. 29. Java Literals: Character  To use a character literal, enclose the character in single quote delimiters.  For example the letter a, is represented as ‘a’.  special characters such as a newline character, a backslash is used followed by the character code. For example, ‘n’ for the newline character, ‘r’ for the carriage return, ‘b’ for backspace.  MELJUN P. CORTES 29
  30. 30. Java Literals: Character The following literals all refer to the same character: char c = ‘P’; char d = 80; char g = ‘u0050’;  hexadecimal MELJUN P. CORTES 30
  31. 31. Java Literals: String  String literals represent multiple characters and are enclosed by double quotes.  An example of a string literal is: “Hello World” MELJUN P. CORTES 31
  32. 32. Primitive Data Types  The Java programming language defines eight primitive data types. boolean (for logical)  char (for textual)  byte  short  int  long (integral)  double  float (floating point).  MELJUN P. CORTES 32
  33. 33. Primitive Data Types: Logical-boolean  A boolean data type represents two states: true and false.  An example is, boolean result = true;  The example shown above, declares a variable named result as boolean type and assigns it a value of true. MELJUN P. CORTES 33
  34. 34. Primitive Data Types: Textual-char  A character data type (char), represents a single Unicode character.  It must have its literal enclosed in single quotes(’ ’).  For example, ‘a’ //The letter a ‘t’ //A tab  To represent special characters like ' (single quotes) or " (double quotes), use the escape character . For example, ''' //for single quotes '"' //for double quotes MELJUN P. CORTES 34
  35. 35. Primitive Data Types: Textual-char  Although, String is not a primitive data type (it is a Class), we will just introduce String in this section.  A String represents a data type that contains multiple characters. It is not a primitive data type, it is a class.  It has its literal enclosed in double quotes(“”).  For example, String message = “Hello world!”; MELJUN P. CORTES 35
  36. 36. Primitive Data Types: Integral – byte, short, int & long  Integral data types in Java uses three forms – decimal, octal or hexadecimal. 2 //The decimal value 2 077 //The leading 0 indicates an octal value 0xBACC //The leading 0x indicates a hex value  Integral types has int as default data type.  You can define its long value by appending the letter l or L: 10L MELJUN P. CORTES 36
  37. 37. Primitive Data Types: Integral – byte, short, int & long  Integral data type have the following ranges: MELJUN P. CORTES 37
  38. 38. Primitive Data Types: Floating Point – float and double  Floating point types has double as default data type.  Floating-point literal includes either a decimal point or one of the following, E or e //(add exponential value) F or f //(float) D or d //(double)  Examples: 3.14 //A simple floating-point value (a double) 6.02E23 //A large floating-point value 2.718F //A simple float size value 123.4E+306D//A large double value with redundant D MELJUN P. CORTES 38
  39. 39. Primitive Data Types: Floating Point – float and double  Floating-point data types have the following ranges: MELJUN P. CORTES 39
  40. 40. Casting  Among integral types, casting is implicit if from narrow to wide: byte b; short s; int i; long l; s = b; i = b; i = s; l = i; l = s; MELJUN P. CORTES 40
  41. 41. Casting  Among integral types, casting is implicit if from narrow to wide: byte b; short s; int i; long l; b = l; s = i; b = i; b = s; s = l; MELJUN P. CORTES 41
  42. 42. Casting  Casting to a more narrow datatype requires an explicit cast. Initial bits will be dropped. byte b; short s; int i; long l; b = (byte) l; s = (short) i; b = (byte) i; b = (byte) s; s = (short) l; MELJUN P. CORTES 42
  43. 43. Casting  Similar rules for floating-point primitives: float f; double d; d = f; f = d; f = (double) d; MELJUN P. CORTES 43
  44. 44. Casting  Integral types can be implicitly cast to floating- point types. byte b; short s; int i; long l; float f; double d; f = l; f = i; d = i; d = b; d = s; MELJUN P. CORTES 44
  45. 45. Casting  If a floating-point is cast to an integral, digits after the decimal-point are dropped: double d = 4.7; int i = (int) d;  value of i: 4 MELJUN P. CORTES 45
  46. 46. Casting  char can be implicitly cast to int, long or floating-point types char c; int i = c; float f = c; short s = c; short s = (short) c; MELJUN P. CORTES 46
  47. 47. Casting  booleans cannot be cast to any other datatype boolean b; int i = b; int j = (int) b; double d = (double) b; short s = (short) b; MELJUN P. CORTES 47
  48. 48. Variables  A variable is an item of data used to store the state of objects.  A variable has a:  data type   The data type indicates the type of value that the variable can hold. name  MELJUN P. CORTES The variable name must follow rules for identifiers. 48
  49. 49. 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. MELJUN P. CORTES 49
  50. 50. Declaring and Initializing Variables: Sample Program 1 2 3 4 5 public class VariableSamples { public static void main( String[] args ){ //declare a data type with variable name // result and boolean data type boolean result; 6 7 8 9 //declare a data type with variable name // option and char data type char option; option = 'C'; //assign 'C' to option 10 11 //declare a data type with variable name //grade, double data type and initialized 12 13 14 } 15 } //to 0.0 double grade = 0.0; MELJUN P. CORTES 50
  51. 51. Declaring and Initializing Variables: Best Practice 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. MELJUN P. CORTES 51
  52. 52. Declaring and Initializing Variables: Best Practice 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; MELJUN P. CORTES 52
  53. 53. Scope of a Variable  The scope    determines where in the program the 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 things, just think of the scope as anything between the curly braces {...}. The outer curly braces are called the outer blocks, and the inner curly braces are called inner blocks. MELJUN P. CORTES 53
  54. 54. 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. MELJUN P. CORTES 54
  55. 55. Example 1 MELJUN P. CORTES 55
  56. 56. Example 1  The code we have here represents five scopes indicated by the lines 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. MELJUN P. CORTES 56
  57. 57. Example 2 MELJUN P. CORTES 57
  58. 58. 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  MELJUN P. CORTES 58
  59. 59. 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, { int test = 10; int test = 20; } your compiler will generate an error since you should have unique names for your variables in one block. MELJUN P. CORTES 59
  60. 60. 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, int test = 0; System.out.print( test ); //..some code here { int test = 20; System.out.print( test ); } MELJUN P. CORTES 60
  61. 61. 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() MELJUN P. CORTES 61
  62. 62. Outputting Variable Data: Sample Program 1 2 3 4 5 6 7 8 9 public class OutputVariable { public static void main( String[] args ){ int value = 10; char x; x = ‘A’; } } System.out.println( value ); System.out.println( “The value of x=“ + x ); The program will output the following text on screen: 10 The value of x=A MELJUN P. CORTES 62
  63. 63. 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 MELJUN P. CORTES 63
  64. 64. System.out.println() vs. System.out.print() Examples  Program 1: System.out.print(“Hello”); System.out.print(“World”); Output: HelloWorld  Program 2: System.out.println(“Hello”); System.out.println(“World”); Output: Hello World MELJUN P. CORTES 64
  65. 65. 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  MELJUN P. CORTES 65
  66. 66. Reference Variables vs. Primitive Variables  Reference Variables  variables that stores the address in the memory location  points to another memory location where the actual data is  When you declare a variable of a certain class, you are actually declaring a reference variable to the object with that certain class. MELJUN P. CORTES 66
  67. 67. Example  Suppose we have two variables with data types int and String. int num = 10; // primitive type String name = "Hello"; // reference type MELJUN P. CORTES 67
  68. 68. 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. MELJUN P. CORTES 68
  69. 69. Operators  Different types of operators: arithmetic operators  relational operators  logical operators  conditional operators   These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first in case multiple operators are used in one statement. MELJUN P. CORTES 69
  70. 70. Arithmetic Operators MELJUN P. CORTES 70
  71. 71. Arithmetic Operators: Sample Program 1 public class ArithmeticDemo { 2 public static void main(String[] args){ 3 //a few numbers 4 int i = 37; 5 int j = 42; 6 double x = 27.475; 7 double y = 7.22; 8 System.out.println("Variable values..."); 9 System.out.println(" i = " + i); 10 System.out.println(" j = " + j); 11 System.out.println(" x = " + x); 12 System.out.println(" y = " + y); System.out.println("Adding..."); 13 System.out.println(" i + j = " + (i + j)); 14 System.out.println(" x + y = " + (x + y)); MELJUN P. CORTES 71
  72. 72. Arithmetic Operators: Sample Program 15 16 17 18 //subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i – j)); System.out.println(" x - y = " + (x – y)); 19 20 21 22 //multiplying numbers System.out.println("Multiplying..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y)); 23 24 25 26 //dividing numbers System.out.println("Dividing..."); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); MELJUN P. CORTES 72
  73. 73. Arithmetic Operator s: Sample Program 29 30 31 32 33 //computing the remainder resulting from dividing // numbers System.out.println("Computing the remainder..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); 34 35 36 37 38 39} //mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x)); } MELJUN P. CORTES 73
  74. 74. Arithmetic Operators: Sample Program Output Variable values... i = 37 j = 42 x = 27.475 y = 7.22 Adding... i + j = 79 x + y = 34.695 Subtracting... i - j = -5 x - y = 20.255 Multiplying... i * j = 1554 x * y = 198.37 MELJUN P. CORTES Dividing... i / j = 0 x / y = 3.8054 Computing the remainder... i % j = 37 x % y = 5.815 Mixing types... j + y = 49.22 i * x = 1016.58 74
  75. 75. Pop Quiz  What is the result of writing this code: byte x = 4; byte y = 3; byte z = x * y; MELJUN P. CORTES 75
  76. 76. Pop Quiz  What is the result of writing this code: byte x = 4; byte y = 3; byte z = x * y;  Will not compile! MELJUN P. CORTES 76
  77. 77. Arithmetic Operators  byte, short and char get automatically promoted to int before any arithmetic operation. byte x = 4; byte y = 3; byte z = (byte) (x + y); MELJUN P. CORTES 77
  78. 78. Arithmetic Operators  In mixed expressions, all participants get promoted to datatype of widest participant  Floating point numbers are always considered “wider” than integrals. byte b; short s; int i; float f; b+s*i-f  all promoted to float MELJUN P. CORTES 78
  79. 79. 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, count = count + 1; //increment the value of count by 1 is equivalent to, count++; MELJUN P. CORTES 79
  80. 80. Increment and Decrement Operators MELJUN P. CORTES 80
  81. 81. 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. int int int k = i = j = k = ++j MELJUN P. CORTES 10; 3; 0; + i; //will result to k = 4+10 = 14 81
  82. 82. 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. int int int k = i = j = k = j++ MELJUN P. CORTES 10; 3; 0; + i; //will result to k = 3+10 = 13 82
  83. 83. Increment and Decrement Operators: Best Practice  Always keep expressions containing increment and decrement operators simple and easy to understand. MELJUN P. CORTES 83
  84. 84. Relational Operator s  Relational operators compare two values and determines the relationship between those values.  The output of evaluation are the boolean values true or false. MELJUN P. CORTES 84
  85. 85. Relational Operators: Sample Program 1 public class RelationalDemo{ 2 public static void main(String[] args){ 3 //a few numbers 4 int i = 37; 5 int j = 42; 6 int k = 42; 7 System.out.println("Variable values..."); 8 System.out.println(" i = " +i); 9 System.out.println(" j = " +j); 10 System.out.println(" k = " +k); 11 //greater than 12 System.out.println("Greater than..."); 13 System.out.println(" i > j = "+(i>j));//false 14 System.out.println(" j > i = "+(j>i));//true 15 System.out.println(" k > j = "+(k>j));//false MELJUN P. CORTES 85
  86. 86. Relational Operators: Sample Program 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 //greater than or equal to System.out.println("Greater than or equal to..."); System.out.println(" i >= j = "+(i>=j));//false System.out.println(" j >= i = "+(j>=i));//true System.out.println(" k >= j = "+(k>=j));//true //less than System.out.println("Less than..."); System.out.println(" i < j = "+(i<j));//true System.out.println(" j < i = "+(j<i));//false System.out.println(" k < j = "+(k<j));//false //less than or equal to System.out.println("Less than or equal to..."); System.out.println(" i <= j = "+(i<=j));//true System.out.println(" j <= i = "+(j<=i));//false System.out.println(" k <= j = "+(k<=j));//true MELJUN P. CORTES 86
  87. 87. Relational Operators: Sample Program 31 32 33 34 35 36 37 38 39 40 //equal to System.out.println("Equal to..."); System.out.println(" i == j = " + (i==j));//false System.out.println(" k == j = " + (k==j));//true //not equal to System.out.println("Not equal to..."); System.out.println(" i != j = " + (i!=j));//true System.out.println(" k != j = " + (k!=j));//false } } MELJUN P. CORTES 87
  88. 88. Relational Operators: Sample Program Output Variable values... i = 37 j = 42 k = 42 Greater than... i > j = false j > i = true k > j = false Greater than or equal to... i >= j = false j >= i = true k >= j = true Less than... i < j = true j < i = false k < j = false MELJUN P. CORTES Less than or equal to... i <= j = true j <= i = false k <= j = true Equal to... i == j = false k == j = true Not equal to... i != j = true k != j = false 88
  89. 89. Logical Operators  Logical operators have one or two boolean operands that yield a boolean result.  There are six logical operators: && (logical AND)  & (boolean logical AND)  || (logical OR)  | (boolean logical inclusive OR)  ^ (boolean logical exclusive OR)  ! (logical NOT)  MELJUN P. CORTES 89
  90. 90. 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. MELJUN P. CORTES 90
  91. 91. Logical Operators: &&(logical) and &(boolean logical) AND  Here is the truth table for && and &, MELJUN P. CORTES 91
  92. 92. 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. MELJUN P. CORTES 92
  93. 93. Logical Operators: &&(logical) and &(boolean logical) AND 1 public class TestAND { 2 public static void main( String[] args ){ 3 int i = 0; 4 int j = 10; 5 boolean test= false; 6 //demonstrate && 7 test = (i > 10) && (j++ > 9); 8 System.out.println(i); 9 System.out.println(j); 10 System.out.println(test); 11 //demonstrate & 12 test = (i > 10) & (j++ > 9); 13 System.out.println(i); 14 System.out.println(j); 15 System.out.println(test); 16 } 17 } MELJUN P. CORTES 93
  94. 94. Logical Operators: &&(logical) and &(boolean logical) AND  The output of the program is, 0 10 false 0 11 false  Note, that the j++ on the line containing the && operator is not evaluated since the first expression (i>10) is already equal to false. MELJUN P. CORTES 94
  95. 95. Logical Operators: || (logical) and | (boolean logical) inclusive OR  Here is the truth table for || and |, MELJUN P. CORTES 95
  96. 96. 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.  MELJUN P. CORTES 96
  97. 97. Logical Operators: || (logical) and | (boolean logical) inclusive OR 1 public class TestOR { 2 public static void main( String[] args ){ 3 int i = 0; 4 int j = 10; 5 boolean test= false; 6 //demonstrate || 7 test = (i < 10) || (j++ > 9); 8 System.out.println(i); 9 System.out.println(j); 10 System.out.println(test); 11 //demonstrate | 12 test = (i < 10) | (j++ > 9); 13 System.out.println(i); 14 System.out.println(j); 15 System.out.println(test); 16 } 17 } MELJUN P. CORTES 97
  98. 98. Logical Operators: || (logical) and | (boolean logical) inclusive OR  The output of the program is, 0 10 true 0 11 true  Note, that the j++ on the line containing the || operator is not evaluated since the first expression (i<10) is already equal to true. MELJUN P. CORTES 98
  99. 99. 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 calculate the result of an exclusive OR. MELJUN P. CORTES 99
  100. 100. Logical Operators: ^ (boolean logical exclusive OR) 1 public class TestXOR { 2 public static void main( String[] args ){ 3 boolean val1 = true; 4 boolean val2 = true; 5 System.out.println(val1 ^ val2); 6 val1 = false; val2 = true; 7 System.out.println(val1 ^ val2); 8 val1 = false; val2 = false; 9 System.out.println(val1 ^ val2); 10 val1 = true; val2 = false; 11 System.out.println(val1 ^ val2); 12 } 13 } MELJUN P. CORTES 100
  101. 101. Logical Operators: ^ (boolean logical exclusive OR)  The output of the program is, false true false true MELJUN P. CORTES 101
  102. 102. 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 !, MELJUN P. CORTES 102
  103. 103. Logical Operators: ! (logical NOT) 1 2 3 4 5 6 7 8 public class TestNOT { public static void main( String[] args ){ boolean val1 = true; boolean val2 = false; System.out.println(!val1); System.out.println(!val2); } }  The output of the program is, false true MELJUN P. CORTES 103
  104. 104. 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 wherein, 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. MELJUN P. CORTES 104
  105. 105. Logical Operators: Conditional Operator (?:) 1 public class ConditionalOperator { 2 public static void main( String[] args ){ 3 String status = ""; 4 int grade = 80; 5 //get status of the student 6 status = (grade >= 60)?"Passed":"Fail"; 7 //print status 8 System.out.println( status ); 9 } 10 }  The output of this program will be, Passed MELJUN P. CORTES 105
  106. 106. Logical Operators: Conditional Operator (?:) MELJUN P. CORTES 106
  107. 107. Operator Precedence MELJUN P. CORTES 107
  108. 108. Operator Precedence  Given a complicated expression, 6%2*5+4/2+88-10 we can re-write the expression and place some parenthesis base on operator precedence, ((6%2)*5)+(4/2)+88-10; MELJUN P. CORTES 108
  109. 109. Operator Precedence: Best Practice  To avoid confusion in evaluating mathematical operations, keep your expressions simple and use parentheses. MELJUN P. CORTES 109
  110. 110. 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 MELJUN P. CORTES 110
  111. 111. 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) MELJUN P. CORTES 111

×