You are on page 1of 38

CC102 Fundamentals of Computer Programming

Fundamentals of
Computer Programming

XENIORITA ALONDRA BIO WEEK 4


Anatomy of a Java
Basic Syntax (recap)
main() method
main( ) is simply a starting place for your program. It is the method called
when a Java application begins. A complex program will have dozens of
classes, only one of which will need to have a main( ) method to get
things started. Furthermore, for some types of programs, you won’t
need main( ) at all. However, for most of the programs main( ) is
required.
COMMENTS IN JAVA
There are three (3) types of comments in Java:
• Line comments (single-line) start with two forward slashes ( // ) and continue to the
end of the current line. Line comments do not require an ending symbol.
• Block comments (multi-line) start with a forward slash and an asterisk ( /* ) and end
with an asterisk and a forward slash ( */ ). Block comments also can extend across as
many lines as needed.
• Javadoc comments are a special case of block comments. They begin with a forward
slash and two asterisks ( /** ) and end with an asterisk and a forward slash ( */ ). You
can use javadoc comments to generate documentation with a program named
javadoc.

**The forward slash ( / ) and the backslash ( \ ) characters often are confused, but they are two distinct characters.
You cannot use them interchangeably.
Understanding main method
The keyword static allows main( ) to be
The public keyword is an access called without having to instantiate a The keyword void simply tells
modifier, which allows the particular instance of the class. the compiler that main( ) does
programmer to control the visibility not return a value.
of class members.
The last character on the line is
the {. This signals the start of
main( )’s body. All of the code
System is a that comprises a method will
predefined class occur between the method’s
that provides opening curly brace and its
access to the closing curly brace.
system, and out is
the output stream
that is connected
to the console.
println() is a method. Method
"Hello World!" is a literal string
Dots separate names are always followed by
Closing curly braces of method that is the argument to the
classes, objects, parentheses.
main. println() method.
and methods.
Closing curly braces of class
DemoWeek2.
IDENTIFIERS,
VARIABLES, AND DATA TYPES
IDENTIFIERS
▪ Identifier - In programming languages, identifiers are used for identification purposes.
▪ Case-sensitivity - Java is case sensitive, which implies that the identifier Hi and hi
would have distinctive importance in Java.
▪ Java Identifier- All Java components require names. Names utilized for classes,
variables and strategies are called identifiers. In Java, there are a few focuses to recall
about identifiers.

➢ All identifiers ought to start with a letter (beginning to end or a to z),


underscore (_) or special character ($).
➢ After the first character, identifiers can have any mix of characters.
➢ You cannot use a keyword as an identifier.
➢ Most significantly, identifiers are case-sensitive. So, Sample is not same as
sample. Examples of identifiers include $salary, age, __1_value and _value.
➢ Examples of illicit identifiers include –compensation and 123abc.
IDENTIFIERS
JAVA KEYWORDS
VARIABLES
Variables in a program are used to store data such as numbers
and letters. They can be thought of as containers of a sort. The
number, letter, or other data item in a variable is called its value.
This value can be changed, so that at one time the variable
contains, say, 6, and at another time, after the program has run
for a while, the variable contains a different value, such as 4.
Primitive Data Types:
• Primitive data types are also known as "value types."
• They directly store the actual value of the data.
• Primitive data types are simple and small in size.
• When you assign a primitive data type to a variable, you're actually storing
the data itself in that variable.
• Examples of primitive data types include integers, floating-point numbers,
characters, and booleans.
Integer Data Type
TYPE Minimum Value Maximum Value Size in bytes
byte −128 127 1
short −32,768 32,767 2
int −2,147,483,648 2,147,483,647 4
long −9,223,372,036,854,775,808 9,223,372,036,854,775,807 8
Floating-point Data Type
TYPE Minimum Value Maximum Value Size in bytes
float –3.4 * 1038 3.4 * 1038 4
double –1.7 * 10308 1.7 * 10308 8
Character Data Type
TYPE Minimum Value Maximum Value Size in bits
char “\uffff” (or 65,535 comprehensive) “\u0000” (or 0) 16
Boolean Data Type
TYPE Minimum Value Maximum Value Size in bits
boolean true or false 1
Reference Data Types (Reference Types):
• Reference data types are also known as "object types."
• They store references (memory addresses) to the location where the data is
stored in memory.
• Reference data types are more complex and can hold large amounts of data.
• When you assign a reference data type to a variable, you're storing a
reference to the data, not the data itself.
• Examples of reference data types include arrays, strings, and custom objects.
In summary, the key difference lies in how data is stored:

• Primitive data types store the actual data value directly in the variable.
• Reference data types store a reference (memory address) to where the data
is located in memory. This allows reference types to represent more complex
data structures and share data efficiently, but it adds a layer of indirection
compared to primitive types.
VARIABLE DECLARATION
Variables are containers for storing data values. In a Java program, you must
declare a variable before it can be used. A variable declaration has the
following form:
datatype identifier;
datatype identifier1, identifier2, identifier3;
ASSIGNMENT STATEMENTS
An assignment statement that
has a variable of a primitive
type on the left side of the
equal sign causes the
following action: First, the
expression on the right side of
the equal sign is evaluated,
and then the variable on the
left side of the equal sign is
set to this value.
INITIALIZE VARIABLES
A variable that has been declared, but that has not yet been
given a value by an assignment statement (or in some other
way), is said to be uninitialized. If the variable is a variable of a
class type, it literally has no value. If the variable has a primitive
type, it likely has some default value. However, your program
will be clearer if you explicitly give the variable a value, even if
you are simply reassigning the default value.
Combining a Variable Declaration
and an Assignment
SIMPLE INPUT USING
SCANNER
SIMPLE INPUT
We use the class Scanner, which Java supplies, to accept keyboard input. Our
program must import the definition of the Scanner class from the package
java.util. Thus, we begin the program with the following statement:
import java.util.Scanner;
The following line sets things up so that data can be entered from the keyboard:
Scanner scanner = new Scanner(System.in);
This line must appear before the first statement that takes input from the
keyboard.
int age = scanner.nextInt();
This assignment statement gives a value to the variable age. The expression on
the right side of the equal sign.
SCANNER CLASS METHODS
Method Description
nextDouble() Retrieves input as a double
nextInt() Retrieves input as an int
nextLine() Retrieves the next line of data and returns it as
a String
Next() Retrieves the next complete token as a String
ECHOING INPUT
Repeating as output what a user has entered as input is called echoing the input.
Echoing input is a good programming practice; it helps eliminate
misunderstandings when the user can visually confirm what was entered.
SAMPLE
SCANNER
Pitfall: Using nextLine() Following One of the Other Scanner Input Methods
You can encounter a problem when you use one of the numeric Scanner class retrieval
methods or the next() method before you use the nextLine() method.
Don’t do it:
If you use any other Scanner
input methods prior to string
input that uses nextLine(),
the string input is ignored
unless you take special
action.
Pitfall: Using nextLine() Following One of the Other Scanner Input Methods
The solution to the problem is simple. After any next(), nextInt(), or nextDouble() call,
you can add an extra nextLine() method call that will retrieve the abandoned Enter key
character. Then, no matter what type of input follows, the program will execute
smoothly.

This statement
consumes the Enter key
that follows the integer.
Imprecision in Floating-Point Numbers
• Floating-point numbers are stored with a limited amount of precision and so are, for
all practical purposes, only approximate quantities. For example, the fraction one
third is equal to 0.3333333 . . . where the three dots indicate that the 3s go on
forever. The computer stores numbers in a format somewhat like the decimal
representation on the previously displayed line, but it has room for only a limited
number of digits. If it can store only ten digits after the decimal, then one third is
stored as 0.3333333333 (and no more 3s).
Imprecision in Floating-Point Numbers
ASSIGNMENT COMPATIBILITIES
You can assign a value of any type on the following list to a
variable of any type that appears further down on the list:

byte short int long float double

In particular, note that you can assign a value of any integer


type to a variable of any floating-point type.
It is also legal to assign a value of type char to a variable of type
int or to any of the numeric types that follow int in our list of
types.
Type Casting
In many situations, you cannot store a value of one type in a variable of another
type unless you use a type cast that converts the value to an equivalent value of
the target type.
SYNTAX
[Data type] [Expression]
EXAMPLES
double guess = 7.8;
int answer = (int) guess;
The value stored in answer will be 7. Note that the value is truncated, not
rounded. Note also that the variable guess is not changed in any way; it still
contains 7.8. The last assignment statement affects only the value stored in
answer.
Operators in Java
OPERATORS IN JAVA
The operator set in Java is extremely rich. Broadly, the operators
available in Java are divided in the following categories:

• Relational Operators
• Arithmetic Operators
• Logical Operators
• Assignment Operators
RELATIONAL OPERATORS
OPERATION OPERATOR DESCRIPTION
EQUAL TO == Compares the values of two variables for
equality
NOT EQUAL TO != Compares the values of two variables for
equality
GREATER THAN > Checks if one value is greater than the other
value
LESSER THAN < Checks if one value is lesser than the other
value
GREATER THAN OR EQUAL >= Checks if one value is lesser than the other
TO value
LESSER THAN OR EQUAL TO <= Checks if one value is lesser than or equal to
the other value
ARITHMETIC OPERATORS
OPERATION OPERATOR DESCRIPTION
ADDITION + Adds the values of two variables
SUBTRACTION - Subtracts the values of two variables
MULTIPLICATION * Multiplies the values of two variables
DIVISION / Divides the values of two variables
MODULUS % The resultant value is the remainder of
division
INCREMENT ++ Increases the value by 1
DECREMENT -- Decreases the value by 1
LOGICAL OPERATORS

OPERATION OPERATOR DESCRIPTION


LOGICAL AND && Returns True if both the
conditions mentioned are true
LOGICAL OR || Returns True if one or both the
conditions mentioned are true
LOGICAL NOT ! Returns True if the condition
mentioned is False
ASSIGNMENT OPERATORS
OPERATION OPERATOR DESCRIPTION
Simple assignment Assigns a value on the right to the variable in the left.
operator
=
Add - assignment operator Adds the value on the right to the value of the variable on
+= the left and assigns the resultant to the variable on the left.
Subtract - assignment operator Subtracts the value on the right to the value of the variable
-= on the left and assigns the resultant to the variable on the
left.
Multiply - assignment operator Multiplies the value on the right to the value of the variable
*= on the left and assigns the resultant to the variable on the
left.
Divide - assignment operator Divides the value on the right to the value of the variable on
/= the left and assigns the resultant to the variable on the left.
Modulus - assignment operator It takes the modulus of the LHS and RHS and assigns the
%= resultant to the variable on the left.
Parenthesis and Precedence Rules
• Parentheses are used in arithmetic expressions to specify the order of
operations.
• They work similarly to algebra and arithmetic for grouping operations.
• Parentheses determine which operations are performed first.
• Example expressions with different parentheses placement:
(cost + tax) * discount and cost + (tax * discount).
• Omitting parentheses results in the computer following operator precedence
rules.
• Operators with higher precedence are evaluated first.
• Including parentheses is recommended for clarity in code, even if precedence
rules match the intended order of operations.
• An exception is multiplication within addition, where parentheses are often
omitted.
Parenthesis and Precedence Rules
Here's a simplified breakdown of the operator precedence rules in Java:
• Parentheses: Expressions inside parentheses are evaluated first.
• Postfix operators: These include increment (++) and decrement (--). They are applied after the
current value is used in the expression.
• Multiplicative operators: These include multiplication (*), division (/), and modulo (%). They are
evaluated from left to right.
• Additive operators: These include addition (+) and subtraction (-). Like multiplicative operators, they
are also evaluated from left to right.
• Relational operators: These include less than (<), greater than (>), less than or equal to (<=), and
greater than or equal to (>=). They are used to compare values and produce boolean results.
• Equality operators: These include equality (==) and inequality (!=). They are used to compare values
for equality and produce boolean results.
• Logical AND (&&): Used for logical AND operations with short-circuiting.
• Logical OR (||): Used for logical OR operations with short-circuiting.
• Conditional (Ternary) Operator (?:): Used for conditional expressions.
• Assignment operators: These include simple assignment (=) and compound assignment operators
• Comma operator (,): Used to separate expressions within a statement, evaluated left to right.
**Remember that parentheses can be used to override the default precedence and explicitly specify the order of
evaluation. When in doubt, use parentheses to make your code more explicit and readable, especially if you have
complex expressions with multiple operators.
Parenthesis and Precedence Rules
Fundamentals of Computer Programming

The End

XENIORITA ALONDRA BIO WEEK 4

You might also like