meljun cortes java programming fundamentals
DESCRIPTION
MELJUN CORTES Java Programming FundamentalsTRANSCRIPT
Java Java FundamentalsFundamentals
Programming Programming FundamentalsFundamentals
1MELJUN P. CORTESMELJUN CORTESMELJUN CORTES
ObjectivesObjectives
At the end of the lesson, the student should At the end of the lesson, the student should be able to:be able to:
Identify the basic parts of a Java programIdentify the basic parts of a Java program Differentiate among Java literals, primitive Differentiate among Java literals, primitive
data types, variable types ,identifiers and data types, variable types ,identifiers and operatorsoperators
Develop a simple valid Java program using Develop a simple valid Java program using the concepts learned in this chaptethe concepts learned in this chapterr
2MELJUN P. CORTES
Dissecting my First Java Dissecting my First Java ProgramProgram
1 public class Hello {2 /**3 * My first Java program4 */5 public static void main( String[] args ){6 //prints the string Hello world on screen7 System.out.println(“Hello world”);8 }9 }
3MELJUN P. CORTES
indicates the name of the class which is Helloindicates the name of the class which is Hello In Java, all code should be placed inside a class In Java, all code should be placed inside a class
declarationdeclaration The class uses an access specifier public, which indicates The class uses an access specifier public, which indicates
that our class in accessible to other classes from other that our class in accessible to other classes from other packages (packages are a collection of classes). We will packages (packages are a collection of classes). We will be covering packages and access specifiers later. be covering packages and access specifiers later.
1 public class Hello{2 /**3 * My first Java program4 */
Dissecting my First Java Dissecting my First Java ProgramProgram
4MELJUN P. CORTES
1 public class Hello {2 /**3 * My first Java program4 */
Dissecting my First Java Dissecting my First Java ProgramProgram
The next line which contains a curly brace The next line which contains a curly brace { indicates the start of a block{ indicates the start of a block..
5MELJUN P. CORTES
The next three lines indicates a Java The next three lines indicates a Java comment. comment.
1 public class Hello{2 /**3 * My first Java program4 */
Dissecting my First Java ProgramDissecting my First Java Program
6MELJUN P. CORTES
indicates the name of one method in Hello indicates the name of one method in Hello which is the main method. which is the main method.
The main method is the starting point of a The main method is the starting point of a Java program. Java program.
Make sure to follow the exact signature. Make sure to follow the exact signature.
1 public class Hello {2 /**3 * My first Java program4 */5 public static void main( String[] args ){
Dissecting my First Java ProgramDissecting my First Java Program
7MELJUN P. CORTES
The next line is also a Java commentThe next line is also a Java comment
1 public class Hello {2 /**3 * My first Java program4 */5 public static void main( String[] args ){6 //prints the string “Hello world” on
screen
Dissecting my First Java Dissecting my First Java ProgramProgram
8MELJUN P. CORTES
The command System.out.println(), prints The command System.out.println(), prints the text enclosed by quotation on the the text enclosed by quotation on the screen. screen.
1 public class Hello {2 /**3 * My first Java program4 */5 public static void main( String[] args ){6 //prints the string “Hello world” on
screen7 System.out.println(“Hello world”);
Dissecting my First Java Dissecting my First Java ProgramProgram
9MELJUN P. CORTES
Best PracticeBest Practice1. Your Java programs should always end with the 1. Your Java programs should always end with the .java.java extension. extension.
2. Filenames should match the name of your 2. Filenames should match the name of your public class. So for example, if 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 public class is Hello, you should save it in a file calledcalled Hello.java. Hello.java.
3. You should write comments in your code 3. You should write comments in your code explaining what a certain class does, or what a explaining what a certain class does, or what a certain method do. certain method do.
10MELJUN P. CORTES
The last two lines which contains the two The last two lines which contains the two curly braces is used to close the main curly braces is used to close the main method and class respectively. method and class respectively.
1 public class Hello {2 /**3 * My first Java program4 */5 public static void main( String[] args ){6 //prints the string “Hello world” on screen7 System.out.println(“Hello world”);8 }9 }
Dissecting my First Java Dissecting my First Java ProgramProgram
11MELJUN P. CORTES
Java CommentsJava Comments Comments Comments
These are notes written to a code for These are notes written to a code for documentation purposes.documentation purposes.
Those texts are not part of the program and Those texts are not part of the program and does not affect the flow of the program.does not affect the flow of the program.
3 Types of comments in Java3 Types of comments in Java C++ Style CommentsC++ Style Comments C Style CommentsC Style Comments Special Javadoc CommentsSpecial Javadoc Comments
12MELJUN P. CORTES
Java CommentsJava Comments
C++-Style Comments C++-Style Comments C++ Style comments starts with //C++ Style comments starts with // All the text after // are treated as commentsAll the text after // are treated as comments For example:For example: // This is a C++ style or single // This is a C++ style or single line comments line comments
13MELJUN P. CORTES
Java CommentsJava Comments
C-Style Comments C-Style Comments C-style comments or also called multiline C-style comments or also called multiline
comments starts with a /* and ends with a comments starts with a /* and ends with a */. */.
All text in between the two delimeters are All text in between the two delimeters are treated as comments.treated as comments.
Unlike C++ style comments, it can span Unlike C++ style comments, it can span multiple lines.multiple lines.
For example:For example: /* this is an exmaple of a /* this is an exmaple of a C style or multiline comments */ C style or multiline comments */
14MELJUN P. CORTES
Java CommentsJava Comments
Javadoc Comments Javadoc Comments Javadoc comments are used for generating Javadoc comments are used for generating
an HTML documentation for your Java an HTML documentation for your Java programs. programs.
You can create javadoc comments by starting You can create javadoc comments by starting the line with /** and ending it with */. the line with /** and ending it with */.
/** /** This is an example of special java docThis is an example of special java doccomments used for \n generating an htmlcomments used for \n generating an html
documentation. It uses tags like: documentation. It uses tags like: @author Florence Balagtas @author Florence Balagtas @version 1.2 @version 1.2
*/*/ 15MELJUN P. CORTES
Java StatementsJava Statements
Statement Statement one or more lines of code terminated by a one or more lines of code terminated by a
semicolon. semicolon.
System.out.println(“Hello world”); System.out.println(“Hello world”);
16MELJUN P. CORTES
Java BlocksJava Blocks BlockBlock
is one or more statements bounded by an is one or more statements bounded by an opening and closing curly braces that opening and closing curly braces that groups the statements as one unit. groups the statements as one unit.
Block statements can be nested Block statements can be nested indefinitely. indefinitely.
Any amount of white space is allowed. Any amount of white space is allowed.
public static void main(String[] args ){public static void main(String[] args ){System.out.println("Hello"); System.out.println("Hello"); System.out.println("world”);System.out.println("world”);
}} 17MELJUN P. CORTES
Java Statements and BlocksJava Statements and BlocksBest PracticeBest Practice
You should indent the next statements four You should indent the next statements four spaces after the start of a block. For spaces after the start of a block. For example:example:
public static void main(String[] args ){public static void main(String[] args ){ System.out.println("Hello");System.out.println("Hello"); System.out.println("world"); System.out.println("world"); } }
18MELJUN P. CORTES
Java IdentifiersJava Identifiers
Identifiers Identifiers are tokens that represent names of are tokens that represent names of
variables, methods, classes, etc.variables, methods, classes, etc. Examples of identifiers are: Hello, main, Examples of identifiers are: Hello, main,
System, out. System, out.
Java identifiers are case-sensitive. Java identifiers are case-sensitive. This means that the identifier Hello is not This means that the identifier Hello is not
the same as hello.the same as hello.
19MELJUN P. CORTES
Java IdentifiersJava Identifiers
Identifiers must begin with either a letter, Identifiers must begin with either a letter, an underscore “_”, or a dollar sign “$”. an underscore “_”, or a dollar sign “$”. Letters may be lower or upper case. Letters may be lower or upper case. Subsequent characters may use numbers 0 Subsequent characters may use numbers 0 to 9. to 9.
Identifiers cannot use Java keywords like Identifiers cannot use Java keywords like class, public, void, etc. We will discuss class, public, void, etc. We will discuss more about Java keywords later. more about Java keywords later.
20MELJUN P. CORTES
Java IdentifiersJava IdentifiersBest PracticeBest Practice
1. For names of classes, capitalize the first letter of the 1. For names of classes, capitalize the first letter of the class name. For example, class name. For example,
ThisIsAnExampleOfClassName ThisIsAnExampleOfClassName
2. For names of methods and variables, the first letter of 2. For names of methods and variables, the first letter of the word should start with a small letter. For example,the word should start with a small letter. For example,
thisIsAnExampleOfMethodName thisIsAnExampleOfMethodName
21MELJUN P. CORTES
Java IdentifiersJava IdentifiersBest PracticeBest Practice
3. In case of multi-word identifiers, use capital 3. In case of multi-word identifiers, use capital letters to indicate the start of the word except letters to indicate the start of the word except the first word. For example, the first word. For example,
charArray, fileNumber, ClassName. charArray, fileNumber, ClassName.
4. Avoid using underscores at the start of the 4. Avoid using underscores at the start of the identifier such as _read or _write.identifier such as _read or _write.
22MELJUN P. CORTES
Java KeywordsJava Keywords
Keywords are predefined identifiers Keywords are predefined identifiers reserved by Java for a specific purpose. reserved by Java for a specific purpose.
You cannot use keywords as names for You cannot use keywords as names for your variables, classes, methods ... etc. your variables, classes, methods ... etc.
The next slide contains the list of the Java The next slide contains the list of the Java Keywords.Keywords.
23MELJUN P. CORTES
Java KeywordsJava Keywords
24MELJUN P. CORTES
Java LiteralsJava Literals
Literals are tokens that do not change - Literals are tokens that do not change - they are constant. they are constant.
The different types of literals in Java are: The different types of literals in Java are: Integer LiteralsInteger Literals Floating-Point LiteralsFloating-Point Literals Boolean LiteralsBoolean Literals Character LiteralsCharacter Literals String LiteralsString Literals
25MELJUN P. CORTES
Java Literals: Floating PointJava Literals: Floating Point
Represents decimals with fractional partsRepresents decimals with fractional parts Example: 3.1416Example: 3.1416
Can be expressed in standard or scientific Can be expressed in standard or scientific notationnotation Example: 583.45 (standard), 5.8345e2 Example: 583.45 (standard), 5.8345e2
(scientific)(scientific)
26MELJUN P. CORTES
Java Literals: BooleanJava Literals: Boolean
Boolean literals have only two values, true or Boolean literals have only two values, true or false. false.
27MELJUN P. CORTES
Java Literals: CharacterJava Literals: Character
Character Literals represent single Unicode Character Literals represent single Unicode characters. characters.
Unicode characterUnicode character a 16-bit character set that replaces the 8-bit a 16-bit character set that replaces the 8-bit
ASCII character set.ASCII character set. Unicode allows the inclusion of symbols Unicode allows the inclusion of symbols
and special characters from other and special characters from other languages.languages.
28MELJUN P. CORTES
Java Literals: CharacterJava Literals: Character
To use a character literal, enclose the To use a character literal, enclose the character in character in single quotesingle quote delimiters. delimiters.
For exampleFor example the letter a, is represented as ‘a’. the letter a, is represented as ‘a’. special characters such as a newline character, special characters such as a newline character,
a backslash is used followed by the character a backslash is used followed by the character code. For example, ‘\n’ for the newline code. For example, ‘\n’ for the newline character, ‘\r’ for the carriage return, ‘\b’ for character, ‘\r’ for the carriage return, ‘\b’ for backspace. backspace.
29MELJUN P. CORTES
Java Literals: CharacterJava Literals: Character
The following literals all refer to the same The following literals all refer to the same character:character:
char c = ‘P’;char c = ‘P’;
char d = 80;char d = 80;
char g = ‘\u0050’; char g = ‘\u0050’; hexadecimal hexadecimal
30MELJUN P. CORTES
Java Literals: StringJava Literals: String
String literals represent multiple characters String literals represent multiple characters and are enclosed by double quotes. and are enclosed by double quotes.
An example of a string literal is: An example of a string literal is:
““Hello World”Hello World”
31MELJUN P. CORTES
Primitive Data TypesPrimitive Data Types The Java programming language defines The Java programming language defines
eight primitive data types. eight primitive data types. boolean (for logical)boolean (for logical) char (for textual)char (for textual) bytebyte shortshort int int long (integral)long (integral) doubledouble float (floating point). float (floating point).
32MELJUN P. CORTES
Primitive Data Types: Logical-Primitive Data Types: Logical-booleanboolean
A boolean data type represents two states: A boolean data type represents two states: true and false.true and false.
An example is, An example is, boolean result = true; boolean result = true;
The example shown above, declares a The example shown above, declares a variable named result as boolean type and variable named result as boolean type and assigns it a value of true. assigns it a value of true.
33MELJUN P. CORTES
Primitive Data Types: Textual-Primitive Data Types: Textual-charchar A character data type (char), represents a single A character data type (char), represents a single
Unicode character. Unicode character. It must have its literal enclosed in single quotes(’ ’). It must have its literal enclosed in single quotes(’ ’). For example,For example,
‘a’ //The letter a ‘a’ //The letter a ‘\t’ //A tab ‘\t’ //A tab
To represent special characters like ' (single quotes) To represent special characters like ' (single quotes) or " (double quotes), use the escape character \. or " (double quotes), use the escape character \. For example,For example,
'\'' //for single quotes '\'' //for single quotes '\"' //for double quotes '\"' //for double quotes
34MELJUN P. CORTES
Primitive Data Types: Textual-Primitive Data Types: Textual-charchar
Although, String is not a primitive data type (it is a Although, String is not a primitive data type (it is a Class), we will just introduce String in this section. Class), we will just introduce String in this section.
A String represents a data type that contains A String represents a data type that contains multiple characters. It is not a primitive data type, it multiple characters. It is not a primitive data type, it is a class. is a class.
It has its literal enclosed in double quotes(“”). It has its literal enclosed in double quotes(“”).
For example, For example, String message = “Hello world!”; String message = “Hello world!”;
35MELJUN P. CORTES
Primitive Data Types: Integral – Primitive Data Types: Integral – byte, short, int & long byte, short, int & long
Integral data types in Java uses three forms – decimal, octal Integral data types in Java uses three forms – decimal, octal or hexadecimal. or hexadecimal. 2 //The decimal value 2 2 //The decimal value 2 077 //The leading 0 indicates an octal value 077 //The leading 0 indicates an octal value 0xBACC //The leading 0x indicates a hex value0xBACC //The leading 0x indicates a hex value
Integral types has int as default data type. Integral types has int as default data type. You can define its long value by appending the letter l or L:You can define its long value by appending the letter l or L:
10L 10L
36MELJUN P. CORTES
Primitive Data Types: Integral – Primitive Data Types: Integral – byte, short, int & longbyte, short, int & long
Integral data type have the following Integral data type have the following ranges: ranges:
37MELJUN P. CORTES
Primitive Data Types: Floating Primitive Data Types: Floating Point – float and doublePoint – float and double Floating point types has double as default data type.Floating point types has double as default data type. Floating-point literal includes either a decimal point or Floating-point literal includes either a decimal point or
one of the following, one of the following, E or e //(add exponential value) E or e //(add exponential value) F or f //(float) F or f //(float) D or d //(double) D or d //(double)
Examples:Examples:3.14 //A simple floating-point value (a double)3.14 //A simple floating-point value (a double)6.02E23 //A large floating-point value 6.02E23 //A large floating-point value 2.718F 2.718F //A simple float size value //A simple float size value 123.4E+306D//A large double value with redundant 123.4E+306D//A large double value with redundant
DD
38MELJUN P. CORTES
Primitive Data Types: Floating Primitive Data Types: Floating Point – float and double Point – float and double
Floating-point data types have the following Floating-point data types have the following ranges: ranges:
39MELJUN P. CORTES
CastingCasting
Among integral types, casting is implicit if from Among integral types, casting is implicit if from narrow to wide:narrow to wide:
byte b; short s; int i; long l;byte b; short s; int i; long l;
s = b;s = b;
i = b;i = b;
i = s;i = s;
l = i;l = i;
l = s;l = s;
40MELJUN P. CORTES
CastingCasting
Among integral types, casting is implicit if from Among integral types, casting is implicit if from narrow to wide:narrow to wide:
byte b; short s; int i; long l;byte b; short s; int i; long l;
b = l;b = l;
s = i;s = i;
b = i;b = i;
b = s;b = s;
s = l; s = l;
41MELJUN P. CORTES
CastingCasting
Casting to a more narrow datatype requires an Casting to a more narrow datatype requires an explicit cast. Initial bits will be dropped.explicit cast. Initial bits will be dropped.
byte b; short s; int i; long l;byte b; short s; int i; long l;
b = (byte) l;b = (byte) l;
s = (short) i;s = (short) i;
b = (byte) i;b = (byte) i;
b = (byte) s;b = (byte) s;
s = (short) l; s = (short) l;
42MELJUN P. CORTES
CastingCasting
Similar rules for floating-point primitives:Similar rules for floating-point primitives:
float f; double d;float f; double d;
d = f;d = f;
f = d;f = d;
f = (double) d;f = (double) d;
43MELJUN P. CORTES
CastingCasting
Integral types can be implicitly cast to floating-Integral types can be implicitly cast to floating-point types.point types.
byte b; short s; int i; long l; float f; double d;byte b; short s; int i; long l; float f; double d;
f = l;f = l;
f = i;f = i;
d = i;d = i;
d = b;d = b;
d = s;d = s;
44MELJUN P. CORTES
CastingCasting
If a floating-point is cast to an integral, If a floating-point is cast to an integral, digits after the decimal-point are dropped:digits after the decimal-point are dropped:
double d = 4.7;double d = 4.7;
int i = (int) d;int i = (int) d;
value of i: 4value of i: 4
45MELJUN P. CORTES
CastingCasting
char can be implicitly cast to int, long or char can be implicitly cast to int, long or floating-point typesfloating-point types
char c;char c;
int i = c;int i = c;
float f = c;float f = c;
short s = c;short s = c;
short s = (short) c;short s = (short) c;
46MELJUN P. CORTES
CastingCasting
booleans cannot be cast to any other datatypebooleans cannot be cast to any other datatype
boolean b;boolean b;
int i = b;int i = b;
int j = (int) b;int j = (int) b;
double d = (double) b;double d = (double) b;
short s = (short) b;short s = (short) b;
47MELJUN P. CORTES
VariablesVariables
A variable is an item of data used to store A variable is an item of data used to store the state of objects. the state of objects.
A variable has a:A variable has a: data typedata type
The data type indicates the type of value that the variable can hold.
name name The variable name must follow rules for
identifiers.
48MELJUN P. CORTES
Declaring and Initializing Declaring and Initializing VariablesVariables
Declare a variable as follows:Declare a variable as follows:
<data type> <name> [=initial value];<data type> <name> [=initial value];
Note: Values enclosed in <> are required Note: Values enclosed in <> are required values, while those values in [] are values, while those values in [] are optional.optional.
49MELJUN P. CORTES
Declaring and Initializing Variables: Declaring and Initializing Variables: Sample ProgramSample Program
1 public class VariableSamples { 2 public static void main( String[] args ){ 3 //declare a data type with variable name
4 // result and boolean data type 5 boolean result;
6 //declare a data type with variable name
7 // option and char data type 8 char option; 9 option = 'C'; //assign 'C' to option
10 //declare a data type with variable name
11 //grade, double data type and initialized
12 //to 0.0 13 double grade = 0.0; 14 }15 }
50MELJUN P. CORTES
Declaring and Initializing Declaring and Initializing Variables: Best PracticeVariables: Best Practice
1. It always good to initialize your variables 1. It always good to initialize your variables as you declare them. as you declare them.
2. Use descriptive names for your variables. 2. Use descriptive names for your variables. Like for example, if you want to have a Like for example, if you want to have a variable that contains a grade for a student, variable that contains a grade for a student, name it as, grade and not just some name it as, grade and not just some random letters you choose. random letters you choose.
51MELJUN P. CORTES
Declaring and Initializing Declaring and Initializing Variables: Best PracticeVariables: Best Practice
3. Declare one variable per line of code. For 3. Declare one variable per line of code. For example, the variable declarations, example, the variable declarations,
double exam=0; double exam=0; double quiz=10; double quiz=10; double grade = 0; double grade = 0;
is preferred over the declaration, is preferred over the declaration,
double exam=0, quiz=10, grade=0; double exam=0, quiz=10, grade=0;
52MELJUN P. CORTES
Scope of a VariableScope of a Variable
The scope The scope determines where in the program the variable is determines where in the program the variable is
accessible. accessible. determines the lifetime of a variable or how long the determines the lifetime of a variable or how long the
variable can exist in memory. variable can exist in memory. The scope is determined by where the variable The scope is determined by where the variable
declaration is placed in the program. declaration is placed in the program.
To simplify things, just think of the scope as anything To simplify things, just think of the scope as anything between the curly braces {...}. The outer curly braces between the curly braces {...}. The outer curly braces are called the outer blocks, and the inner curly braces are called the outer blocks, and the inner curly braces are called inner blocks. are called inner blocks.
53MELJUN P. CORTES
Scope of a VariableScope of a Variable
A variable's scope is A variable's scope is inside the block where it is declared, inside the block where it is declared,
starting from the point where it is declared, starting from the point where it is declared, and in the inner blocks. and in the inner blocks.
54MELJUN P. CORTES
Example 1Example 1
55MELJUN P. CORTES
Example 1Example 1
The code we have here represents five scopes The code we have here represents five scopes indicated by the lines and the letters representing the indicated by the lines and the letters representing the scope. scope.
Given the variables i,j,k,m and n, and the five scopes 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 A,B,C,D and E, we have the following scopes for each variable: variable: The scope of variable i is A. The scope of variable i is A. The scope of variable j is B. The scope of variable j is B. The scope of variable k is C. The scope of variable k is C. The scope of variable m is D. The scope of variable m is D. The scope of variable n is E. The scope of variable n is E.
56MELJUN P. CORTES
Example 2Example 2
57MELJUN P. CORTES
Example 2Example 2 In the main method, the scopes of the In the main method, the scopes of the
variables are, variables are, ages[] - scope A ages[] - scope A i in B - scope Bi in B - scope B i in C – scope C i in C – scope C
In the test method, the scopes of the In the test method, the scopes of the variables are, variables are, arr[] - scope D arr[] - scope D i in E - scope E i in E - scope E
58MELJUN P. CORTES
Scope of a VariableScope of a Variable
When declaring variables, only one variable with a given When declaring variables, only one variable with a given identifier or name can be declared in a scope. identifier or name can be declared in a scope.
That means that if you have the following declaration, That means that if you have the following declaration,
{ { int test = 10; int test = 10; int test = 20; int test = 20;
} }
your compiler will generate an error since you should your compiler will generate an error since you should have unique names for your variables in one block.have unique names for your variables in one block.
59MELJUN P. CORTES
Scope of a VariableScope of a Variable
However, you can have two variables of the However, you can have two variables of the same name, if they are not declared in the same name, if they are not declared in the same block. For examplesame block. For example, ,
int test = 0; System.out.print( test ); //..some code here {
int test = 20; System.out.print( test );
}
60MELJUN P. CORTES
Outputting Variable DataOutputting Variable Data
In order to output the value of a certain In order to output the value of a certain variable, we can use the following variable, we can use the following commands:commands:System.out.println() System.out.println() System.out.print() System.out.print()
61MELJUN P. CORTES
Outputting Variable Data: Outputting Variable Data: Sample Program Sample Program 1 public class OutputVariable {2 public static void main( String[] args ){3 int value = 10;4 char x;5 x = ‘A’;
6 System.out.println( value );7 System.out.println( “The value of x=“ + x );8 }9 }
The program will output the following text on screen:
10The value of x=A
62MELJUN P. CORTES
System.out.println() vs. System.out.println() vs. System.out.print()System.out.print()
System.out.println()System.out.println() Appends a newline at the end of the data Appends a newline at the end of the data
outputoutput
System.out.print() System.out.print() Does not append newline at the end of the Does not append newline at the end of the
data outputdata output
63MELJUN P. CORTES
Program 1:Program 1:
Output:Output:HelloWorldHelloWorld
Program 2:Program 2:
Output:Output:HelloHelloWorldWorld
System.out.println() vs. System.out.println() vs. System.out.print() ExamplesSystem.out.print() Examples
System.out.print(“Hello”);System.out.print(“World”);
System.out.println(“Hello”);System.out.println(“World”);
64MELJUN P. CORTES
Reference Variables vs. Reference Variables vs. Primitive VariablesPrimitive Variables Two types of variables in Java:Two types of variables in Java:
Primitive VariablesPrimitive Variables Reference VariablesReference Variables
Primitive VariablesPrimitive Variables variables with primitive data types such as variables with primitive data types such as
int or long. int or long. stores data in the actual memory location of stores data in the actual memory location of
where the variable iswhere the variable is
65MELJUN P. CORTES
Reference Variables vs. Reference Variables vs. Primitive VariablesPrimitive Variables
Reference VariablesReference Variables variables that stores the address in the variables that stores the address in the
memory locationmemory location points to another memory location where points to another memory location where
the actual data isthe actual data is When you declare a variable of a certain When you declare a variable of a certain
class, you are actually declaring a reference class, you are actually declaring a reference variable to the object with that certain variable to the object with that certain classclass. .
66MELJUN P. CORTES
ExampleExample
Suppose we have two variables with data Suppose we have two variables with data types int and String. types int and String.
int num = 10; // primitive typeint num = 10; // primitive type
String name = "Hello"; // reference type String name = "Hello"; // reference type
67MELJUN P. CORTES
ExampleExample
The picture shown below is the actual The picture shown below is the actual memory of your computer, wherein you memory of your computer, wherein you have the address of the memory cells, the have the address of the memory cells, the variable name and the data they hold.variable name and the data they hold.
68MELJUN P. CORTES
OperatorsOperators Different types of operatorsDifferent types of operators::
arithmetic operatorsarithmetic operators relational operatorsrelational operators logical operatorslogical operators conditional operatorsconditional operators
These operators follow a certain kind of These operators follow a certain kind of precedence so that the compiler will know precedence so that the compiler will know which operator to evaluate first in case which operator to evaluate first in case multiple operators are used in one statement. multiple operators are used in one statement.
69MELJUN P. CORTES
Arithmetic OperatorsArithmetic Operators
70MELJUN P. CORTES
Arithmetic Operators: Arithmetic Operators: Sample ProgramSample Program1 public class ArithmeticDemo {2 public static void main(String[] args){3 //a few numbers4 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));
71MELJUN P. CORTES
Arithmetic Operators: Arithmetic Operators: Sample ProgramSample Program
15 //subtracting numbers16 System.out.println("Subtracting...");17 System.out.println(" i - j = " + (i – j));18 System.out.println(" x - y = " + (x – y));
19 //multiplying numbers20 System.out.println("Multiplying...");21 System.out.println(" i * j = " + (i * j));22 System.out.println(" x * y = " + (x * y));
23 //dividing numbers24 System.out.println("Dividing...");25 System.out.println(" i / j = " + (i / j));26 System.out.println(" x / y = " + (x / y));
72MELJUN P. CORTES
Arithmetic Operators: Arithmetic Operators: Sample ProgramSample Program
29 //computing the remainder resulting from dividing30 // numbers31 System.out.println("Computing the remainder...");32 System.out.println(" i % j = " + (i % j));33 System.out.println(" x % y = " + (x % y));
34 //mixing types35 System.out.println("Mixing types...");36 System.out.println(" j + y = " + (j + y));37 System.out.println(" i * x = " + (i * x));38 } 39}
73MELJUN P. CORTES
Arithmetic Operators: Arithmetic Operators: Sample Program OutputSample 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
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
74MELJUN P. CORTES
Pop QuizPop Quiz
What is the result of writing this code:What is the result of writing this code:
byte x = 4;
byte y = 3;
byte z = x * y;
75MELJUN P. CORTES
Pop QuizPop Quiz
What is the result of writing this code:What is the result of writing this code:
byte x = 4;
byte y = 3;
byte z = x * y;
Will not compile!
76MELJUN P. CORTES
Arithmetic OperatorsArithmetic Operators
byte, short and char get automatically byte, short and char get automatically promoted to int before any arithmetic promoted to int before any arithmetic operation.operation.
byte x = 4;
byte y = 3;
byte z = (byte) (x + y);
77MELJUN P. CORTES
Arithmetic OperatorsArithmetic Operators
In mixed expressions, all participants get In mixed expressions, all participants get promoted to datatype of widest participantpromoted to datatype of widest participant
Floating point numbers are always Floating point numbers are always considered “wider” than integralconsidered “wider” than integrals.s.
byte b; short s; int i; float f;byte b; short s; int i; float f;
b + s * i - f b + s * i - f all promoted to float all promoted to float
78MELJUN P. CORTES
Increment and Decrement Increment and Decrement Operators Operators
unary increment operator (++) unary increment operator (++) unary decrement operator (--)unary decrement operator (--) Increment and decrement operators increase Increment and decrement operators increase
and decrease a value stored in a number and decrease a value stored in a number variable by 1. variable by 1.
For example, the expression, For example, the expression, count = count + 1;count = count + 1;
//increment the value of count by 1 //increment the value of count by 1
is equivalent to, is equivalent to, count++; count++;
79MELJUN P. CORTES
Increment and Decrement Increment and Decrement Operators Operators
80MELJUN P. CORTES
Increment and Decrement Increment and Decrement Operators Operators The increment and decrement operators can The increment and decrement operators can
be placed before or after an operand. be placed before or after an operand. When used before an operand, it causes the When used before an operand, it causes the
variable to be incremented or decremented by variable to be incremented or decremented by 1, and then the new value is used in the 1, and then the new value is used in the expression in which it appearsexpression in which it appears. .
int i = 10; int j = 3; int k = 0; k = ++j + i; //will result to k = 4+10 = 14
81MELJUN P. CORTES
Increment and Decrement Increment and Decrement Operators Operators
When the increment and decrement When the increment and decrement operators are placed after the operand, the operators are placed after the operand, the old value of the variable will be used in the old value of the variable will be used in the expression where it appears. expression where it appears.
int i = 10;int j = 3; int k = 0; k = j++ + i; //will result to k = 3+10 = 13
82MELJUN P. CORTES
Increment and Decrement Increment and Decrement Operators: Best PracticeOperators: Best Practice
Always keep expressions containing Always keep expressions containing increment and decrement operators simple increment and decrement operators simple and easy to understand. and easy to understand.
83MELJUN P. CORTES
Relational OperatorsRelational Operators
Relational operators compare two values and determines Relational operators compare two values and determines the relationship between those values. the relationship between those values.
The output of evaluation are the boolean values true or The output of evaluation are the boolean values true or false.false.
84MELJUN P. CORTES
Relational Operators: Relational Operators: Sample ProgramSample Program
1 public class RelationalDemo{2 public static void main(String[] args){3 //a few numbers4 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 than12 System.out.println("Greater than...");13 System.out.println(" i > j = "+(i>j));//false14 System.out.println(" j > i = "+(j>i));//true15 System.out.println(" k > j = "+(k>j));//false
85MELJUN P. CORTES
Relational Operators: Relational Operators: Sample ProgramSample Program
16 //greater than or equal to17 System.out.println("Greater than or equal to...");18 System.out.println(" i >= j = "+(i>=j));//false19 System.out.println(" j >= i = "+(j>=i));//true20 System.out.println(" k >= j = "+(k>=j));//true21 //less than22 System.out.println("Less than...");23 System.out.println(" i < j = "+(i<j));//true24 System.out.println(" j < i = "+(j<i));//false25 System.out.println(" k < j = "+(k<j));//false26 //less than or equal to27 System.out.println("Less than or equal to...");28 System.out.println(" i <= j = "+(i<=j));//true29 System.out.println(" j <= i = "+(j<=i));//false30 System.out.println(" k <= j = "+(k<=j));//true
86MELJUN P. CORTES
Relational Operators: Relational Operators: Sample ProgramSample Program
31 //equal to32 System.out.println("Equal to...");33 System.out.println(" i == j = " + (i==j));//false34 System.out.println(" k == j = " + (k==j));//true 35 //not equal to36 System.out.println("Not equal to...");37 System.out.println(" i != j = " + (i!=j));//true38 System.out.println(" k != j = " + (k!=j));//false39 }40 }
87MELJUN P. CORTES
Relational Operators: Relational Operators: Sample Program OutputSample 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
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
88MELJUN P. CORTES
Logical OperatorsLogical Operators
Logical operators have one or two boolean Logical operators have one or two boolean operands that yield a boolean result. operands that yield a boolean result.
There are six logical operators:There are six logical operators: && (logical AND)&& (logical AND) & (boolean logical AND)& (boolean logical AND) || (logical OR)|| (logical OR) | (boolean logical inclusive OR)| (boolean logical inclusive OR) ^ (boolean logical exclusive OR)^ (boolean logical exclusive OR) ! (logical NOT)! (logical NOT)
89MELJUN P. CORTES
Logical OperatorsLogical Operators The basic expression for a logical operation The basic expression for a logical operation
is, is, x1 op x2 x1 op x2
where,where,x1, x2 - can be boolean expressions, variables x1, x2 - can be boolean expressions, variables or constantsor constantsop - is either &&, &, ||, | or ^ operator. op - is either &&, &, ||, | or ^ operator.
The truth tables that will be shown next, The truth tables that will be shown next, summarize the result of each operation for all summarize the result of each operation for all possible combinations of x1 and x2. possible combinations of x1 and x2.
90MELJUN P. CORTES
Here is the truth table for && and &,Here is the truth table for && and &,
Logical Operators: &&(logical) Logical Operators: &&(logical) and &(boolean logical) ANDand &(boolean logical) AND
91MELJUN P. CORTES
The basic difference between && and & operators :The basic difference between && and & operators : && supports short-circuit evaluations (or partial && supports short-circuit evaluations (or partial
evaluations), while & doesn't. evaluations), while & doesn't.
Given an expression:Given an expression:exp1 && exp2 exp1 && exp2
&& will evaluate the expression exp1, and immediately && will evaluate the expression exp1, and immediately return a false value is exp1 is false. return a false value is exp1 is false.
If exp1 is false, the operator never evaluates exp2 If exp1 is false, the operator never evaluates exp2 because the result of the operator will be false because the result of the operator will be false regardless of the value of exp2. regardless of the value of exp2.
In contrast, the & operator always evaluates both In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer.exp1 and exp2 before returning an answer.
Logical Operators: &&(logical) Logical Operators: &&(logical) and &(boolean logical) ANDand &(boolean logical) AND
92MELJUN P. CORTES
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 }
Logical Operators: &&(logical) and Logical Operators: &&(logical) and &(boolean logical) AND&(boolean logical) AND
93MELJUN P. CORTES
The output of the program is, The output of the program is, 0 0 10 10 false false 0 0 11 11 false false
Note, that the j++ on the line containing the Note, that the j++ on the line containing the && operator is not evaluated since the first && operator is not evaluated since the first expression (i>10) is already equal to falseexpression (i>10) is already equal to false. .
Logical Operators: &&(logical) and Logical Operators: &&(logical) and &(boolean logical) AND&(boolean logical) AND
94MELJUN P. CORTES
Logical Operators: || (logical) and | Logical Operators: || (logical) and | (boolean logical) inclusive OR (boolean logical) inclusive OR
Here is the truth table for || and |,Here is the truth table for || and |,
95MELJUN P. CORTES
The basic difference between || and I operators :The basic difference between || and I operators : || supports short-circuit evaluations (or partial || supports short-circuit evaluations (or partial
evaluations), while | doesn't.evaluations), while | doesn't. Given an expression:Given an expression:
exp1 || exp2 exp1 || exp2 || will evaluate the expression exp1, and immediately || will evaluate the expression exp1, and immediately
return a true value is exp1 is truereturn a true value is exp1 is true If exp1 is true, the operator never evaluates exp2 If exp1 is true, the operator never evaluates exp2
because the result of the operator will be true regardless because the result of the operator will be true regardless of the value of exp2.of the value of exp2.
In contrast, the | operator always evaluates both exp1 In contrast, the | operator always evaluates both exp1 and exp2 before returning an answer. and exp2 before returning an answer.
Logical Operators: || (logical) and | Logical Operators: || (logical) and | (boolean logical) inclusive OR (boolean logical) inclusive OR
96MELJUN P. CORTES
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 }
Logical Operators: || (logical) and | Logical Operators: || (logical) and | (boolean logical) inclusive OR (boolean logical) inclusive OR
97MELJUN P. CORTES
The output of the program is,The output of the program is, 0 0 10 10 true true 0 0 11 11 true true
Note, that the j++ on the line containing the || Note, that the j++ on the line containing the || operator is not evaluated since the first operator is not evaluated since the first expression (i<10) is already equal to true. expression (i<10) is already equal to true.
Logical Operators: || (logical) and | Logical Operators: || (logical) and | (boolean logical) inclusive OR (boolean logical) inclusive OR
98MELJUN P. CORTES
Logical Operators: ^ (boolean Logical Operators: ^ (boolean logical exclusive OR) logical exclusive OR)
Here is the truth table for ^, Here is the truth table for ^,
The result of an exclusive OR operation is TRUE, if and only The result of an exclusive OR operation is TRUE, if and only if one operand is true and the other is false. if one operand is true and the other is false.
Note that both operands must always be evaluated in order Note that both operands must always be evaluated in order to calculate the result of an exclusive OR. to calculate the result of an exclusive OR.
99MELJUN P. CORTES
Logical Operators: ^ (boolean Logical Operators: ^ (boolean logical exclusive OR)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 }
100MELJUN P. CORTES
The output of the program is, The output of the program is, false false true true false false true true
Logical Operators: ^ (boolean Logical Operators: ^ (boolean logical exclusive OR)logical exclusive OR)
101MELJUN P. CORTES
Logical Operators: ! Logical Operators: ! (logical NOT)(logical NOT)
The logical NOT takes in one argument, The logical NOT takes in one argument, wherein that argument can be an wherein that argument can be an expression, variable or constant.expression, variable or constant.
Here is the truth table for !,Here is the truth table for !,
102MELJUN P. CORTES
Logical Operators: ! Logical Operators: ! (logical NOT)(logical NOT)
1 public class TestNOT {2 public static void main( String[] args ){3 boolean val1 = true;4 boolean val2 = false;5 System.out.println(!val1);6 System.out.println(!val2);7 } 8 }
The output of the program is, The output of the program is, false false true true
103MELJUN P. CORTES
Logical Operators: Conditional Logical Operators: Conditional Operator (?:)Operator (?:) The conditional operator ?: The conditional operator ?:
is a ternary 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 isThe structure of an expression using a conditional operator is
exp1?exp2:exp3 exp1?exp2:exp3
wherein,
exp1 - is a boolean expression whose result must either be true or false
Result:Result:
If exp1 is true, exp2 is the value returned.
If it is false, then exp3 is returned.
104MELJUN P. CORTES
Logical Operators: Logical Operators: Conditional Operator (?:)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 student6 status = (grade >= 60)?"Passed":"Fail";7 //print status8 System.out.println( status );9 }10 }
The output of this program will be, The output of this program will be, Passed Passed
105MELJUN P. CORTES
Logical Operators: Conditional Logical Operators: Conditional Operator (?:)Operator (?:)
106MELJUN P. CORTES
Operator PrecedenceOperator Precedence
107MELJUN P. CORTES
Operator PrecedenceOperator Precedence
Given a complicated expression, Given a complicated expression,
6%2*5+4/2+88-10 6%2*5+4/2+88-10
we can re-write the expression and place we can re-write the expression and place some parenthesis base on operator some parenthesis base on operator precedence, precedence,
((6%2)*5)+(4/2)+88-10; ((6%2)*5)+(4/2)+88-10;
108MELJUN P. CORTES
Operator Precedence: Best Operator Precedence: Best PracticePractice
To avoid confusion in evaluating To avoid confusion in evaluating mathematical operations, keep your mathematical operations, keep your expressions simple and use parenthesesexpressions simple and use parentheses. .
109MELJUN P. CORTES
SummarySummary Java Comments (C++-Style Comments, C-Java Comments (C++-Style Comments, C-
Style Comments, Special Javadoc Style Comments, Special Javadoc Comments)Comments)
Java statements, blocks, identifiers, Java statements, blocks, identifiers, keywordskeywords
Java Literals (integer, floating point, boolean, Java Literals (integer, floating point, boolean, character, String)character, String)
Primitive data types( boolean, char, byte, Primitive data types( boolean, char, byte, short, int, long, float, double)short, int, long, float, double)
CastingCasting
110MELJUN P. CORTES
SummarySummary
Variables (declare, initialize, output)Variables (declare, initialize, output) Scope of a variableScope of a variable System.out.println() vs. System.out.print()System.out.println() vs. System.out.print() Reference Variables vs. Primitive VariablesReference Variables vs. Primitive Variables Operators (Arithmetic operators, Increment Operators (Arithmetic operators, Increment
and Decrement operators, Relational and Decrement operators, Relational operators, Logical operators, Conditional operators, Logical operators, Conditional Operator (?:), Operator Precedence)Operator (?:), Operator Precedence)
111MELJUN P. CORTES