Object Oriented Programming - Introduction To Java Language

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 87

OBJECT

ORIENTED
PROGRAMMING
ICT 010
BASICS OF JAVA
PROGRAMMING
OBJECT-ORIENTED PROGRAMMING
WHAT IS JAVA?

Object-Oriented Platform Independent High Performance

The focus of OOP languages is With the use of Just-In-Time


not on structure, but on Write once, run Everywhere compilers, Java enables high
modeling data. performance.

Simple Robust

Eliminate error prone


Java is designed to be easy to
situations by emphasizing
learn. If you understand the
mainly on compile time error
basic concept of OOP Java, it
checking and runtime
would be easy to master.
checking.
HISTORY OF JAVA
James Gosling initiated the Java language project in1991.
Developed in Sun Microsystem.
It was first called Oak and was developed as a part of the
Green project.
In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies
JAVA VIRTUAL MACHINE
It provides the hardware platform specifications where we
compile the java programs.
Phase II: Compile
Java Source Byte
Code Java Compiler Code
(.java) (.class)

Phase I: Edit Java virtual machine Byte Code


Loaded into
Java Interpreter JVM
Phase IV: Verify
Phase III: Load
Phase V: Execute

Mac Windows Linux


EDITION OF JAVA
Java platform, Micro Edition (Java ME)
Provides a robust, flexible environment for applications
running on embedded and mobile devices in the Internet of
Things:
micro-controllers | sensors | gateways | mobile phones,
personal digital assistants (PDAs) | TV set-top boxes,
printers and more.
EDITION OF JAVA
Java platform, Standard Edition (Java SE)
lets you develop and deploy Java applications on desktop and
servers. Java offers the rich user interface, performance,
versatility, portability, and security that today's applications
require
EDITION OF JAVA
Java platform, Enterprise Edition (Java EE)
The standard in community-driven enterprise software.
Developed using the java community process, with
contributions from industry experts, commercial and open
source organizations, Java User Groups, and countless
individuals.
PROGRAM EDITOR
This enables programmers to create a program file, edit the
file and then save the file. (e.g. Notepad)
COMMANDS

set path: //to address the path


setting of the java compiler.

Javac //used to compile a java


program .

Java //used to execute a java


program.
INTEGRATED DEV. ENVIRONMENT
The platform that is used to write, compile, run, and
debug such as Xcode.
Integrated with
Text Editor | Compiler | JDK
INTRODUCTION TO JAVA CODE
Class name is hellojava

public | private as access modifier

static can be accessed without requiring an


instantiation of the class to which it belongs

void returns no value

main first method to invoke

String [] args contains the supplied


command-line arguments as an array of
String objects
VARIABLE
Place holder for value, nothing but reserve memory
locations to store data.
Variable Declaration
x = 10 value Start with a-z | A-Z | _ | $
No number in start of declaring unit name
No spaces or special characters are allowed
Variable names are case-sensitive
variable Cannot use a java keyword (reserved word)
Not too long hard to understand
Not too short can’t understand
EXPRESSION VS STATEMENT
Expression - any section of the
code that evaluates, usually created
to produce a new value.

Statement - is a complete line of


code that performs some action
and can include one or more
expression.

Block of Statement – a group


of zero or more statements.
Expression
Block of Statements
Statement
BYTE
Type Size in Bytes Range Store
byte 1 byte -128 to 127 Integer data type
SHORT
Type Size in Bytes Range Store
short 2 bytes -32,768 to 32,767 Integer data type
INT
Type Size in Bytes Range Store
Int 4 bytes -2147483648 -2147483647 Integer data type
LONG
Type Size in Bytes Range Store
long 8 bytes -9223372036854775808 to 9223372036854775807 Integer data type
FLOAT
Type Size in Bytes Range Store
float 4 bytes 1.4E-45 to 3.4028235E38 Floating point
DOUBLE
Type Size in Bytes Range Store
double 8 bytes 4.9E-324 to 1.7976931348623157E308 Floating point
BOOLEAN
Type Size in Bytes Range Store
boolean 1 bit True/false
CHAR
Type Size in Bytes Range Store
char 2 bytes \u0000 to \uFFFF Unicode Character
STRING
STRING
INT, DOUBLE, FLOAT, LONG >> STRING
STRING >> INT, DOUBLE, FLOAT, LONG

