0% found this document useful (0 votes)
4 views137 pages

4.3 Java

The document provides an overview of Java programming, detailing its structure, syntax, and key concepts such as classes, methods, and object-oriented programming principles. It explains how to run Java, the importance of the main method, and the various data types available in Java, including their default values and sizes. Additionally, it covers the rules for naming classes, methods, and variables, as well as the use of operators and comments in Java code.

Uploaded by

Öykü Korkutan
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)
4 views137 pages

4.3 Java

The document provides an overview of Java programming, detailing its structure, syntax, and key concepts such as classes, methods, and object-oriented programming principles. It explains how to run Java, the importance of the main method, and the various data types available in Java, including their default values and sizes. Additionally, it covers the rules for naming classes, methods, and variables, as well as the use of operators and comments in Java code.

Uploaded by

Öykü Korkutan
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/ 137

JAVA

IB Computer Science
The Koç School
Computer Education Department
JAVA BASICS
Java
Java programming language is the global standard for
developing and delivering embedded and mobile
applications, games, web-based content, and enterprise
software.

Java enables you to efficiently develop, deploy, and use


various applications and services.

It is a high level programming language.


How to Run Java?

JDK (Java Development Kit) - from Oracle


http://www.oracle.com/technetwork/java/javase/downloads/index.html

IDE (Integrated Development Environment) – from Eclipse


http://www.eclipse.org/downloads/eclipse-packages/
Java’s Structure
Java programs are called “classes”

They exist inside a container called a


“project”

All classes have at least one method


called “main()”
Object, Class, Method, Variable
Object − Objects have states and behaviors. Example: A dog has
states - color, name, breed as well as behavior such as wagging
their tail, barking, eating. An object is an instance of a class.

Class − A class can be defined as a template/blueprint that


describes the behavior/state that the object of its type supports.

Methods − A method is basically a behavior. A class can contain


many methods. It is in methods where the logics are written,
data is manipulated and all the actions are executed.

Instance Variables − Each object has its unique set of instance


variables. An object's state is created by the values assigned to
these instance variables.
Features of Java

Curly braces are used to mark the beginning and end of a class.
The curly braces will always occur in pairs. The open curly brace marks the
beginning of the class and the close curly brace marks the end.
Curly braces are also used to mark other blocks of code within Java programs.
Features of Java

All Java programs are contained within one or more classes.


A class name needs to begin with a letter (not a number or symbol) and it contains
no spaces.
By convention, Java programmers capitalize the first letter of each word within the
name.
Features of Java

Every Java program will contain a main method.


When your program is executed, the computer will execute the code starting at the
main method.
Features of Java

The main method will contain one or more Java statements.


A program is a set of instructions. These instructions are called statements in Java.
Statements can be anything from a single line of code to a complex mathematical
equation. This program contains one statement that instructs the computer to
display the phrase "Hello World" onto the terminal window.
Features of Java

All Java statements must end with a semicolon.


Semicolons are used to mark the end of Java statements; not spacing, tabbing,
indenting, or carriage returns.
All of the spacing you see in the program is removed when the program is
compiled. The spacing is there to make it easier for us humans to read the code.
Features of Java

Java is case-sensitive.
All keywords in Java should be declared using lower-case letters.
Classes start with capital letters, methods and variables start with lower case
letters.
Syntax Rules

- Classes start capital letters and have no ( )


- Methods start lowercase letters and have a ( )
- Variables always start with a lowercase letter
- = means ‘gets the value of’
- == means ‘equals’ when comparing numbers
- .equals() means ‘equals’ when comparing words (String statements)
- String values are typed in: “string value”
Rules in Class, Method and Project Name
Class Names − Class names the first letter should be in Upper Case. If several words are
used to form a name of the class, each word's first letter should be in Upper Case. (class
MyFirstJavaClass)

Method Names − Method names should start with a Lower Case letter. If several words are
used to form the name of the method, each other word's first letter should be in Upper
Case. (public void myMethodName())

Project File Name − Name of the project file should exactly match the class name. When
saving the file, you should save it using the class name (Remember Java is case sensitive)
and append '.java' to the end of the name (if the file name and the class name do not
match, your program will not compile). (Assume 'MyFirstJavaProgram' is the class name.
Then the file should be saved as 'MyFirstJavaProgram.java')
Variable, Constant and Operator

Variable is used to store data elements of a program. The stored data can be
changed during the program execution.

Constant represent things and quantities that don’t change. This can be seen as
non-modifiable variables.

Operators are used to manipulate operands (e.g. +, -, etc.). Operators can be


