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

CPE402 Chapter3 Programming Language Fundamentals - Final

This document discusses Java naming conventions and variables. It provides naming convention rules for classes, interfaces, methods, variables, packages and constants. CamelCase is used when combining multiple words. There are three types of variables in Java: instance variables, static variables, and local variables. Primitive data types include boolean, char, byte, short, int, long, float and double.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

CPE402 Chapter3 Programming Language Fundamentals - Final

This document discusses Java naming conventions and variables. It provides naming convention rules for classes, interfaces, methods, variables, packages and constants. CamelCase is used when combining multiple words. There are three types of variables in Java: instance variables, static variables, and local variables. Primitive data types include boolean, char, byte, short, int, long, float and double.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 139

CHAPTER 3:

JAVA PROGRAMMING
LANGUAGE
FUNDAMENTALS
PREPARED BY: ENGR. ERWIN S. COLIYAT, LECTURER I
BATANGAS STATE UNIVERSITY - PB MAIN II
COLLEGE OF ENGINEERING ARCHITECTURE AND FINE ARTS
CHAPTER 3.1
JAVA NAMING
CONVENTION
NAMING CONVENTIONS
 Java naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method, etc.
 All the classes, interfaces, packages, methods and fields of Java
programming language are given according to the Java naming convention. If
you fail to follow these conventions, it may generate confusion or erroneous
code.
 All Java components require names. Names used for classes, variables and
methods are called identifiers.
 Naming conventions in Java make programs more understandable by making
them easier to read.
NAMING CONVENTIONS

Why should follow the Java naming standards?


 To reduce the effort needed to read and understand source code.
 To enable code reviews to focus on more important issues than
arguing over syntax and naming standards.
 To enable code quality review tools to focus their reporting mainly
on significant issues other than syntax and style preferences.
CLASS
 It should start with the uppercase letter.
 It should be a noun such as Color, Button, System, Thread, etc.
 Use appropriate words, instead of acronyms.
Example: -

public class Employee


{
//code snippet
}
INTERFACE
 It should start with the uppercase letter.
 It should be an adjective such as Runnable, Remote,
ActionListener.
 Use appropriate words, instead of acronyms.
Example: -
interface Printable
{
//code snippet
}
METHOD
• It should start with lowercase letter.
• It should be a verb such as main(), print(), println().
• If the name contains multiple words, start it with a lowercase letter followed by
an uppercase letter such as actionPerformed().
Example:-
class Employee
{
//method
void draw()
{
//code snippet
}
}
VARIABLE
• It should start with a lowercase letter such as id, name.
• It should not start with the special characters like & (ampersand), $ (dollar), _
(underscore).
• If the name contains multiple words, start it with the lowercase letter followed
by an uppercase letter such as firstName, lastName.
• Avoid using one-character variables such as x, y, z.
Example :-
class Employee
{
//variable
int id;
//code snippet
}
PACKAGE

• It should be a lowercase letter such as java, lang.


• If the name contains multiple words, it should be separated by dots (.) such
as java.util, java.lang.
Example :-

package com.javatpoint; //package


class Employee
{
//code snippet
}
CONSTANT
• It should be in uppercase letters such as RED, YELLOW.
• If the name contains multiple words, it should be separated by an
underscore(_) such as MAX_PRIORITY.
• It may contain digits but not as the first letter.
Example :-

class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}
CamelCase in JAVA
Java follows camel-case syntax for naming the class, interface,
method, and variable.

If the name is combined with two words, the second word will
start with uppercase letter always such as actionPerformed(),
firstName, ActionEvent, ActionListener, etc.
CHAPTER 3.2:
VARIABLES
VARIABLES
• Java is a statically-typed programming language. It means, all 
variables must be declared before its use. That is why we need to
declare variable's type and name.

• A variable is a container which holds the value while the 


Java program is executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
VARIABLES
• Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means its
value can be changed.

Syntax
type variable = value;
Where type is one of Java's data types (such as int or String), and variable is the name of the variable
(such as x or name). The equal sign is used to assign values to the variable.

int data=10;//Here data is variable  
Types of Variables
• There are three types of variables in Java:
1) INSTANCE VARIABLE
A variable declared inside the class but outside the body of the
method, is called instance variable. It is not declared as static.
It is called instance variable because its value is instance specific
and is not shared among instances.

2) STATIC VARIABLE
A variable which is declared as static is called static variable. It
cannot be local. You can create a single copy of static variable and
share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the
memory.