try{ i = Integer.parseInt(String);
} catch(NumberFormatException e)
{
// print e to show exception
}
RELATIONAL OPERATOR
Operator Use Description
A relational
> op1 > op2 op1 is greater than op2 operator
compares two
< op1 < op2 op1 is less than op2 values and
determines the
>= op1 >= op2 op1 is greater or equal op2
relationship
<= op1 <= op2 op1 is less or equal op2 between them.
These include
== op1 == op2 op1 and op2 are equal numerical equality
and inequalities.
!= op1 != op2 op1 and op2 are not equal
LOGICAL BOOLEAN OPERATOR
Logical AND (&&)
exp1 exp2 result

True True True

True False False

False True False

False False False


LOGICAL BOOLEAN OPERATOR
Logical Exclusive OR (^)
exp1 exp2 result

True True False

True False True

False True True

False False False


LOGICAL BOOLEAN OPERATOR
Logical OR (||)
exp1 exp2 result

True True True

True False True

False True True

False False False


LOGICAL BOOLEAN OPERATOR
Logical Not (!)
exp1 result

True False

False True
BITWISE AND BIT SHIFT OPERATOR
Operator Description

| Bitwise OR

& Bitwise AND

^ Bitwise XOR

<< Left Shift

>> Right Shift


CONDITIONAL OPERATOR
Conditional operator (?:) Conditional operator is also
known as the ternary operator.

This operator consists of three


operands and is used to
evaluate Boolean expressions.

The goal of the operator is to


decide, which value should be
assigned to the variable

Syntax
variable x = (expression) ? value if true : value if false
OPERATOR PRECEDENCE
Prece Operator Type
dence

1 () Parenthesis

2 ++ -- ! Inc & dec

3 */% Arithmetic

4 +- Arithmetic

5 >> << Bit Shift

6 < > <= >= Relational

7 == != Relational

8 &|^ Bitwise Ope

9 && || Logical Ope


ASSIGNMENT AND SHORTCUT OPE
Assignment x=y x=y
Addition assignment x += y x=x+y
Subtraction assignment x -= y x=x-y
Multiplication assignment x *= y x=x*y
Division assignment x /= y x=x/y
Remainder assignment x %= y x=x%y
Left shift assignment x <<= y x = x << y
Right shift assignment x >>= y x = x >> y
Bitwise AND assignment x &= y x=x&y
Bitwise XOR assignment x ^= y x=x^y
Bitwise OR assignment x |= y x=x|y
IF | IF-ELSE-IF | IF ELSE NESTED IF
STATEMENT The selection structure tests a
condition, then executes one
sequence of statements instead
of another, depending on whether
the condition is true or false.

A condition is any variable or


expression that returns a
Boolean value (TRUE or FALSE)
If (expression 1) {
//statement
}else if (expression 2){
//statement
}else{
//default statement
}
While loop executes the code
SWITCH STATEMENT block only if the
condition is True.

Do While executes the


statements in the code block
at least once even if the
condition Fails

Switch(expression) {
Case value:
//statement 1
break; //optional
Case value:
//statement 2
break; //optional
default: :
//statement 3
break; //optional
}
WHILE AND DO WHILE LOOP
While loop executes the code
block only if the
condition is True.

Do While executes the


statements in the code block at
least once even if the condition
Fails
Syntax
While (boolean condition)
{
loop statements…
}
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
}
ENHANCE FOR LOOP Mainly used to traverse a
collection of elements including
arrays.
Declaration − The newly
declared block variable is of a
type compatible with the
elements of the array you are
accessing.
Expression − This evaluates to
the array you need to loop
through.
Syntax
for (declaration : expression) {
// Statements
}
LOOP CONTROL STATEMENTS
Break statement Terminates
the loop or switch statement
and transfers execution to the
statement immediately
following the loop or switch.

Continue statement Causes