arithmetical, relational and logical. Operands can be variables, boolean values,
numeric values, text.
Comment Line
Java supports:
- single-line (//)
- multi-line (/* */)
comments.
All characters available inside any
comment are ignored by Java
compiler.
Print Statement
Escape Sequences

A character preceded by a backslash (\)


is an escape sequence and has special
meaning to the compiler.

When an escape sequence is


encountered in a print statement, the
compiler interprets it accordingly. For
example, if you want to put quotes
within quotes you must use the escape
sequence, \", on the interior quotes.
Object-oriented Programming
Object-oriented languages follow a different programming pattern from
structured programming languages like C and COBOL.
The structured-programming paradigm is highly data oriented: You have data
structures, and then program instructions act on that data.
Object-oriented languages such as the Java language combine data and program
instructions into objects.
Object-oriented Programming

An object is a self-contained entity that contains attributes and


behavior, and nothing more.
Instead of having a data structure with fields (attributes) and passing
that structure around to all of the program logic that acts on it
(behavior), in an object-oriented language, data and program logic are
combined into an object.
Object-oriented Programming

Example: A “Person” object:

This first example is based on a common application-development


scenario: an individual being represented by a Personobject.
The definition of an object: object has two primary elements:
• attributes
• behavior
Object-oriented Programming
Attributes (nouns) of a person object

What attributes can a person have? Some common ones include:


● Name
● Age
● Height
● Weight
● Eye color
● Gender
Object-oriented Programming
Behavior (verbs) of a person object

You may ask your Person object, "What is your body mass index (BMI)?”. In
response, Person would use the values of its height and weight attributes to
calculate the BMI.
Or you may want the Person to print all of its attributes.

So, for now, that Person has the following behaviours:


● Calculate BMI
● Print all attributes
Principles of OOP: Encapsulation,
Inheritance, Overriding, Polymorphism
Encapsulation:
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class. Therefore, it is also known
as data hiding.

Benefits of Encapsulation:
• The fields of a class can be made read-only
or write-only.
• A class can have total control over what is
stored in its fields.
Principles of OOP: Encapsulation,
Inheritance, Overriding, Polymorphism
Inheritance:
Inheritance can be defined as the process where Super class
one class acquires the properties (methods and
fields) of another. With the use of inheritance, the
information is made manageable in a hierarchical
order.
The class which inherits the properties of other is
known as subclass (derived class, child class) and
the class whose properties are inherited is known
as superclass (base class, parent class). Sub-class
Principles of OOP: Encapsulation,
Inheritance, Overriding, Polymorphism
Overriding:
Overriding is a feature that allows a subclass or
child class to provide a specific implementation of a
method that is already provided by one of its super-
classes or parent classes. When a method in a
subclass has the same name, same parameters or
signature and same return type (or sub-type) as a
method in its super-class, then the method in the
subclass is said to override the method in the
super-class.
Principles of OOP: Encapsulation,
Inheritance, Overriding, Polymorphism

Polymorphism:
Polymorphism is the capability of a method to do different things based on the
object that it is acting upon. In other words, polymorphism allows you define one
method and have multiple implementations according to the situation.
VARIABLES, CONSTANTS
AND DATA TYPES
Variable and Value

A variable is like a box


What is inside the box can change or ‘vary’.
The ‘thing’ inside the box is the value.

int x = 3
Declaring, Assigning, Initializing
Declaring is the process of defining the variable.
int number;

Assigning (instantiating) is the process of setting a value to a declared variable.


number = 3;

Initializing is the process of assigning a value while declaring the variable.


int number = 3;
Data Types
A variable's type must correspond to
one of eight basic data types, defined
within the language. These
fundamental types, also called
primitives, allow you to define
variables for storing data that falls into
one of three categories:
• Numeric values, which can be
either integer or floating point
• Variables which store a single
Unicode character
• Logical variables that can assume
the values of true or false
Data Types
Information that is stored in the computer's
memory is stored as a contiguous series of
bytes. These bytes can represent a number,
a string, a picture, a chunk of sound, or
whatever, as determined by context. It is the
responsibility of the data type to inform the
computer of the type of data a variable is
storing.
Different data types require different
amounts of memory. The data type informs
the computer how much memory is needed
for a particular variable.
Primitive Data Types
Primitive data types are predefined by the language and named by a keyword.
• Byte
• Short
• Int
• Long
• Float
• Double
• Boolean
• Char
Byte
• Byte data type is an 8-bit (1 Byte) data type
• Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1)
• Default value is 0
• Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an integer.