3) LOCAL VARIABLE
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
Types of Variables
1. INSTANCE VARIABLES - declare inside class but not inside method

class Instance {
float pi = 3.1416; //instance variable
int data = 20; //instance variable
}

PROPERTIES
1. Instance variable always 2. Cannot be reinitialized 3. We can reinitialized
get a default value. directly wilth class. instance variable inside the
method.
data
int data; class Instance { class Instance {

0 int data = 15;


data = 20; //error
int data = 15;
void someMethod(){
} data = 20; //allowed
}
Types of Variables
2. STATIC VARIABLES - declare within the class and need to use static keyword.
in this section we will only discuss the introduction to static variables.

class Test{
static int data = 50;

can create a single copy of static variable and share among all the instances of the class
data_2

Obj1 Obj2

data data
Types of Variables
3. LOCAL VARIABLES - declared inside method or method parameters

int areaCircle (int radius)


{ are local variables
int total = radius * radius ;
return total;
}

PROPERTIES
1. Not accessible outside the method.
2. Do not get default value.
Example to understand the types of variables in java

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
CHAPTER 3.3:
DATA TYPES
DATA TYPES
Data types specify the different sizes and values that can be stored
in the variable. There are two types of data types in Java:
There are two types of data types in Java: primitive and non-primitive.
DATA TYPES IN JAVA

Primitive data types: There are 8


primitive data types: boolean, char,
byte, short, int, long, float and double.

Non-primitive data types: The non-


primitive data types include Classes, 
Interfaces, and Arrays.
JAVA PRIMITIVE DATA TYPES
In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.

Data Type Default Value Default size

boolean false 1 bit


char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
PRIMITIVE DATA TYPES
Integer types - stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends on the
numeric value.

Floating point types - represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.

Character - The char data type is used to store a single character.

Booleans - A boolean data type is declared with the boolean keyword and can only take the
values true or false:

The most used for numbers are int (for whole numbers) and double (for floating point numbers).
Integer Types

Byte - The byte data type can store whole numbers from -128 to 127. This can be used
instead of int or other integer types to save memory when you are certain that the value will be
within -128 and 127:

public class MyClass {


public static void main(String[] args) {
byte myNum = 100;
System.out.println(myNum);
}
}
Integer Types

Short - The short data type can store whole numbers from -32768 to 32767:

public class MyClass {


public static void main(String[] args) {
short myNum = 5000;
System.out.println(myNum);
}
}
Integer Types

Int - The int data type can store whole numbers from -2,147,483,648 to 2,147,483,647. In
general, and in our tutorial, the int data type is the preferred data type when we create variables
with a numeric value.

public class MyClass {


public static void main(String[] args) {
int myNum = 100000;
System.out.println(myNum);
}
}
Integer Types

Long - The long data type can store whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":

public class MyClass {


public static void main(String[] args) {
long myNum = 15000000000L;
System.out.println(myNum);
}
}
Floating Point Types
You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.

Float - The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that
you should end the value with an "f":

public class MyClass {


public static void main(String[] args) {
float myNum = 5.75f;
System.out.println(myNum);
}
}
Floating Point Types

Double - The double data type can store fractional numbers from -1.7e−308 to 1.7e+308.
Note that you should end the value with a "d":

public class MyClass {


public static void main(String[] args) {
double myNum = 19.99d;
System.out.println(myNum);
}
}
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the
power of 10:

public class MyClass {


public static void main(String[] args) {
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
}
}
Floating Point Types
Use float or double?

The precision of a floating point value indicates how many


digits the value can have after the decimal point. The
precision of float is only six or seven decimal digits, while
double variables have a precision of about 15 digits.
Therefore it is safer to use double for most calculations.
Booleans

Booleans - A boolean data type is declared with the boolean keyword and can only take the
values true or false:

public class MyClass {


public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}
Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.
Char

Characters - The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

public class MyClass {


public static void main(String[] args) {
char myGrade = 'B';
System.out.println(myGrade);
}
}

char a = 65, b = 66, c = 67;


System.out.println(a);
Alternatively, you can use ASCII values to display certain characters:
System.out.println(b);
System.out.println(c);
public class DataTypes {

public static void main(String[] args) {


byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
long longVar = 60L;
float floatVar = 20f;
double doubleVar = 20.123d;
boolean booleanVar = true;
Try this code! char charVar ='W';

System.out.println("Value Of byte Variable is " + byteVar);


System.out.println("Value Of short Variable is " + shortVar);
System.out.println("Value Of int Variable is " + intVar);
System.out.println("Value Of long Variable is " + longVar);
System.out.println("Value Of float Variable is " + floatVar);
System.out.println("Value Of double Variable is " + doubleVar);
System.out.println("Value Of boolean Variable is " + booleanVar);
System.out.println("Value Of char Variable is " + charVar);
}
}
Non Primitive Data Types
Non-primitive data types are called reference types because they
refer to objects.

The main difference between primitive and non-primitive data types are:
1. Primitive types are predefined (already defined) in Java. Non-primitive types are created by
the programmer and is not defined by Java (except for String).
2. Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
3. A primitive type has always a value, while non-primitive types can be null.
4. A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
5. The size of a primitive type depends on the data type, while non-primitive types have all the
same size.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will learn more about
these in a later chapter.
Java Type Casting
Type casting is when you assign a value of one primitive data type to
another type.
• In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type
size

byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) - converting a larger type to a smaller size type.

double -> float -> long -> int -> char -> short -> byte
Widening Casting
• Widening casting is done automatically when passing
a smaller size type to a larger size type:

Try this code!


public class MyClass
{
public static void main(String[] args)
{
int myInt = 9; double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);
System.out.println(myDouble);
}
}
Narrowing Casting
Narrowing casting must be done manually by placing the type in
parentheses in front of the value:

Try this code!


public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Explicit casting: double to int
System.out.println(myDouble);
System.out.println(myInt);
}
}
CHAPTER 3.4:
OPERATORS
Java Operators
Operators are used to perform operations on variables and
values.

In the example below, we use the + operator to add together


two values:

int x = 100 + 50;


JAVA OPERATORS
Java divides the operators into the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
ARITHMETIC OPERATORS
Arithmetic operators are used to perform common mathematical
operations.
Operator Name Description Example Try it
+ Addition Adds together two values x+y Try it »

- Subtraction Subtracts one value from another x-y Try it »

* Multiplication Multiplies two values x*y Try it »


/ Division Divides one value from another x/y Try it »
% Modulus Returns the division remainder x%y Try it »

++ Increment Increases the value of a variable by 1 ++x Try it »

-- Decrement Decreases the value of a variable by 1 --x Try it »


Example:
Although the + operator is often used to add together two values, like
in the previous example, it can also be used to add together a variable
and a value, or a variable and another variable:

int sum1 = 100 + 50; // 150 (100 + 50)


int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Java Assignment Operators
Assignment operators are used to assign values to
variables.

In the example below, we use the assignment operator (=) to


assign the value 10 to a variable called x:

Example: int x = 10;


EXAMPLE 1:
public class MyClass {
public static void main(String[] args) {
int x = 10;
x += 5;
System.out.println(x);
}
}
A list of all assignment operators:
Operator Example Same As Try it
= x=5 x=5 Try it »
+= x += 3 x= +3 Try it »
-= x -= 3 x = x - 3x Try it »
*= x *= 3 x=x*3 Try it »
/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »
&= x &= 3 x=x&3 Try it »
|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »
>>= x >>= 3 x = x >> 3 Try it »
<<= x <<= 3 x = x << 3 Try it »
Java Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example Try it


== Equal to x == y Try it »

!= Not equal x != y Try it »

> Greater than x>y Try it »

< Less than x<y Try it »

>= Greater than or equal to x >= y Try it »

<= Less than or equal to x <= y Try it »


Java Logical Operators
Logical operators are used to determine the logic between
variables or values:

Operator Name Description Example Try it


&&  Logical and Returns true if both statements are x < 5 &&  x < 10 Try it »
true
||  Logical or Returns true if one of the statements x < 5 || x < 4 Try it »
is true
! Logical not Reverse the result, returns false if !(x < 5 && x < 10) Try it »
the result is true
UNARY Operators
The unary operator performs operations on only one operand.