the loop to skip the remainder
of its body and immediately
retest its condition prior to
reiterating.
NESTED LOOP A loop within a loop, an
inner loop within the body of
an outer one.
The first pass of the
outer loop triggers the
inner loop, which executes to
completion.
Outer loop represent the rows
and inner loop for the columns
Syntax
for (declaration : expression) {
// Statements of 1st loop
for(declaration : expression){
// Statements of 2nd loop
}
}
LABELLED LOOP Labelled Loop
If we need to jump out from
the outer loop using break
statement given inside inner
loop, The answer is to
define label along with colon(:)
sign before a loop.
Syntax
outer:
for (declaration : expression) {
// Statements of 1st loop
for(declaration : expression){
// Statements of 2nd loop
break outer;
}
}
LE PRACTICE!
Write a program called Grades,
which prompts user Input the prelim,
midterm, pre-final and final grades.
Compute the final grade using the formula
FG = 20Prelim + 20%Midterm + 30%Pre-Final
+30%Final.

Prelim: 90
Midterm: 85
Pre-final: 95
Final: 80
Final Grade: 87.5
LE PRACTICE!
Write a program that averages the rain fall for three months,
April, May, and June. Declare and initialize a variable to the
rain fall for each month. Compute the average, and write out
the results, something like:

Rainfall for April: 12


Rainfall for May : 14
Rainfall for June: 8
Rainfall average is : 11.33333333
LE PRACTICE!
Write a program that takes radius of a circle from the
user and calculates the diameter, circumference and area of
the circle and display the result.The formula to compute is
diameter = radius*2, circumference = 2πr and area = πr2
where π (pi)= 3.1416.

Write a program to calculate rectangle perimeter and area using its


length and width. Formula A=lw, P = 2l + 2W
LE PRACTICE!
Write a program which program converts an input value in degrees Fahrenheit to the
corresponding value in degrees Centigrade. The formula is Centigrade = (Fahrenheit-32) *
5.0/9.0.

Write a program that takes three double values x, v, and t and prints the value of x + vt + gt2 /2,
where g is the constant 9.78033.
LE PRACTICE!
Write the equivalent program of the Ohm's law relates the resistance
of a electrical device (like a heater) to the electric current flowing
through the device and the voltage applied to it.
The law is: I = V/R. Here,V is the voltage (measured in volts),
I is the current (measured in amps), and R is the resistance
LE PRACTICE!
At a movie theater box office a person less than age 17 is charged the
"child rate". Otherwise a person is charged "adult rate."

Enter age: 20
Charge: Adult Rate
LE PRACTICE!
A car rental agency wants a program to implement its rules for who can rent a car.
The rules are: a.A renter must be 21 years old or older.
b.A renter must have a credit card with credit of $10,000 or more.

Enter age: 22
Do you have a credit card[Y/N]? Y
How much is the credit amount? 9000
Sorry, but you cannot rent a car.

Enter age: 22
Do you have a credit card[Y/N]? Y
How much is the credit amount? 15000
You can rent a car. Here is the car key!
LE PRACTICE!
You would like to buy a new $25,000 red Toyota Supra.
To buy the car you could pay cash for it, or you could buy it on credit.
Therefore, to buy this car, you need enough cash or enough credit.
Write a problem to help you determine if you can buy the car.

Buy a car through [1] Cash [2] Credit Card: 1


How much is your cash? 20000
I am sorry but your cash is not enough to buy the car.
Buy a car through [1] Cash [2] Credit Card: 2
How much is your credit amount? 25000
Thank you for transacting with us.
LE PRACTICE!
Create a program that will input the username and password. If the inputted username and
password similar to your hidden username and password display “Congratulations! Access
Granted!” otherwise, display “Access Denied! Nice Try!”

Enter your username: user


Enter your password: abc123
Congratulations! Access Granted!
LE PRACTICE!
Write a Java program that keeps a number from the user and generates
an integer between 1 and 7 and displays the name of the weekday.

Enter a number: 4
Day:Thursday
LE PRACTICE!
Write Java program to allow the user to input his/her age. Then the program will show if the
person is eligible to vote. A person who is eligible to vote must be older than or equal to 18
years old.

Enter your age: 18


You are eligible to vote.
LE PRACTICE!
Write a Java program to calculate the
revenue from a
sale based on the unit price and quantity of a product
input by the user.The discount rate is 10% for the
quantity purchased between 100 and 120 units,
and 15% for the quantity purchased greater than 120 units.
If the quantity purchased is less than 100 units, the discount rate is 0%.

