0% found this document useful (0 votes)
30 views

Java Lecture

This document provides an overview of key concepts in Java including: - What Java is and its main components like the Java Virtual Machine and Java Runtime Environment - Features of Java like garbage collection and code security - Java terminology such as JDK, JRE, IDE, and packages - Different types of comments in Java code - Java statements, blocks, identifiers, keywords, and literals - Primitive data types in Java including boolean, char, integers, and floating-point numbers - How to declare and initialize variables, output variable data, and the difference between reference and primitive variables - Common operators in Java like arithmetic, relational, increment/decrement, and logical operators

Uploaded by

Joshua Silva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Java Lecture

This document provides an overview of key concepts in Java including: - What Java is and its main components like the Java Virtual Machine and Java Runtime Environment - Features of Java like garbage collection and code security - Java terminology such as JDK, JRE, IDE, and packages - Different types of comments in Java code - Java statements, blocks, identifiers, keywords, and literals - Primitive data types in Java including boolean, char, integers, and floating-point numbers - How to declare and initialize variables, output variable data, and the difference between reference and primitive variables - Common operators in Java like arithmetic, relational, increment/decrement, and logical operators

Uploaded by

Joshua Silva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

JAVA LECTURE

What is Java?
 Java is created in 1991 by James Gosling et al. of Sun
Microsystem
 What is Java Technology?
A programming language
A development environment
An application Environment
Features of Java
Java Virtual Machine
An imaginary machine that is implemented by emulating
software on a real machine. The JVM provides the
hardware platform specifications to which you compile all
Java technology code
Features of Java
Garbage Collection
The garbage collection thread is responsible for freeing any
memory that can be freed. This happens automatically
during the lifetime of Java programs.
Features of Java
Code Security
The code security is attained in Java through the
implementation of its Java Runtime Environment (JRE). The
JRE runs code compiled for a JVM and performs class
loading through the class loader, code verification and
finally code execution.
Java Terminologies
JDK
Allow Developer to Create Java programs that
can be executed by Java Run time
Environment (JRE)
Java Terminologies
JRE
It is supplied by the Java 2 Software development Kit
(SDK) contains the complete set of class files for all
Java technology packages, which includes basic
languages classes, GUI component classes and so
on.
Java Terminologies
IDE
A software used by a developer so
they can easily code in a certain
programming language, IDE has
tons of features that makes
programming easier
Java Terminologies
Packages
This is like a folder in a directory where we can throw our related
codes in the same directory.
Java Comments
Comments are notes written to a code for documentation purposes.
Three types of comments:
 C++ style comments – known as a single line comments. Its starts with //. All text after
// are treated as comments.

//This is a C++ style or single line comments

C-style comments – also called a multiline comments starts with a /* and


ends with */
/*
this is an example of
multiline comments or c-style comments
*/
Java Comments
Special Javadoc Comments are use for generating HTML documentation for
java programs. The comments starts with /** and ending with */. Like c-style
comments it can span multiple lines.
/**
This is an example of a special Javadoc comments used for
generating an HTML documentation.
It uses tags like: @version 1.2
*/
Java statements and blocks
Statement is one or more lines of code terminated by semicolon.
System.out.println(“Hello World”);

Block is one or more statement bounded by an opening and closing


curly braces
{
System.out.println(“Hello ”);
System.out.println(“World”);
}
Java Identifiers
Identifiers are tokens that represent names of variables, method, classes, etc.

public class hello {


public static void main (String[] args) {
System.out.println (“Hello World”);
}
}

Examples: hello, main ,System.out


Java Keywords
Keywords are predefined identifiers reserved by Java for a specific
purpose.
You cannot use keywords as names for variables, classes or methods.

boolean float return try


byte goto short throws
catch implements int new
char imports super package
class privates while default
Java literals
Literals are tokens that do not change or are constant.
Types of Java literals:
Integer literals
Floating-point literals
Boolean literals
Character literals
String literals
Java literals
Integer comes in different formats: decimal (base of 10), hexadecimal (base of
16) and octal (base of 8).