Example: byte a = 100; byte b = -50;


Short
• Short data type is a 16-bit (2 Bytes) data type
• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767 (inclusive) (2^15 -1)
• Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an integer
• Default value is 0.

Example: short s = 10000; short r = -20000;


Int
• Int data type is a 32-bit (4 Bytes) data type
• Minimum value is - 2,147,483,648 (-2^31)
• Maximum value is 2,147,483,647(inclusive) (2^31 -1)
• Integer is generally used as the default data type for integral values unless there
is a concern about memory.
• The default value is 0

Example: int a = 100000; int b = -200000;


Long
• Long data type is a 64-bit (8 Bytes) data type
• Minimum value is -9,223,372,036,854,775,808(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
• This type is used when a wider range than int is needed
• Default value is 0L
Important! When you specify a literal value for a long type, put a capital L to the
right of the value to explicitly state that it’s a long type. Integer literals are assumed
by the compiler to be of type int unless you specify otherwise by using an L
indicating long type.

Example: long a = 10000000000000L; long b = -200000L;


Float
• Float data type is a 32-bit (4 Bytes) floating point
• Float is mainly used to save memory in large arrays of floating point numbers
• Default value is 0.0f
• Float data type is never used for precise values

Important!
Floating point values are assumed to be of type double unless you explicitly state
that it is a float type, not a double type. You do that by putting an “f” (float) to the
right of the value.

Example: float f1 = 234.5f


Double
• Double data type is a 64-bit (8 Bytes) floating point
• This data type is generally used as the default data type for decimal values,
generally the default choice
• Double data type should never be used for precise values
• Default value is 0.0d

Example: double d1 = 123.4;


Double Example
Output:
Class DoubleDemo
{ 123.43555
public static void main(String args[])
{
double dec = 123.43555;
System.out.println("Value of dec is : " + dec);
}
}
Boolean
• Boolean data type represents one bit of data
• There are only two possible values: true and false
• This data type is used for simple flags that track true/false conditions
• Default value is false

Example: boolean one = true;


Boolean Example
public static void main(String args[]) {
Output:
boolean b1, b2, b3;
true
b1 = true; // Assigning Value
false
b2 = false; // Assigning Value
b3 = b2; // Assigning Variable false

System.out.println(b1); // Printing Value


System.out.println(b2); // Printing Value
System.out.println(b3); // Printing Value

}
Char
• char data type is a single 16-bit Unicode character
• Minimum value is '\u0000' (or 0)
• Maximum value is '\uffff' (or 65,535 inclusive)
• Char data type is used to store any character

Example: char letterA = 'A';

A char character is written in 'x' rather than “x”

ASCII code table


Char Example
char ch1, ch2; // declaration
ch1 = 88; // (code for X) Assigning a value to ch1
ch2 = 'Y';

System.out.print("ch1 and ch2: ");


System.out.println(ch1 + " " + ch2); Output:
ch1 and ch2: X Y
Summary

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
Assignment Operator (=)
In Java, the equal sign (=) is called the assignment operator. The assignment
operator is used to assign a value to a variable. Here are some examples.
// declare variables
int integerValue;
double floatValue;
char charValue;
// assign values to variables
integerValue = 875;
floatValue = 28.975;
charValue = 'b';
Assignment Operator (=)
The assignment occurs from right to left. The value on the right is copied into the
variable on the left.
The assign operator can be used to replace the contents of a variable with a new
value.
// declare variable
int num;
// assign values to variable 0
num = 0; 50
System.out.println(num); 225
num = 50;
System.out.println(num);
num = 225;
System.out.println(num);
Labeling Output
The term user-friendly is often associated with computer software. A user-friendly
program is one that is easy for a user to use and understand. One aspect of a user-
friendly program is the way in which the output of the program is displayed on the
screen. Look at the sample program below and the output produced.

int temperature = 98; 98

System.out.println(temperature); The temperature today is 98

System.out.println();
System.out.println("The high temperature today is " +
temperature);
Concatenation Operator
In Java, the plus sign (+) is used to label the data within a println statement. When
the plus sign is used in this context it is referred to as the concatenation operator.
Let's look at some examples.
int testGrade = 87; Test grade = 87
You can bench press 195 pounds.
int weight = 195; The cost of the shirt is 29.95
double cost = 29.95;

System.out.println("Test grade = " + testGrade);


System.out.println("You can bench press " + weight + "
pounds.");
System.out.println("The cost of the shirt is " + cost);
Concatenation Operator
The concatenation operator can also be used to provide spacing between data
items.
int num1 = 10; 10 20 30
10 20 30
int num2 = 20;
int num3 = 30;

System.out.println(num1 + " " + num2 + " " + num3);


System.out.println(num1 + " " + num2 + " " + num3);
String
String is not a primitive. It's a real type, but Java has special treatment for String.

// Create a string with a constructor


String s1 = new String("Who let the dogs out?");

// Just using "" creates a string, so no need to write it the


previous way.
String s2 = "Who who who who!";

// Java defined the operator + on strings to concatenate:


String s3 = s1 + s2;
Widening
class Simple{ Output:
public static void main(String[] args){
int a=10; 10
double f=a; // no explicit type casting 10.0

System.out.println(a);
System.out.println(f);
}}
Narrowing (Typecasting)
class Simple{ Output:
public static void main(String[] args){
10.5
float f=10.5f;
//int a=f; // compile time error 10
int a=(int)f; // explicit type casting

System.out.println(f);
System.out.println(a);
}}
Number to String
A number cannot be cast to a String—instead we must convert it with a method like
Integer.toString.
This method returns a String version of the int argument.

public class Program {


public static void main(String[] args) { Output:
int number = 100;
String result = Integer.toString(number); 100
System.out.println(result);
}
}
String to Number
We convert a String to an integer by parsing it. The Integer.parseInt method can do
this. It receives a String argument and returns an int.

public class Program {


public static void main(String[] args) {
Output:
String value = "100";
int result = Integer.parseInt(value); 100
System.out.println(result);
}
}
Overflow & Underflow
Overflow and underflow is a condition where you cross the limit of prescribed size
for a data type.
When overflow or underflow condition is reached, either the program will crash or
the underlying implementation of the programming language will have its own way
of handling things.
Flowed output is predictable and reproducible. That is, its behaviour is the same
every time you run the program.
Overflow Example
class Simple{
public static void main(String[] args){
int max_value = 2147483647;//upper limit for integer
max_value ++;

System.out.println(max_value); Output:
}}
-2147483648
Underflow Example
class Simple{
public static void main(String[] args){

int min_value = -2147483648;


min_value --;
Output:
System.out.println(min_value);
2147483647
}}
Wrapper Classes
In Java the overflow and underflow are more serious because there is no
warning or exception raised by the JVM when such a condition occurs.

We can see the upper and lower limit of each data type by looking at the
MAX_VALUE and MIN_VALUE constants in wrapper classes.

Example:
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
Scope of Variables
The scope of a variable refers to the section of code where a variable can be
accessed.
Scope starts where the variable is declared.
Scope ends at the termination of the statement block in which the variable was
declared.
There are three types of variables:
• Instance
• Local
• Class
Scope of Variables
• Local variables are declared in a method. Local variables are not visible outside the method.
• Instance variables are declared in a class, but outside a method. Visible in all methods. Can be
used in the entirety of the class. Every object in the class may have a different value of this.
• Class/static variables are declared with the static keyword in a class, but outside a method.
Can be used in the entirety of the class. Every object has the same static value of this.
Constant
There are several values in the real world which will never change.
A square will always have four sides,
PI to three decimal places will always be 3.142,
A day will always have 24 hours.
These values remain constant. When writing a program it makes sense to represent
them in the same way - as values that will not be modified once they have been
assigned to a variable. These variables are known as constants.
OPERATORS, ARITHMETIC AND
LOGICAL OPERATIONS
Arithmetic Operators
An expression is a combination of operators and operands, like a mathematical
expression.
The operands might be numbers, variables, or constants.
Expressions usually do a calculation such as addition or division.
In Java, you can form arithmetic expressions involving addition(+), subtraction(-),
multiplication(*), and division (/) in basically the same way that you would form
them in ordinary arithmetic or algebra.
Arithmetic Operators

Arithmetic Expression Result


15 + 28 43
6 - 20 -14
8*7 56
81 / 9 9
Division Operator (/)
If either or both operands to any numeric operator are floating point values, the
result is a floating point value.
The division operator produces results that are somewhat more complicated.
If both operands are integers, the / operator performs integer division, meaning
that any fractional part of the result is discarded.
If one or the other or both operands are floating point values, the / operator
performs floating point division, and the fractional part of the result is kept.
Division Operator (/)
Expression Result Type of Division Explanation
Performed
10 / 4 2 Integer Division 4 goes into 10 2.5 times, but the fractional part (.5) is
discarded so the answer is 2, an integer.
10.0 / 4 2.5 Floating Point First operand is a floating point number. Answer is 2.5, a
Division floating point number.
10 / 4.0 2.5 Floating Point Second operand is a floating point number. Answer is 2.5,
Division a floating point number.
10.0 / 4.0 2.5 Floating Point Both operands are floating point numbers. Answer is 2.5,
Division a floating point number.
Remainder Operator (%)
The remainder operator (%) also called the modulus operator.
The remainder operator returns the remainder after performing the division
operation.

Expression Result Explanation


17 % 4 1 17 divided by 4 equals 4 with a remainder of 1.
50 % 2 0 50 divided by 2 equals 25 with a remainder of 0.
9.3 % 5.1 4.2 9.3 divided by 5.1 equals 1 with a remainder of
4.2
Assignment Operators

Operator Description Example Equivalent Expression


= assignment x=y x = y;
++ increments a value by 1 x++ x = x+1;
-- decrements a value by 1 x-- x = x-1;
+= addition, then assignment x += y x = x + y;
-= subtraction, then assignment x -= y x = x - y;
*= multiplication, then assignment x *= y x = x * y;
/= division, then assignment x /= y x = x / y;
%= remainder, then assignment x %= y x = x % y;
Increment and Decrement Operators
Increment (++) and decrement (--) operators in Java programming let you easily
add 1 to, or subtract 1 from, a variable.

public static void main(String[] args){


int x = 5;
System.out.println(x);
x++; Output:
System.out.println(x);
5
x--;
System.out.println(x); 6
} 5
Increment and Decrement Operators
Increment and decrement operators can be placed before (prefix) or after (postfix)
the variable they apply to. If you place an increment or decrement operator before
its variable, the operator is applied before the rest of the expression is evaluated. If
you place the operator after the variable, the operator is applied after the
expression is evaluated.

int a = 5; a = 2; a = 2;
b = ++a; b = a++;
int b = 3;
is same as: is same as:
int c = a * b++; // c is set to 15 a = a + 1; b = a;
int d = a * ++b; // d is set to 20 b = a; a = a + 1;
Increment and Decrement Operators
int count=15;
int a, b, c, d;
a = count++;
b = count;
c = ++count;
d = count;
System.out.println(a + ", " + b + ", " + c + ", " + d);
Output:
What is the output?
15, 16, 17, 17
The Equality and Relational Operators
The equality and relational operators Operator Description
determine if one operand is greater
than, less than, equal to, or not == equal to
equal to another operand. != not equal to
> greater than
>= greater than or
equal to
< less than
<= less than or equal to
Conditional Operators
The && and || operators perform Conditional-AND and Conditional-OR
operations on two boolean expressions.

Operator Description
&& Conditional-AND
|| Conditional-OR
Conditional Operators

public static void main(String[] args){


int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1");
}
Operator Precedence
Precedence Level Operator Operation
1 () grouping
2 (int) cast
(double)
3 * multiplication
/ division
% remainder
4 + addition
- subtraction
5 = assignment
USER INPUT
Importing Utility Package
The Scanner class is a standard Java class that can be used to read user input from
the keyboard or a file.
The class contains several methods for reading user input from the keyboard.
To use the Scanner class in our programs, you must include the following import
statement at the top of our program.

import java.util.Scanner;

The import statement instructs the compiler to give a program access to the
Scanner class. The words java and util in the statement are called packages.
Scanner Class
Once we have imported the Scanner class into our program, we are ready to
instantiate a Scanner object.

Scanner keyboard = new Scanner(System.in);

The above code creates a Scanner object named keyboard. The name keyboard is
arbitrary, you can name your objects anything you want as long as you follow the
rules for declaring identifiers. It should, however, be a name that actually describes
what the object does.
The System.in you see in the parentheses tells the computer that you want to read
from the standard input device - the keyboard.
Scanner Class Example
// 1. Create a Scanner object
Scanner keyboard = new Scanner( System.in );
// 2. Prompt the user
System.out.print( "Type some data for the program: " );
// 3. Use the Scanner to read a line of text from the user.
String input = keyboard.nextLine(); //nextLine() is used for string entry

// 4. Now, you can do anything with the input string that you need to.
// Like, output it to the user.
System.out.println( "input = " + input );

// 5.Close the scanner object


keyboard.close();
Entry methods
The nextInt() method enables users to read integer values from the keyboard.
int num = keyboard.nextInt();

The nextDouble() method enables users to read decimal values from the keyboard.
double num = keyboard.nextDouble();

The nextLine() method enables users to read string values from the keyboard.
String input = keyboard.nextLine();

The next().charAt(0) method enables users to read the first letter entered.
char letter = keyboard.next().charAt(0);
next().charAt (0) Example
Scanner keyboard = new Scanner(System.in);
char letter;

System.out.print("Enter a letter--> ");


letter = keyboard.next().charAt(0); // read char value

System.out.println();
System.out.println("The letter entered = " + letter);
keyboard.close();
Enter a letter --> e

The letter entered = e


CONDITIONAL STATEMENTS
Decision Making
Decision making structures have one or more
conditions to be evaluated or tested by the
program, along with a statement or
statements that are to be executed if the
condition is determined to be true, and
optionally, other statements to be executed if
the condition is determined to be false.
Decision Making
if statement
An if statement consists of a boolean expression followed by one or more statements.
if...else statement
An if statement can be followed by an optional else statement, which executes when
the boolean expression is false.
nested if statement
You can use one if or else if statement inside another if or else if statement(s).
switch statement
A switch statement allows a variable to be tested for equality against a list of values.
If Statements:
Syntax:

if(Boolean_expression) {
// Statements will execute
// if the Boolean expression is true
}
If Statements:
Syntax example:

public class Test {

public static void main(String args[]) {


int x = 10;

if( x < 20 ) {
System.out.print("This is an if statement");
}
}
}
If-else Statements:
Syntax:

if(Boolean_expression) {
// Executes when the Boolean
// expression is true
}else {
// Executes when the Boolean
// expression is false
}
If-else Statements:
Exercise:
public class Test {

public static void main(String args[]) {


int x = 30;

if( x < 20 ) {
System.out.print("The number is smaller than
20");
}else {
System.out.print("The number is equal to or
greater than 20");
}
}
}
The if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if, else if, else statements there are a few points to keep in mind.
● An if can have zero or one “else” and it must come after any “else if”.
● An if can have zero to many “else if”s and they must come before the else.
● Once an “else if” succeeds, none of the remaining “else if”s or “else” will be
tested.
The if...else if...else Statement
Syntax:
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is
true.
}
The if...else if...else Statement
Exercise:
public class Test {
public static void main(String args[]) {
int x = 30;

if( x == 10 ) {
System.out.print("Value of X is 10");
}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {
System.out.print("Value of X is 30");
}else {
System.out.print("This is else statement");
}
}
}
Nested if Statement
Syntax:
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}
Nested if Statement
Syntax:
public class Test {

public static void main(String args[]) {


int x = 30;
int y = 10;

if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
Switch Statement
Syntax:
switch(expression) {
case value :
// Statements
break; // optional

case value :
// Statements
break; // optional

// You can have any number of case statements.


default : // Optional
// Statements
}
Switch Statement
● The variable used in a switch statement can only be integers,byte, short, char
and strings.
● You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
● The value for a case must be the same data type as the variable in the switch
and it must be a constant or a literal.
● When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
● When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
Switch Statement
● Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
● A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task when
none of the cases is true. No break is needed in the default case.
Switch Statement
Exercise:
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter grade: ");
char grade = keyboard.next().charAt(0);
keyboard.close();
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Very Good");
break;
...
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
ITERATION (LOOP)
Iteration (Loop)
There may be a situation when you need to
execute a block of code several number of times.
In general, statements are executed sequentially:
The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control
structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement
or group of statements multiple times.
Iteration (Loop)
Java programming language provides the following types of loop to handle looping
requirements.
while loop
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
for loop
Executes a sequence of statements for a given number of times.
do...while loop
Like a while statement, except that it tests the condition at the end (instead of
beginning) of the loop body.
For Loop
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to be executed a specific
number of times.
A for loop is useful when you know how many times a task is to
be repeated.
Syntax:
for(initialization; Boolean_expression; update)
{
// Statements
}
For Loop
● The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables and this step ends with a semi-colon (;).
● Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop will not be executed and control jumps to the next statement past
the for loop.
● After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can
be left blank with a semicolon at the end.
● The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
for(initialization; Boolean_expression; update) {
// Statements
}
For Loop
public class Test {
value of x : 10
value of x : 11
public static void main(String args[]) { value of x : 12
value of x : 13
value of x : 14
value of x : 15
for(int x = 10; x < 20; x = x + 1) { value of x : 16
System.out.println("value of x : " + x ); value of x : 17
value of x : 18
} value of x : 19

}
}
Infinite For Loop
// infinite loop
{
int x = 1;
for ( ; ; )
{
System.out.println(x);
x++;
}
}
Exercise I
Write a Java program to print the following output by using for loop:
Exercise II
Write a program that takes a number “n” from the user. Then prints that many
numbers from 1 to n, side by side (with a space in between each).

Sample Output:
How many numbers do you want to see?
20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
While
If the boolean_expression result is true, then the actions inside
the loop will be executed. This will continue as long as the
expression result is true.
When the condition becomes false, program control passes to
the line immediately following the loop.
Key point of the while loop is that the loop might not ever run.
When the expression is tested and the result is false, the loop
body will be skipped and the first statement after the while loop
will be executed.
Syntax:
while(Boolean_expression) {
// Statements
}
While
public class Test { value of x : 10
value of x : 11
public static void main(String args[]) { value of x : 12
int x = 10; value of x : 13
value of x : 14
value of x : 15
while( x < 20 ) { value of x : 16
System.out.println("value of x : " + x ); value of x : 17
x++; value of x : 18
} value of x : 19

}
}
Infinite While Loop
class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}
Exercise

Write a program that calculates the sum and average of grades numbers by the
user until user enters a number less than 0 or more than 100.

Output:

Enter next grade: 10


Sum of grades = 10
Average of grades = 10
Enter next grade: 30
Sum of grades = 40
Average of grades = 20
Enter next grade:
Do … while
● Notice that the Boolean expression appears at the
end of the loop, so the statements in the loop
execute once before the Boolean is tested.
● If the Boolean expression is true, the control jumps
back up to do statement, and the statements in the
loop execute again. This process repeats until the
Boolean expression is false.
Syntax:
do {
// Statements
}while(Boolean_expression);
Do … while
public class Test {
value of x : 10
value of x : 11
public static void main(String args[]) { value of x : 12
value of x : 13
int x = 10; value of x : 14
value of x : 15
value of x : 16
value of x : 17
do { value of x : 18
System.out.println("value of x : " + x ); value of x : 19

x++;
}while( x < 20 );
}
}
Do … while
while(condition) // no semicolon here
{
....
}

do
{
...
}
while(condition); // a semicolon here
Loop Control Statements:
The break statement in Java programming language
has the following two usages
● When the break statement is encountered inside
a loop, the loop is immediately terminated and
the program control resumes at the next
statement following the loop.
● It can be used to terminate a case in the switch
statement.
Loop Control Statements:
public class Test { 10
20
public static void main(String args[]) {

for(int x = 10; x < 100; x = x + 10) {


if( x == 30 ) {
break;
}
System.out.println( x );
}
}
}
Loop Control Statements:
The continue keyword can be used in any of the loop
control structures. It causes the loop to immediately
jump to the next iteration of the loop.
● In a for loop, the continue keyword causes control
to immediately jump to the update statement.
● In a while loop or do/while loop, control
immediately jumps to the Boolean expression.
Loop Control Statements:
public class Test { 10
20
public static void main(String args[]) { 40
50

for(int x = 10; x < 60; x = x + 10) {


if( x == 30 ) {
continue;
}
System.out.println( x );
}
}
}
Randomization
Generating random numbers in Java
Java provides various ways to generate random numbers using some built-in
methods and classes:

1. java.util.Random class
2. Math.random method
java.util.Random
For using this class to generate random numbers, we have to first create an
instance of this class and then invoke methods such as nextInt(), nextDouble(),
nextLong() etc using that instance.
We can generate random numbers of types integers, float, double, long,
booleans using this class.
We can pass arguments to the methods for placing an upper bound on the range
of the numbers to be generated. For example, nextInt(6) will generate numbers in
the range 0 to 5 both inclusive.
java.util.Random
import java.util.Random;
public class generateRandom{
public static void main(String args[]) {
Random rand = new Random(); // create instance of Random class
int x = rand.nextInt(1000); // Generate random integer in range
0 to 999
System.out.println("Random Integer: ” + x);

double y = rand.nextDouble(); // Generate Random double


System.out.println("Random Double: ” + y);
}
} Random Integer: 547
Random Double: 0.8369779739988428
Math.random()
The class Math contains various public class generateRandom
methods for performing various {
numeric operations such as, public static void main(String args[])
calculating exponentiation, {
logarithms etc. System.out.println("Random
double: " + Math.random());
One of these methods is random(), }
this method returns a double value }
with a positive sign, greater than or
equal to 0.0 and less than 1.0.
Random double: 0.13077348615666562
Random integers in a specific range
int max = 100;
int min = 50;
int value = (int)(Math.random()*(max – min + 1)) + min;
Or
int max = 100;
int min = 50;
int value = rand.nextInt(max – min + 1) + min;
ARRAYS
Need for Arrays
Problem: Getting 20 test scores from the user and calculating the average.
int test1, test2, test3,test4, test5,
test6, test7, test8, test9, test10,
test11, test12, test13, test14, test15,
test16, test17, test18, test19, test20; //Computation of average
int sum = 0;
//input statements double avg = 0;
sum = (test1 + test2 + test3 + test4 + test5 +
test1 = keyboard.nextInt(); test6 + test7 + test8 + test9 + test10 +
test2 = keyboard.nextInt(); test11 + test12 + test13 + test14 + test15 +
test3 = keyboard.nextInt(); test16 + test17 + test18 + test19 + test20);
test4 = keyboard.nextInt();
avg = sum / 20;
test5 = keyboard.nextInt();
test6 = keyboard.nextInt();
test7 = keyboard.nextInt();
test8 = keyboard.nextInt();
test9 = keyboard.nextInt();
test10 = keyboard.nextInt();
test11 = keyboard.nextInt();

if there were 50 or even 100


test12 = keyboard.nextInt();
test13 = keyboard.nextInt();
test14 = keyboard.nextInt();
test15 = keyboard.nextInt();

test scores...
test16 = keyboard.nextInt();
test17 = keyboard.nextInt();
test18 = keyboard.nextInt();
test19 = keyboard.nextInt();
test20 = keyboard.nextInt();
Need for Arrays
Array Solution:
Scanner keyboard = new Scanner(System.in);
int[] tests = new int[5]; // declare and initialize an array
int sum = 0, avg = 0;

for(int i = 0; i < 5; i++)


{
System.out.println("Not giriniz: ");
tests[i] = keyboard.nextInt(); // input test scores
sum += tests[i]; // sum test scores
}
avg = sum / 5; // compute class average
System.out.println("Ortalama: " + avg)
Arrays
An array stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
Declaring Arrays:
int[] tests; // Declare an integer array variable

Array variable(tests) is not the array. It is only the place holder for the array.
In order to create the array itself we must specify its type and how many elements
it is to contain. To declare an array variable you must include square brackets[]
between the data type and variable name.
Defining Arrays:
tests = new int[10]; // Define an array of 10 integers

This statement creates an array that will store 10 values of type int, and records a
reference to the array in the variable tests. The reference is simply where the
array is in memory.
Declaration, Instantiation and Initialization of Array
We can declare, instantiate and initialize the java array together by:
int[] array = {1, 3, 5, 7, 11, 13, 15};

Here is an example of a string array that uses an initializer list to assign values
to each of its elements.
String[] flag = {"red", "white", "blue"};
Common Error:
A common error that programmers make when using arrays is an
IndexOutOfBounds Exception.
This error occurs when you attempt to index an element of an array that does not
exist.
array = new int[3];
After this statement, array[0], array[1], array[2] are possible. array[3] is out of
bound.
Look at the following example.
int[] array = new int[3];
array[3] = 99; // This line causes an
IndexOutOfBounds exception
Example:
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList.
double[] myList = new double[10];
Logical Size & Physical Size
When creating (instantiating) an array we are required to give it a size. This size value
represents the physical size of the array. The physical size is the total number of
elements(cells) in the array.
For example, if you needed an array to store the names of students who showed up
for after school tutorials you might declare an array like the following:
//100 is the physical size of the array
String[] tutorials = new String[100];
Logical Size & Physical Size
// 100 is the physical size of the array
String[] tutorials = new String[100];
// counter - logical size of the array
int numStudents = 0;
The counter variable numStudents job is to keep track of how many students are
added to the array.
This counter variable represents the logical size of the array. The logical size of an
array is the current number of elements in the array that are occupied.
The foreach Loops:
Foreach loop or enhanced for loop enables you to traverse the complete array
sequentially without using an index variable.
public class TestArray {

public static void main(String[] args) { 1.9


double[] myList = {1.9, 2.9, 3.4, 3.5}; 2.9
3.4
// Print all the array elements 3.5
for (double x: myList) {
System.out.println(x);
}
}
}
Arrays can be used in:
Mathematical Analysis:
• Determine a minimum or maximum value
• Compute a sum, average, or mode
Analyzing Element Properties:
• Determine if at least one element has a particular property
• Determine if all elements have a particular property
• Access all consecutive pairs of elements
• Determine the presence or absence of duplicate elements
• Determine the number of elements meeting specific criteria
Reordering Elements:
• Shift or rotate elements left or right
• Reverse the order of the elements

You might also like