Enter unit price: 25


Enter quantity: 110
Total amount: 2750.0
Discount: 275.0 (10.0%)
The revenue from sale: 2475.0
LE PRACTICE!
Write a program in Java to input n numbers from keyboard and find their sum and average.

Test Data
Input a numbers : 5
5 numbers are:
1
2
3
4
5
The sum of 5 no is : 15
The Average is : 3.0
LE PRACTICE!
Write a program in Java to display the cube of the number up to given an integer.
Input number of terms : 4
Number is : 1 and cube of 1 is : 1
Number is : 2 and cube of 2 is : 8
Number is : 3 and cube of 3 is : 27
Number is : 4 and cube of 4 is : 64
LE PRACTICE!
Write a program in Java to display the n terms of odd natural number and their sum. Go to the editor

Input number of terms is: 5


The odd numbers are :
1
3
5
7
9
The Sum of odd Natural Number up to 5 terms is: 25
LE PRACTICE!
Create a program that will input the username and password. If the inputted username and password similar to
your hidden username and password display “Congratulations! Access Granted!” otherwise, display “Access
Denied! Try Again [Y/N]?” If the user answered Y, repeat the login otherwise exit the program.

Enter your username: user


Enter your password: abc123
Congratulations! Access Granted!

Enter your username: user


Enter your password: abc125
Access Denied! Try Again[Y/N]? Y
Enter your username: …
Enter your password: …

LE PRACTICE!
Create a program that will input the username and password. If the inputted username and password similar to
your hidden username and password display “Congratulations! Access Granted!” otherwise, display “Access
Denied! Try Again [Y/N]?” If the user answered Y, repeat the login otherwise exit the program.

Enter your username: user


Enter your password: abc123
Congratulations! Access Granted!

Enter your username: user


Enter your password: abc125
Access Denied! Try Again[Y/N]? Y
Enter your username: …
Enter your password: …

LE PRACTICE!
Write a program in Java to display the pattern like right angle
triangle with a number.

Input number of rows : 5


1
12
123
1234
12345
ARRAY
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.
ONE DIMENSIONAL ARRAY

A one-dimensional
array is, essentially, a
list of like-typed
variables. To create
an array, you first
must create an array
variable of the
desired type.
TWO DIMENSIONAL ARRAY

The elements of
a 2D array are
arranged in rows
and columns, and
the new operator
for2Darrays specifie
s both the number
of rows and the
number of columns.
ACCESSING ARRAY IN ENHANCE FOR LOOP
The for-each loop iterate
through items of
arrays/collections.

for (type variableName : collection){


loopBody
}

The variableName specifies the type


of variable and its name. The collection
represents the name of the array. The
loopBody is the stamen being executed
upon.
1D ARRAY
EXAMPLE

The final keyword are used


to create a constants in the
program.
2D ARRAY EXAMPLE

arrayName [row] [col] = data;


N – DIMENSIONAL ARRAY
JAGGED ARRAY
ARRAY LIST
MAP
WRAPPER CLASSES
String is basically an
object that
represents sequence
of char values.

Java String class


provides a lot of
methods to perform
operations on
string.
STRING CLASS
String is basically an
object that
represents sequence
of char values.

Java String class


provides a lot of
methods to perform
operations on
string.
CREATING A STRING OBJECT

String Literal By New Keyword


JAVA STRING
CLASS METHODS
Method Description
char charAt(int index) Returns char value for the particular
index

int length() Returns string length

String substring(int Index) Returns substring for given begin index.

boolean contains(Char Returns true or false after matching the


sequence of char value.
Sequence s)
boolean equals(Object Checks the equality of string with the
given object.
another)
boolean isEmpty() Check if string is empty

String concat(String str) Concatenates the specified string

String toLowerCase() Return a string in lowercase

String toUpperCase() Return a string in uppercase

String trim() Removes beginning and ending spaces of