For decimal numbers, we have no special notations. We just a decimal number


as it is . For hexadecimal numbers, it should precede by “0x” or “0X”. For
octals, they are precede by “0”.

For example, consider the number 12. Its decimal representation is 12, while in
hexadecimal, it is 0xC, and in octal, it is equivalent to 014. it is default to the
data type of int which have 32 bit value.
Java literals
Floating-point literals represent decimals with fractional parts. It can be
expressed in a standard or scientific notations.
For example, 583.45 is in standard notation, while 5.8345e2 is in scientific
notations.
Floating-point literals default to the data type double which has 64-bit value. To
use a smaller precision 32-bit float just append “f” or “F” character.

Boolean literals have only two value, true or false.


Java literals
Character literals represent a single Unicode character. A Unicode character is
a 16-bit character set that replaces the 8-bit ASCII character set.
To use a character literal, enclose the character in a single quote delimiters.
For examples the letter a, is represented as ‘a’.
To use special characters such as a newline character, a backslash is used
followed by the character code. For example, ‘\n’ for newline character, ‘\r’ for
the carriage return, ‘\b’ for backspace.
String literals represent multiple characters and are enclosed by double
quotes. For example “Hello World”
Primitive data types
Eight Java primitive data types:
Logical
Boolean data type represents two states: true or false
Textual
character (char) represent a single Unicode character enclosed in a
double quote.
String represent a data type that contains multiple character. It is a
primitive data type but a class
Primitive data types
Integral
 have three forms – decimal, octal and hex
 has int as a default data type.

Integer length Name or Type Range


8 bits Byte -27 to 27-1
16 bits Short -215 to 215-1
32 bits Int -231 to 231-1
64 bits long -263 to 263-1

Floating-point
float -32 bits
double -64 bits
Check Your Understanding
1. Notes written for a code for documentation purposes
A. Comments
B. Block
C. Statement
D. Code
2. Also known as multiline comments
A. C++ style
B. C style
C. Javadoc
D. Block
Check Your Understanding
1. A delimiter for C++ style Comments
A. { }
B. /* */
C. /** */
D. //
2. Statements are terminated by _____ delimiter
A. :
B. [ ]
C. ?
D. ;
Check Your Understanding
1. Character literals are enclosed in _____ delimiters
A. { }
B. ‘ ‘
C. “ “
D. [ ]
2. Blocks are terminated by _____ delimiter
A. { }
B. [ ]
C. ?
D. ;
Check Your Understanding
1. String literals are enclosed in _____ delimiters
A. { }
B. ‘ ‘
C. “ “
D. [ ]
2. Primitive data types that holds decimals and fractional value
A. String and char
B. float and double
C. int and long
D. Boolean
Variables
Variables is an item of data used to store state of objects.

A variable has a data type and a name. The data type indicates the type of
value that a variable can hold. The variable names must follow the rules for
identifiers.
To Declare and Initialize Variables: Tips:
1. It is always good to initialize
<data type><name>[=initial value]; variables
2. Use descriptive name for
Note: Values enclosed in <> are required values, while those values enclosed in [] are optional. variables
3. Declare one variable per line
of code
Outputting Variable Data
System.out.print(); System.out.println();

Consider the statement: Consider the statement:

System.out.print(“Hello”); System.out.println(“Hello”);
System.out.print(“World”), System.out.println(“World”);

Output: Output:

Hello World Hello


World
Reference Variables vs Primitive Variables
Reference Variables Primitive Variables

Variables with primitive data types, Variables that stores the address in
they store data in the actual the memory location
memory location of where the It points to another memory location
variable is of where the actual data is.
Java Operators
Arithmetic Operators
Relational Operators
Increment and Decrement Operators
Logical Operators
Conditional Operators
Arithmetic Operators

Operator Use Description