Operator Meaning
Unary plus (not necessary to use since numbers are positive
+
without using it)
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- decrement operator: decrements value by 1
Logical complement operator: inverts the value of a
!
boolean
JAVA Boolean
Very often, in programming, you will need a data type that can only have one of
two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, Java has a boolean data type, which can take the values true or false.
Java Math
Java Math Syntax Description
Math.max(x,y) can be used to find the highest value of x and y:
Math.min(x,y) can be used to find the lowest value of of x and y:
Math.sqrt(x) method returns the square root of x:
Math.abs(x) method returns the absolute (positive) value of x:
Math.random() returns a random number between 0.0 (inclusive), and
1.0 (exclusive):
int randomNum = (int) You can use this formula to get more control over the
(Math.random() * random number.
101); e.g. you only want a random number between 0 and
// 0 to 100 100.
Try this code!!!
package javamath;
public class JavaMath {
public static void main(String[] args) {
int a=-11;
int b=5;
int randNum = (int)(Math.random() * 101); // 0 to 100
System.out.println("maximum number is:" + " " + Math.max(a, b)); //maximum number
System.out.println("minimum number is:" + " " + Math.min(a, b)); //manimum number
System.out.println("the sqrt is:" + " " + Math.sqrt(a+b));
System.out.println("the absolute number is:" + " " + Math.abs(a+b));
System.out.println("This prints any value randomly:" + " " + Math.random() * 101); // 0 to 100);
}
}
CHAPTER 3.5:
JAVA STRINGS
Strings
Strings - The String data type is used to store a sequence of characters (text). String values
must be surrounded by double quotes:

public class MyClass {


public static void main(String[] args) {
String greeting = "Hello World";
System.out.println(greeting);
}
}

The String type is so much used and integrated in Java, that some call it "the special ninth type".

A String in Java is actually a non-primitive data type, because it refers to an object. The String object has
methods that are used to perform certain operations on strings.
String Length
• A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with the length()
method:

public class MyClass {


public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
}
}
More String Methods
• There are many string methods available, for example toUpperCase() and toLowerCase():

public class MyClass {


public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}
Finding a Character in a String
The indexOf() method returns the index (the position) of the first occurrence of a specified text
in a string (including whitespace):

public class MyClass {


public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}

Java counts positions from zero.


0 is the first position in a string, 1 is the second, 2 is the third ...
String Concatenation

• The + operator can be used between strings to combine them. This is called concatenation:
public class MyClass {
public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}
Note that we have added an empty text (" ") to create a space between firstName and lastName on print.

You can also use the concat() method to concatenate two strings:

String firstName = "John ";


String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Adding Numbers and Strings
WARNING!
 Java uses the + operator for both addition and concatenation.
 Numbers are added. Strings are concatenated.

If you add a number and a string, the result will be a string concatenation:

String x = "10";
int y = 20;
String z = x + y; // z will be 1020 (a String)
Special Characters
Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

String txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:

Escape character Result Description

\' ' Single quote

\" " Double quote

\\ \ Backslash

String txt = "We are the so-called \"Vikings\" from the north.";
String txt = "It\'s alright.";
String txt = "The character \\ is called backslash.";
CHAPTER 3.6:
USERS INPUT
AND OUTPUT
Learn simple ways to
display output and take
input from the user.
Java Output

You can simply use System.out.println(), System.out.print() or


System.out.printf() to send output to standard output (screen).

System is a class and out is a public static field which accepts


output data. Don't worry if you don't understand it. Classes,
public, and static will be discussed in later chapters.
Let's take an example to output a line.

class AssignmentOperator {
public static void main(String[] args) {
System.out.println("Java programming is interesting.");
}
}

When you run the program, the output will be:


Java programming is interesting.
Here, println is a method that displays the string inside quotes.
What's the difference between println(), print()
and printf()?

 print() - prints string inside the quotes.


 println() - prints string inside the quotes similar like print()
method. Then the cursor moves to the beginning of the next
line.
 printf() - it provides string formatting (similar to printf in C/C++
programming).
Example 2: print() and println()

class Output {
public static void main(String[] args) {
System.out.println("1. println ");
System.out.println("2. println ");
System.out.print("1. print ");
System.out.print("2. print");
}
}
When you run the program, the output will be:

1. println
2. println
1. print 2. print
Example 3: Printing Variables and Literals
To display integers, variables and so on, do not use
quotation marks.
class Variables {
public static void main(String[] args) {
Double number = -10.6;
System.out.println(5);
System.out.println(number);
}
}
Example 3:
When you run the program, the output will be:

5
-10.6
Example 4: Print Concatenated Strings
You can use + operator to concatenate strings and print it.

class PrintVariables {
public static void main(String[] args) {

Double number = -10.6;

System.out.println("I am " + "awesome.");


System.out.println("Number = " + number);
}
}
Example 4:
When you run the program, the output will be:
I am awesome.
Number = -10.6
Consider: System.out.println("I am " + "awesome.");

Strings "I am " and "awesome." is concatenated first before it's printed on the
screen.

Consider: System.out.println("Number = " + number);