the stirng
WHAT ARE EXCEPTIONS AND ERRORS
• Errors are conditions which causes the program to terminate.
Types of Errors
• In java when an error is detected an Exception is thrown.
• Exception can be caught and handled with the try catch Program Error User Error
statement.
USE OF EXCEPTION try {
• Exceptions separate error handling code from regular code. // test code
• Exceptions propagate errors up the call stack. }catch(Exception e){
WHEN TO HANDLE ERRORS USING EXCEPTION //exception handling code
• User Input }finally{
• File I/O //code after try/catch, for
cleaning of code.
}
BUILT-IN EXCEPTIONS
•Many exceptions and errors are automatically generated by the Java
virtual machine.
•Errors, generally abnormal situations in the JVM, such as:
o Running out of memory
o Infinite recursion
o Inability to link to another class
•Runtime exceptions, generally a result of programming errors, such
as:
o Dereferencing a null reference
o Trying to read outside the bounds of an array
o Dividing an integer value by zero
EXCEPTION HIERARCHY

• All Exceptions are subtype of java.lang


• Exceptions are subtype of throwable which is
the superclass of all types of error and includes
the Error class
• Error class represents something we can’t deal
about.
EXCEPTION HIERARCHY
• Write a Java Program to sort a numeric array
• Write a Java program to sum and average values of an array.
• Write a Java program to test if an array contains a specific value
• Write a Java program to find the index of an array element
• Write a Java program to insert an element (specific position) into an array.
• Write a Java program to find the maximum and minimum value of an array.
WRAPPER CLASSES
• public class Debug
• {
• public static void main(String[] args)
• {
• integer i = 2.3;
• Double d = 5;
• System.out.println( i.intValue );
• System.out.println( doubleValue() );
• // Print out the min and max values possible for integers
• System.out.println(Integer.min_value);
• System.out.println( int.MAX_VALUE() );
• }
• }
Java Exception

-is a n event which occurs during the execution of a


program , that disrupts the normal flow of the program
instructions . When an error occurs within a method , the
method creates an object and hands it off to the runtime
system. The object , called an exception object contains
information about the error including its type and the state
of the program when the error occur red. Creating an
exception object and handling it to the runtime system is
called throwing an exception.
- After a method throws an to handle it. The set of possible
“something” to handle the exception is the ordered list of
methods that had been called to get the method where
the error occurred. The list of methods is known as the
call stack.
Java Exception
Types of Errors

1. Syntax Error - Arise because the rules of the language are not followed.
2. Logic Error – Indicates the logic used for coding doesn’t produce
expected outcome/output.
3. Runtime Errors – Occurs because the program tries to perform an
operation that is impossible to complete.

Types of Exceptions

Exceptions can be broadly categorized into two types.

1. Unchecked Exceptions

- Subclasses of RunTime Exception and Error


- Does not require explicit handling
Java Exception
- RunTime Errors are internal to your program, so you can get rid of them by
debugging your code.

Example: null pointer exception, index out of bounds exception, division by zero
exception .

Sample Program

public class TestExceptions {


public static void main( String args[]){

String str = null;


int len = str.length();
}}

Output:
Exception in thread “main” java .lang.NullPointerException at
test.TestException.main (TestException.java:4)
Java Exception
2. Checked Exceptions

- Must be caught or declared in a throws clause.


- Compile will issue an error if not handled appropriately.
- Subclasses of Exceptions other than subclasses of RunTimeExceptions.
-Other arrive from external resources

Java handles exceptions via 5 keywords, try, catch, fin ally, throw and throws.

1. Try Block – Write code inside this block which could generate errors.
2. Catch Block – Code inside this block is used for exception handling.
When the exception is raised from try block, only then catch block would
execute.
3. Finally Block – This block always execute whether exception occurs or not.
It is used for freeing resources, cleaning up, closing connections.
Java Exception
The basic structure of using try-catch-finally block is shown:

try{
//write code that could generate exceptions
}
catch(<exception to be caught>){
//code for exception handling
}
finally{
//any clean-up code
}

4. Throw - To manually throw an exception.


5. Throws – if method is not interested in handling the exception then it can be
throw back the exception to the caller method using throws keyword.
Java Exception
Sample Program:

public class DivideException{


public static void main(String args[]){

int result = division(100,0);

System.out.println("Result:" +result);
}

public static int division(int totalSum, int totalNumber){

int quotient = 1;

System.out.println("Computing Division");

You might also like