+ op1 + op2 Adds op1 and op2
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op 2 Computes the remainder of
dividing op1 by op2
- op1 – op2 Subtracts op2 from op1
Check your understanding
Identify the appropriate variables for the following data
1. Grades
2. Names
3. Middle initial
4. Percentages
5. Any whole numbers
Evaluate the following equation and give the answer
1. 10 +2 /1
2. 3*2^2
3. 10%2-5
Increment and Decrement
Operator Use Description
++ op++ Increments op by 1; evaluates to the value of op
before it was incremented
++ ++op Increment op by 1; evaluates to the value of op
after it was incremented
-- op-- Decrements op by 1; evaluates to the value of op
before it was decremented

-- --op Decrements op by 1; evaluates to the value of op


after it was decremented
Increment and Decrement Operators
When used before an operand, it causes the variable to be incremented or
decremented by 1, and the new value will be used in the expression in which it
appears.
for example:
int i=10;
int j=3;
int k= 0;
k=++j + i;// will result to k=4+10=14
Increment and Decrement Operators
When used after an operand, the old value will be used in the expression in
which it appears.
for example:
int i=10;
int j=3;
int k= 0;
k=j++ + i;// will result to k=3+10=13
Check your Understanding
Evaluate the following code and determine its output:

int x=5; int x=6; int x=2;


int y=2; int y=2; int y=2;
int z=0; int z=0; int z=0;
z= y++ *x; z= ++x / y; z= Math.pow(x-- , y--);
System.out. println(z); System.out. println(z); System.out. println(z);
z= ++x / y++; z= ++x / y++;
z=y++ - x;
System.out.println(z); System.out.println(z);
System.out.println(z);
Relational Operators
Operator Use Description
> op1 > op2 op1 is greater than op 2
>= op1 > op2 op1 is greater than or equal to op2
< op < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 is equal to op2
!= op1 != op2 op1 is not equal to op2
Check your Understanding
Evaluate the following code and determine its output:

int x=5; int x=6; int x=2;


int y=2; int y=2; int y=2;
boolean z=true; boolean z=false;
boolean z=false;
z= ++x <= y; z= Math.pow(x-- , y--)
z= x != ++ y ; < (++y + x);
System.out. println(z); System.out. println(z); System.out. println(z);
z= ++x == y++; z= ++x >= y++;
z=++y > x;
System.out.println(z); System.out.println(z);
System.out.println(z);
Logical Operators (And)
&& (logical AND) and & (boolean logical AND)

The basic difference between && and & operators is that && support short-circuit evaluations (or
partial evaluations), while & doesn’t.

Syntax:
exp1 && exp2
exp1 & exp2

x1 x2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Check your Understanding
Evaluate the following code and determine its output:

int x=5; int x=6;


int y=2; int y=2;
int a =3; int a=2;
boolean z=false; boolean z=true;
z=( x > y) && (y <x); z= x+y != a+y && z;
System.out. println(z); System.out. println(z);
z=++y > x & ++x < y; z= (x+a)==(x+y) &(y<=a);
System.out.println(z); System.out.println(z);
Logical Operators (OR)
|| (logical OR) and | (boolean logical OR)

The basic difference between || and | operators is that | support short-circuit evaluations (or
partial evaluations), while | doesn’t.

Syntax:
exp1 || exp2
exp1 | exp2

x1 x2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Check your Understanding
Evaluate the following code and determine its output:

boolean a=false; int x=6;


boolean b=false; int y=2;
boolean c=true; int a=2;
boolean z=true; boolean z=true;
z=a ||b ; z= x+y != a+y || z;
System.out. println(z); System.out. println(z);
z=a | b | c; z= (x+a)==(x+y) |(y<=a);
System.out.println(z); System.out.println(z);
Logical Operators (OR)
^ (Boolean logical exclusive OR)

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.

Syntax:
exp1 ^ exp2

x1 x2 Result
TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Check your Understanding
Evaluate the following code and determine its output:

boolean a=true; int x=6;


boolean b=true; int y=2;
boolean c=true; int a=2;
boolean z=true; boolean z=true;
z=a ^b ; z= x+y != a+y ^ z;
System.out. println(z); System.out. println(z);
z=a ^ b ^c; z= (x+a)==(x+y) ^ (y<=a);
System.out.println(z); System.out.println(z);
Logical Operators (NOT)
!(logical NOT)