The value of variable number is evaluated first. It's value is in double which is
converted to string by the compiler. Then, the strings are concatenated and
printed on the screen.
Java Input
There are several ways to get input from the user in
Java. You will learn to get input by using Scanner
object.

For that, you need to import Scanner class using:

import java.util.Scanner;
Learn more about Java import

• Then, we will create an object of Scanner class


which will be used to get input from the user.

Scanner input = new Scanner(System.in);


int number = input.nextInt();
Example 5: Get Integer Input From the User

import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
When you run the program, the output will be:

Enter an integer: 23
You entered 23
• Here, input object of Scanner class is created. Then, the
nextInt() method of the Scanner class is used to get integer
input from the user.

• To get long, float, double and String input from the user,
you can use nextLong(), nextFloat(), nextDouble() and
next() methods respectively.
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Exam Scanner input = new Scanner(System.in);
ple 6: // Getting float input

Get System.out.print("Enter float: ");


float myFloat = input.nextFloat();

float, System.out.println("Float entered = " + myFloat);

// Getting double input


doubl System.out.print("Enter double: ");
double myDouble = input.nextDouble();
e and System.out.println("Double entered = " + myDouble);

String // Getting String input


System.out.print("Enter text: ");

Input String myString = input.next();


System.out.println("Text entered = " + myString);
}
}
When you run the program, the output will be:

Enter float: 2.343


Float entered = 2.343
Enter double: -23.4
Double entered = -23.4
Enter text: Hey!
Text entered = Hey!

Note: there are other several ways to get input from the user.
CHAPTER 3.7:
CONDITIONAL
STATEMENTS
Java Conditions and If Statements
Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different
decisions.
Java has the following conditional statements:
 Use if to specify a block of code to be executed, if a specified
condition is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition
is false
 Use switch to specify many alternative blocks of code to be
executed
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.
The if Statement
In the example below, we test two values to find out if 20 is greater
than 18. If the condition is true, print some text:

Example 1:
if (20 > 18) {
System.out.println("20 is greater than 18");
}
Example 2: We can also test variables:
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
The if Statement
• In the previous example, we use two variables, x and y, to test
whether x is greater than y (using the > operator). As x is 20, and y
is 18, and we know that 20 is greater than 18, we print to the
screen that "x is greater than y".
The 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
}
The else Statement
Example:

int time = 20;


if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening.
The else Statement

In the previous example, time (20) is greater than 18, so the


condition is false. Because of this, we move on to the else condition
and print to the screen "Good evening". If the time was less than
18, the program would print "Good day".
The 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
}
The else if Statement
int time = 22;
if (time < 10) {
EXAMPLE:

System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
The else if Statement
EXAMPLE EXPLAINED

In the example above, time (22) is greater than 10, so the


first condition is false. The next condition, in the else if
statement, is also false, so we move on to the else
condition since condition1 and condition2 is both false -
and print to the screen "Good evening".

However, if the time was 14, our program would print


"Good day."
Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator
because it consists of three operands. It can be used to replace multiple lines
of code with a single line. It is often used to replace simple if else statements:

variable = (condition) ? expressionTrue : expressionFalse;


Instead of writing:
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
EXAMPLE
System.out.println("Good evening.");
}

You can simply write:

int time = 20;


String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
PRACTICE 1:

Print "Hello World" if x is greater


than y.
PRACTICE 2:

Print "Hello World" if x is equal to y.


PRACTICE 3:

Print "Yes" if x is equal to y,


otherwise print "No".
PRACTICE 4:

Print "1" if x is equal to y, print "2" if


x is greater than y, otherwise print
"3".
PRACTICE 5:
Run this code and identify the error.

int time = 20;


String result =time < 18"Good day.""Good evening.";
System.out.println(result);
Java Switch
Use the switch statement to select one of many code blocks to
be executed.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Java Switch Statements
How it Works?
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each
case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be
described later in this chapter.
Java Switch Statements
../../../../Documents/SwitchExample.java
The break Keyword
When Java reaches a break keyword, it breaks out of the switch
block.

This will stop the execution of more code and case testing inside
the block.

When a match is found, and the job is done, it's time for a break.
There is no need for more testing.

A break can save a lot of execution time because it "ignores" the


execution of all the rest of the code in the switch block.
The default Keyword
The default keyword specifies some code to run if there is no case
match:

int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
The break Keyword

Note that if the default statement is used