The logical NOT takes in one argument, wherein that argument can be an expression, variable or
constant.

Syntax:
!val1

x1 Result
TRUE FALSE
FALSE TRUE
Conditional Operators (?:)
The conditional operator ?: is a ternary operator. This means that it takes in three
arguments that together form a conditional expression.
Syntax:
exp1?exp2:exp3
Wherein exp1 is a boolean expression whose result must either be true or false.
If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.

public class conditionalOperator{


public static void main(String[]args){
String status=“”;
int grade =80;

status=(grade >=60)? “PASSED”: “FAIL”;


System.out.println(status);
}
}
Conditional Operators (?:)
1. WAP that will return the “ACCESS GRANTED” if the user input the
password “COMPUTER” otherwise it will return “ACCESS DENIED”.

2. WAP that will return the largest number among the three given integers.
Operator Precedence
Operator precedence defines the compiler’s order of evaluation of operators so as to come up with an
unambigous result.
The following is the list of Java operators from hihgest to lowest precedence.
• . [] ()
• ++ -- ! ~
• / %
• << >> >>> <<<
• < > <= >=
• == !=
• & |
• ^
• &&
• ||
• ?:
• =

The highest precedence is on the top row and the lowest precendence is on the bottom row
Getting Input from the keyboard(BufferedReader)
Package gettingIn;
import java.io.*;
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
//import java.io.IOException;
public class gettingIn{
public static void main(String[]args){
BufferedReader dataIn = new BufferedReader(newInputStreamReader(System.in));
String name=“”;
System.out.println(“Please Enter your Name”
try{
name=dataIn.readLine();
}catch (IOException e){
System.println(“Error!”);
}
System.out.println(“Hello” +name);
}
}
Getting Input (BufferedReader)
• Create a program that will ask for the password from the user, if the password
is equals to "COMPUTER" it will display "ACESS GRANTED" otherwise
"ACCESS DENIED

• WAP that will ask three integer from the user and will return the largest
number.
Getting Input from the keyboard (Scanner)
• The Scanner class is used to get user input, and it is found in
the java.util package.
• To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example,
we will use the nextLine() method, which is used to read Strings:

import java.util.Scanner; // Import the Scanner class


class Main { public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
Control Structures (Decision Control Structure)
Decision Control Structures – are Java statements that allows us to select and
execute specific block of code while skipping other sections.
1. If statement
2. If-else statement
3. If-else-if statement
Control Structures (Decision Control Structure)
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax
if (condition) { // block of code to be executed if the condition is true }
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

Example #1
if (20 > 18) { System.out.println("20 is greater than 18"); }

Example #2
int x = 20;
int y = 18;
if (x < y) { System.out.println("x is greater than y"); }
Control Structures (Decision Control Structure)
The if-else Statement
Use the else statement to specify a block of code to be executed if the condition
is false
Syntax
if (condition) {
// block of code to be executed if the condition is true }
else {
// block of code to be executed if the condition is false }
Example
int time = 20; if (time < 18) {
System.out.println("Good day."); }
else { System.out.println("Good evening.");
}
Control Structures (Decision Control Structure)
The if-else-if statement
Use the else if statement to specify a new condition if the first condition is false
Syntax
if (condition1) {
// block of code to be executed if condition1 is true }
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true }
else {
// block of code to be executed if the condition1 is false and condition2 is false }
Control Structures (Decision Control Structure)
int time = 22;
if (time < 10) {
System.out.println("Good morning."); }
else if (time < 20) {
System.out.println("Good day."); }
else {
System.out.println("Good evening."); }
Control Structures (Decision Control Structure)
• WAP that will ask for the password from the user and will display “ACCESS
GRANTED” if the password is equal to “COMPUTER” otherwise it will display
“ACCESS DENIED”

• WAP that will evaluate the letter input by the user and will display “VOWEL” or
“CONSONANT” at runtime.

• WAP that will as for the age of the user and will display “YOU ARE ALLOWED
to VOTE” if the age is greater than or equal to 18.

You might also like