as the last statement in a switch block, it
does not need a break.
int day = 2;
PRACTICE 6: switch (
1:
){

System.out.println("Saturday");
Insert the missing break;
parts to complete the 2:
following switch System.out.println("Sunday");
statement. ;
}
int day = 4;
switch ( ){
PRACTICE 7: 1:
System.out.println("Saturday");
break;
Insert the missing 2:
parts to complete the
following switch
System.out.println("Sunday");
statement. ;
:
System.out.println("Weekend");
}
CHAPTER 3.8:
JAVA LOOPS
AND ITERATION
Loops can execute a block of code as long as a
specified condition is reached. Loops are handy
because they save time, reduce errors, and they
make code more readable.
JAVA FOR LOOP
When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:

for (statement 1; statement 2; statement 3) {


// code block to be executed
}
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code


block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been
executed.
EXAMPLE:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
 Statement 1 sets a variable before the loop starts (int i = 0).

 Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.

 Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
EXAMPLE:
This example will only print even values between 0 to 10.

for (int i = 0; i <= 10; i = i + 2) {


System.out.println(i);
}
For-Each Loop
There is also a "for-each" loop, which is used
exclusively to loop through elements in
an array:
for (type variableName : arrayName) {
// code block to be executed
}
Java While Loop
The while loop loops through a block of code as long as a
specified condition is true:

while (condition) {
// code block to be executed
}
Java While Loop
The In the example below, the code in the loop will run, over and
over again, as long as a variable (i) is less than 5:

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

Note: Do not forget to increase the variable used in the


condition, otherwise the loop will never end!
The Do/While Loop

The do/while loop is a variant of the while loop. This loop


will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the
condition is true.

do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will
always be executed at least once, even if the condition is
false, because the code block is executed before the
condition is tested:
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise
the loop will never end!
PRACTICE 8:

Print i as long as i is less than 6.


PRACTICE 9:

Use the do/while loop to print i as


long as i is less than 6.
PRACTICE 10:

Use a for loop to print "Yes" 5


times:
PRACTICE 11:

Stop the loop if i is 5.


PRACTICE 12:

In the loop, when the value is "4",


jump directly to the next value.
Java Break
and Continue
Java Break
It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.

for (int i = 0; i < 10; i++) {


if (i == 4) { This example
jumps out of the
break;
loop when i is
} equal to 4:
System.out.println(i);
}
Java Continue
The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration
in the loop.
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
This example skips the
value of 4: }
System.out.println(i);
}
Break and Continue in While Loop
You can also use break and continue in while loops:

public static void main(String[] args) {


int i = 0;
while (i < 10) {
System.out.println(i);
i++; Break
if (i == 4) {
break;
Example
}
}
int i = 0;
while (i < 10) {
if (i == 4) {
Continue
i++;
continue;
EXAMPLE
}
System.out.println(i);
i++;
}
CHAPTER 3.9:
JAVA ARRAYS
Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for
each value.
JAVA ARRAYS

To declare an array, define the variable type with


square brackets:

String[] cars;
JAVA ARRAYS
• We have now declared a variable that holds an array of strings. To
insert values to it, we can use an array literal - place the values in a
comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

 To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};


Access the Elements of an Array

• You access an array element by referring to the index number.


• This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Change an Array Element
To change the value of a specific element, refer to the index
number:

cars[0] = "Opel";

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length
property:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars.length);
// Outputs 4
Loop Through an Array
You can loop through the array elements with the for loop, and use the
length property to specify how many times the loop should run.

The following example outputs all elements in the cars array:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Loop Through an Array with For-Each
There is also a "for-each" loop, which is used exclusively to
loop through elements in arrays:
for (type variable : arrayname) {
...
}
The following example outputs all elements in the cars array,
using a "for-each" loop:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
The previous example can be read like this: for each String
element (called i - as in index) in cars, print out the value of i.

If you compare the for loop and for-each loop, you will see
that the for-each method is easier to write, it does not require
a counter (using the length property), and it is more readable.
Multidimensional Arrays
• A multidimensional array is an array containing one or more
arrays.

• To create a two-dimensional array, add each array within its


own set of curly braces:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.


To access the elements of the myNumbers array, specify
two indexes: one for the array, and one for the element
inside that array. This example accesses the third
element (2) in the second array (1) of myNumbers:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };


int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
We can also use a for loop inside another for loop to get
the elements of a two-dimensional array (we still have to
point to the two indexes):

public class MyClass {


public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}
END OF PRESENTATION!

THANK YOU!

You might also like