Chapter - 1 Introduction To Object-Oriented Programming

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

Course Title: Object Oriented Programming.

Credit Hour: 3 hrs.


Course Code: CoSc2051.
ECTS: 5 [2 Lecture , 3 Lab and 2 Tutorial Hours]
Lecture Schedule: Every _____________

Bedasa Wayessa
[email protected]
Compiled by Bedasa OOP- CoSc2051 1
Classroom Rules
• Late comer will only tolerated for the first 5 minutes of every class
• Talk to me and Not to each other
• Do not sleep
• Do not use phones
• Fail to obey the Classroom rule  face 2  3 class ban

Compiled by Bedasa OOP- CoSc2051 2


Assignment Submission
 Guidelines for submission will be provided with every assignment
 Re-grade requests will ONLY be entertained within one week after
the assignments have been handed back to students or assignment due
date

 IMPORTANT: Late submissions are allowed ONLY until 1 day following

the deadline, with 10% marks deduction.

 IMPORTANT: Late + Copy = ZERO Marking

Compiled by Bedasa OOP- CoSc2051 3


QUIZZES
• Quizzes will NOT be announced
• Re-grade requests will only be entertained within one week after the
marked quizzes have been handed back to students [with tangible and
acceptable reason only]

Compiled by Bedasa OOP- CoSc2051 4


Course description
• This programming course emphasizes the methodology of programming
from an object-oriented perspective and software engineering principles.
• It allows students to develop the ability to analyze programming
problems and design and document suitable solutions and to implement
reliable and robust software using contemporary program design
methods.
• Topics to be dealt with are:
– classes: data abstraction, information hiding, overloading; inheritance;
polymorphism; exceptions handling.

Compiled by Bedasa OOP- CoSc2051 5


Course objectives
• Upon successful completion of the course, students will be able to:
– Explain the basic object oriented concepts
– Successfully code, debug and run programs with appropriate
development environment
– Work on more advanced programs
– Have clear differentiation between structural and object oriented
programming paradigms

Compiled by Bedasa OOP- CoSc2051 6


Course outline
• Chapter 1: Introduction to Object-Oriented Programming (4 hrs)
– 1.1. Types of programming paradigms
– 1.2. Overview of OO principles
– 1.3. Editing, Compiling and Interpreting
• Chapter 2: Objects and Classes (6 hrs)
– 2.1.Defining a class
– 2.2.Creating an Object
• 2.3.5. Destroying Objects
– 2.3.Instantiating and using objects
• 2.3.6. Enumerated Types
• 2.3.1. Printing to the Console
2.4.Instance fields
• 2.3.2. Methods and Messages
2.5.Constructors and Methods
• 2.3.3. Parameter Passing
2.6.Access Modifiers
• 2.3.4. Comparing and Identifying Objec ts
2.7.Encapsulation
Compiled by Bedasa OOP- CoSc2051 7
Course outline
• Chapter 3: Inheritance and Polymorphism (8 hrs)
– 3.1.Inheritance
– 3.2.Casting
– 3.3.Method Overriding and Overloading
– 3.4.Polymorphism
– 3.5.Super
– 3.6.The Object Class
– 3.7.Abstract Classes
– 3.8.Interfaces
– 3.9.Using Interfaces

Compiled by Bedasa OOP- CoSc2051 8


Course outline
• Chapter 4: Exception Handling (4 hrs)
– 4.1.Exceptions Overview
– 4.2.Catching Exceptions
– 4.3.The finally Block
– 4.4.Exception Methods
– 4.5.Declaring Exceptions
– 4.6.Defining and Throwing Exceptions
– 4.7.Errors and Runtime Exceptions

Compiled by Bedasa OOP- CoSc2051 9


Course outline
• Chapter 5: Packages (4 hrs)
– 5.1.Packages
– 5.2.The import Statement
– 5.3.Static Imports
– 5.4.CLASSPATH and Import
– 5.5.Defining Packages
– 5.6.Package Scope

Compiled by Bedasa OOP- CoSc2051 10


Course outline
• Chapter 6: Data structures (6 hrs)
– 6.1. The Set
– 6.2. Set Implementation Classes
– 6.3. The List
– 6.4. List Implementation Classes
– 6.5. The Queue
– 6.6. Queue Implementation Classes
– 6.7. Map/ dictionary

Compiled by Bedasa OOP- CoSc2051 11


Teaching - Learning methods
• Two contact hours of lectures, three hours of lab and two hours of tutorials
per week.
• Students do home assignments.

Assessment method
Task Task Type Session Max Mark
1 Test Lab & Theory Individual 30
2 Assignments/Quiz Lab & Theory Individual 10
3 Project Lab Individual/group 10
4 Final Exam both Individual 50
Total 100

Compiled by Bedasa OOP- CoSc2051 12


Course Information
• References/textbooks
• Text book
1. H.M. Deitel, P.J. Deitel, Java How to Program. 8th ed. Prentice Hall
2. Eckel, Bruce. Thinking in Java. 4th Ed. New Jersey: Prentice Hall
• Additional
1. Y. Daniel Liang - Introduction to Java Programming. Comprehensive
Version-Pearson (2014)
2. John Dean, Ray Dean - Introduction to Programming with Java A
Problem-Solving Approach-McGraw-Hill (2008)
• Link:
– https://docs.oracle.com/javase/tutorial/
– Online Java Compiler - online editor (onlinegdb.com)
– Online Java Compiler (programiz.com)

Compiled by Bedasa OOP- CoSc2051 13


Mapping Learning Outcomes to Skill Sets
• General Objective
• Demonstrate how real-world entities such as inheritance, hiding,
polymorphism, and son can be implemented in programming.
• Learning outcomes
• Understand the basic object oriented concepts.
• Successfully code, debug and run programs with object oriented
principles.
• Apply object oriented programming concepts to solve problems.

Compiled by Bedasa OOP- CoSc2051 14


Introduction to Object-
Oriented Programming

Compiled by Bedasa OOP- CoSc2051 15


Introductions
• Chapter 1: Introduction to OOP
– Types of programming paradigms
– Overview of OO principles
– Editing, Compiling and Interpreting

Compiled by Bedasa OOP- CoSc2051 16


Introductions
 All computer programs consist of two elements: code and data.
 A Programming language is a notational system for describing
tasks/computations in a machine and human readable form.
 Most computer languages are designed to facilitate certain operations
and not others:
 Numerical computation, or text manipulation, or I/O.
 More broadly, a computer language typically embodies a particular
programming paradigm.
 Which programming language?

Compiled by Bedasa OOP- CoSc2051 17


Introductions
• What is a "programming paradigm"?
– Paradigm: "A philosophical and theoretical framework of a scientific
school or discipline within which theories, laws, and generalizations and
the experiments performed in support of them are formulated;
– broadly: a philosophical or theoretical framework of any kind“
• Paradigms as “ways of organizing thought”
– Programming paradigm = The basic structuring of thought
underlying the programming activity.
• Programming paradigm (in this course)
– Programming technique( Examples: 'Divide and conquer’)
– Programming style
– Programming culture
Compiled by Bedasa OOP- CoSc2051 18
Programming Paradigms : PL
 Since a task can be solved in different ways (paradigms), the language
used to describe the solution differs in abstractions, structures due to
the way in which the problem is solved.
 A programming paradigm is a fundamental style of computer
programming.
 Programming paradigms differ in:
– The concepts and abstractions used to represent the elements of
a program (such as objects, functions, variables, constraints, etc.)
– The steps that compose a computation (assignation, evaluation, data
flow, control flow, etc.).

Compiled by Bedasa OOP- CoSc2051 19


Programming Paradigms : PL
.
Imperative/ Object
Algorithmic Declarative Oriented
(HOW) (all about what)

Functional Logic
Programming Programming
Algol Lisp Prolog Smalltalk
Cobol Haskell Simula
PL/1 ML C++ , C#
Ada Miranda Java ,VB
Fortran APL
C
Modula-3

Compiled by Bedasa OOP- CoSc2051 20


Imperative paradigms
 First do this and next do that.
 It is based on commands that update variables in storage.
 The main : Explicitly tells the computer "how" to accomplish it.
 The Latin word imperare means “to command”.
 E.g GO TO command
 It works by changing the program state through assignment statements.
 It performs step by step task by changing state.
 The paradigm consist of several statements and after execution of all
the result is stored.
 Includes procedural & structured programming.
 Many people also find the imperative paradigm to be a more natural
way of expressing themselves.
Compiled by Bedasa OOP- CoSc2051 21
Imperative paradigms
 Advantages :
 Efficient;
 Close to the machine;
 Popular; Familiar.
 Disadvantages :
 Semantics of a program can be complex to understand/prove
 Debugging is harder(process of identifying and resolving errors);
 Abstraction is more limited than with some paradigms;
 Order is crucial, which doesn't always suit itself to problems.
 Parallel programming is not possible

Compiled by Bedasa OOP- CoSc2051 22


Imperative paradigms
 Examples of Imperative programming paradigm:
 C : developed by Dennis Ritchie and Ken Thompson
 Fortran : developed by John Backus for IBM
 Basic : developed by John G Kemeny and Thomas E Kurtz
public class Main {
public static void main(String[] args) {

// Step 1: Declare and initialize variables


int x = 10;
int y = 5;

// Step 2: Perform a calculation (addition) and store the result


int sum = x + y;

// Step 3: Print the result


System.out.println("The sum is: " + sum);
}
} OOP- CoSc2051
Compiled by Bedasa 23
Declarative Programming
 Definition: Opposite of imperative programming; focuses on what
result is needed rather than how to execute a task.
 Aim: Brings programming languages closer to human language and
thinking.
 Characteristics:
 Considers programs as theories of logic.
 Simplifies writing parallel programs.
 Emphasizes what needs to be done, not how to do it.
 Core Principle: Declares the desired result without specifying how it is
produced.
 Languages: SQL, HTML, Prolog, Haskell (for functional).
 E.g. Select * from Student;

Compiled by Bedasa OOP- CoSc2051 24


Declarative Programming
import java.util.Arrays;

public class Main {


public static void main(String[] args) {
// Declarative approach using Java Streams
int[] numbers = {1, 2, 3, 4, 5};

// Describe what you want (sum the numbers)


int sum = Arrays.stream(numbers).sum();

System.out.println(sum); // Output: 15
}
}
 import java.util.Arrays; is necessary to use the Arrays class.
 An array of integers is defined: int[] numbers = {1, 2, 3, 4, 5};.
 The Arrays.stream(numbers) method converts the array into a
stream, which allows you to perform operations on it.

Compiled by Bedasa OOP- CoSc2051 25


Functional programming paradigms
 In this paradigm we express computations as the evaluation of
mathematical functions.
 Functional programming paradigms treat values as single entities.
 Unlike variables, values are never modified.
 Instead, values are transformed into new values.
 Computations of functional languages are performed largely through
applying functions to values,.
 It uses functions to perform everything.
 It is a form of declarative programming.
 In this, the command execution order is not fixed.

Compiled by Bedasa OOP- CoSc2051 26


Functional programming paradigms
 Advantages:
 The high level of abstraction, removes the possibility of committing many
classes of errors;
 The lack of dependence on assignment operations, allowing programs to be
evaluated in many different orders.
 This evaluation order independence makes function-oriented languages
good candidates for programming massively parallel computers;
 The absence of assignment operations makes the function-oriented programs
much more amenable to mathematical proof and analysis than are imperative
programs.
 Disadvantages:
 Perhaps less efficiency
 Problems involving many variables or a lot of sequential activity that are
sometimes easier to handle imperatively or with object-oriented programming.
Compiled by Bedasa OOP- CoSc2051 27
Logic programming paradigms
 The LP takes a declarative approach to problem-solving.
 Various logical assertions about a situation are made, establishing all
known facts.
 Then queries are made.
 The role of the computer becomes maintaining data and logical
deduction.
 Logical Paradigm Programming:
 A logical program is divided into three sections:
1. A series of definitions/declarations that define the problem domain
2. Statements of relevant facts
3. Statement of goals in the form of a query

Compiled by Bedasa OOP- CoSc2051 28


Logic programming paradigms
 While the functional paradigm emphasizes the idea of a
mathematical function, the logic paradigm focuses on predicate
logic, in which the basic concept is a relation.
 Logic languages are useful for expressing problems where it is not
obvious what the functions should be.
 For example consider the uncle relationship:
 A given person can have many uncles, and another person can be
uncle to many nieces and nephews.
 Let us consider now how we can define the brother relation in terms
of simpler relations and properties father, mother, and male.
 Using the Prolog logic language one can say:

Compiled by Bedasa OOP- CoSc2051 29


Logic programming paradigms
clauses
brother(X,Y) :- /* X is the brother of Y */
/* if there are two people F and M for which*/
father(F,X), /* F is the father of X */
father(F,Y), /* and F is the father of Y */
mother(M,X), /* and M is the mother of X */
mother(M,Y), /* and M is the mother of Y */
male(X). /* and X is male */
 Predicates
 mother(sara, jack). /* sara is the mother of jack */
 is fact.
 Query
? mother(sara, jack).
Yes

Compiled by Bedasa OOP- CoSc2051 30


Logic programming paradigms
 Advantages:
 system solves the problem, so the programming steps themselves
are kept to a minimum;
 Proving the validity of a given program is simple.

Compiled by Bedasa OOP- CoSc2051 31


The Object-Oriented Paradigm
 Object Oriented Programming (OOP) is a paradigm in which real-
world objects are each viewed as separate entities having their own
state which is modified only by built in procedures, called methods.
 Alan Kay characterized the fundamental of OOP as follows:
– Everything is modeled as object
– Computation is performed by message passing:
• objects communicate with one another via message passing.
– Every object is an instance of a class where a class represents a
grouping of similar objects.
– Objects are organized into classes, from which they inherit methods
and equivalent variables.

Compiled by Bedasa OOP- CoSc2051 32


Fundamental Principles of OOP
1. Objects
2. Classes
3. Methods and Messages
4. Abstraction
5. Inheritance
6. Encapsulation
7. Polymorphism

Compiled by Bedasa OOP- CoSc2051 33


OOP Concepts
 In object-oriented programming (OOP), programs are organized into
objects.
 The properties of objects are determined by their class
 Objects act on each other by passing messages.
 Object
 Definition:
An object is a software bundle that has State and Behavior.
 Software Objects are often used to model real-world objects.
 Example:
dogs have states (name, color, hungry, breed) and
behaviors (bark, fetch, and wag tail).

Compiled by Bedasa OOP- CoSc2051 34


Object Examples
 Example 1: Dogs
 States: name, color, breed, and “is hungry?”
 Behaviors: bark, run, and wag tail
 Example 2: Cars
 States: color, model, speed, direction
 Behaviors: accelerate, turn, change gears

Compiled by Bedasa OOP- CoSc2051 35


Class
 Definition: A class is a blueprint that defines the states and the
behaviors common to all objects of a certain kind.
 In the real world, you often have many objects of the same kind.
 For example, a guard dog, herding dog, snoop dog . . .
 Even though all dogs have four legs, and bark, each dog’s behavior is
independent of other dogs.
class Dog {
 For example:
// state and behavior
 Dog #1 is a black Poodle,
}
 Dog #2 is a red Irish Setter

Compiled by Bedasa OOP- CoSc2051 36


Methods
 An Object's behavior is defined by its methods
 Methods, like fields, are written inside the braces of the class
 Methods can access the fields (the state) of their object and can change
them
class Dog {
String name; // field
// behavior
public void bark()
{
...
}
}

Compiled by Bedasa OOP- CoSc2051 37


Message
 Definition: Software objects interact and communicate with each other
by sending messages to each other.
 Example: when you want your dog to gather a herd of goats, you
whistle and send him out.

Compiled by Bedasa OOP- CoSc2051 38


Inheritance
 Inheritance is a mechanism in which one object acquires all the states
and behaviors of a parent object.
 Inheritance allows child classes inherits the characteristics of existing
parent class
 Attributes (fields and properties)
 Operations (methods)
 Child class can extend the parent class
 Add new fields and methods
 Redefine methods (modify existing behavior)
 A class can implement an interface by providing implementation for all
its methods.
 Inheritance is same as specialization.
Compiled by Bedasa OOP- CoSc2051 39
Inheritance
 Inheritance terminology

base class /
derived class inherits parent class

class implements interface

derived interface implements base interface

E.g. A old style television (idiot box) is transformed with extra


features into slim and smart television where it re-used the
properties of old television.
Compiled by Bedasa OOP- CoSc2051 40
Inheritance – Benefits
 Inheritance has a lot of benefits
– Extensibility
– Reusability
– Provides abstraction
– Eliminates redundant code
 Use inheritance for building is-a relationships
– E.g. dog is-a animal (dogs are kind of animals)
 Don't use it to build has-a relationship
– E.g. dog has-a name (dog is not kind of name)

Compiled by Bedasa OOP- CoSc2051 41


Inheritance – Example

Base class
. Person
+Name: String
+Address: String

Derived class Derived class

Employee Student
+Company: String +School: String
+Salary: double

Compiled by Bedasa OOP- CoSc2051 42


Encapsulation
 Encapsulation is a process of wrapping code and data together into a
single unit.
 Encapsulation is the process of grouping data in a single section.
 Encapsulation hides the implementation details
 Class announces some operations (methods) available for its clients –
its public interface.
 All data members (fields) of a class should be hidden.
 Accessed via properties (read-only and read-write).
 No interface members should be hidden.

Compiled by Bedasa OOP- CoSc2051 43


Encapsulation – Example
 Example: Complete television is single box where all the mechanism
are hidden inside the box all are capsuled.
 Data fields are private.
 Constructors and accessors are defined (getters and setters)

Person

-name : String
-age : TimeSpan
+Person (String name, int age)
+Name : String { get; set; }
+Age : TimeSpan { get; set; }

Compiled by Bedasa OOP- CoSc2051 44


Encapsulation – Benefits
 Ensures that structural changes remain local:
 Changing the class internals does not affect any code outside of the class
 Changing methods' implementation does not reflect the clients using
them
 Encapsulation allows adding some logic when accessing client's data
 E.g. validation on modifying a property value
 Hiding implementation details reduces complexity easier
maintenance.
 We can make a class read-only or write-only:
 For a read-only  a getter method and
 For write-only  a setter method will be used.

Compiled by Bedasa OOP- CoSc2051 45


Polymorphism
 Polymorphism is a concept in which we can execute a single
operation in different ways.
 Polymorphism is same as generalization.
 Polymorphism  ability to take more than one form (objects have
more than one type)
 A class can be used through its parent interface
 A child class may override some of the behaviors of the parent class
 Polymorphism allows abstract operations to be defined and used.
 Abstract operations are defined in the base class' interface and
implemented in the child classes
 Declared as abstract or virtual

Compiled by Bedasa OOP- CoSc2051 46


Polymorphism
 Why handle an object of given type as object of its base type?
– To invoke abstract operations
– To mix different related types in the same collection
 E.g. List<object> can hold anything
– To pass more specific object to a method that expects a parameter
of a more generic type
– To declare a more generic field which will be initialized and
"specialized" later

Compiled by Bedasa OOP- CoSc2051 47


Polymorphism

Figure Abstract
. action
+CalcSurface() : double

Concrete
class Square Circle
-x : int -x : int
-y : int -y : int
Overriden -size : int -radius: int Overriden
action action

override CalcSurface() override CalcSurface()


{ {
return size * size; return PI * radius * raduis;
} }

Compiled by Bedasa OOP- CoSc2051 48


Abstraction
 Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
 Abstraction means hiding internal details and showing the required things.
– E.g.: pressing the accelerator will increase the speed of a car.
– But the driver doesn’t know how pressing the accelerator increases
the speed – they don't have to know that.
 Technically abstract means something incomplete or to be completed later.
 In Java, we can achieve abstraction in two ways:
– abstract class (0 to 100%) and interface (100%).

Compiled by Bedasa OOP- CoSc2051 49


Overview of Java Programming
 Java is a high-level, general-purpose, object-oriented, and secure
programming language.
 Developed by James Gosling at Sun Microsystems, Inc. in 1991.
 It was developed by Sun Microsystems and released in 1995 as a core
component of the Java platform (initially known as Java 1.0 or J2SE).
 Over time, multiple configurations were built to suit various platforms:
 Java EE for Enterprise Applications
 Java ME for Mobile Applications
 Java is guaranteed to be Write Once, Run Anywhere (WORA).
 Widely used for various applications, including web development, mobile
apps, desktop software, and more.

Compiled by Bedasa OOP- CoSc2051 50


Overview of Java Programming
 Key Features of Java
 Object-Oriented: Everything in Java is an object, promoting modularity and
extensibility.
 Platform-Independent: Java code compiles to platform-independent
bytecode, executed by the Java Virtual Machine (JVM).
 Simple and Easy to Learn: Designed for readability and ease of use.
 Secure: Built-in security features prevent unauthorized access and malicious
code execution.
 Robust: Compile-time error checking and runtime checks minimize errors.
 Multithreaded: Supports concurrent execution of multiple threads.
 Interpreted: Bytecode is translated on-the-fly by the JVM.
 High Performance: JIT (Just-In-Time) compilers optimize execution speed.
 Distributed: Designed for internet-based distributed systems.
 Dynamic: Adapts to evolving environments.

Compiled by Bedasa OOP- CoSc2051 51


Overview of Java Programming
 Basic structure of a Java program.
 Documentation Section: The doc section is optional but
important.
 Package Declaration:
 Also optional, the package declaration comes after the doc section.
 It specifies the package in which the class resides.
 Only one package statement is allowed per Java program.
 The package name helps organize classes and avoids naming conflicts.
 Import Statements:
 Java packages contain predefined classes and interfaces.
 To use a class from a specific package, we need to import it.
 The import statement precedes the class declaration.
 You can either import a specific class or all classes from a package.
Compiled by Bedasa OOP- CoSc2051 52
Overview of Java Programming
 Basic structure of a Java program.
 Class Definition: The heart of a Java program is the class.
 A class contains fields (variables) and methods (behaviors).
 The public class keyword defines a class.
 Class Variables and Local Variables:
 Class variables (also called instance variables) belong to the class and are
shared among all instances.
 Local variables are declared within methods and have limited scope.
 Methods/Routines/Behaviors:
 Methods define the behavior of a class.
 The main method is the entry point for execution.
 Other methods perform specific tasks.

Compiled by Bedasa OOP- CoSc2051 53


Overview of Java Programming
 Basic structure of a Java program.
 //Class
Documentation
Definition:section (optional)
The heart of a Java program is the class.
// Package declaration
A class contains (optional)
fields (variables) and methods (behaviors).
package IntroJavaProgram;
 The public class keyword defines a class.
//Import statements (if needed)
Class Variables
 import and Local Variables:
java.util.Scanner;
 Class variables (also called instance variables) belong to the class and are
//Class definition
shared
public among
class all instances.{
HelloJava
 // Class
Local variable
variables (optional)
are declared within methods and have limited scope.
static String greeting = "Hello, World!";
 Methods/Routines/Behaviors:
// Main method (entry point)
 Methods define the behavior of a class.
public static void main(String[] args) {
 TheSystem.out.println(greeting);
main method is the entry point for execution.
 }Other methods perform specific tasks.
}
Compiled by Bedasa OOP- CoSc2051 54
Overview of Java Programming
 Basic structure of a Java program.
 In the Java programming language:
– A program is made up of one or more classes
– A class contains one or more methods
– A method contains program statements
– These terms will be explored in detail throughout the course
– A Java application always contains a method called main
//Class definition
public class HelloJava {
// Main method (entry point)
public static void main(String[] args) {
System.out.println(“Hello Java”);
}
}
Compiled by Bedasa OOP- CoSc2051 55
Overview of Java Programming
 The Compiler and the Java Virtual Machine
 Java Compiler:
 The Java compiler (often referred to as javac) is part of the Java
Development Kit (JDK).
 Its primary role is to compile source code written in the Java
programming language into bytecode.
 The generated bytecode is stored in class files.
 The Java compiler ensures that the code adheres to the language
rules and produces valid bytecode.

Compiled by Bedasa OOP- CoSc2051 56


Overview of Java Programming
 The Compiler and the Java Virtual Machine
 Java Virtual Machine (JVM):
 The JVM is an abstract machine that enables your computer to run Java
programs.
 When you execute a Java program, the following steps occur:
 Compilation: The Java compiler compiles your Java code into bytecode.
 Execution: The JVM translates this bytecode into native machine code
specific to the underlying platform.
 Key points about the JVM:
 It interprets bytecode and executes it efficiently.
 The same compiled class file can run on any version of the JVM across
different platforms and operating systems.
 The JVM manages memory, garbage collection, and other runtime aspects.
Compiled by Bedasa OOP- CoSc2051 57
Overview of Java Programming
 The process of compiling and running your first Java program.
 Prerequisites:
1. Java Development Kit (JDK) installed on your computer.
2. A text editor or an integrated development environment (IDE) to
write and edit your Java code. You can choose from options like
Notepad++, Eclipse, IntelliJ IDEA, or NetBeans.
1. Write the Code: Type the following code into the file:
public class HelloJava {
public static void main(String[] args) {
System.out.println(“Hello World”);
}
}

2. Save the file with the name HelloJava.java.


Compiled by Bedasa OOP- CoSc2051 58
Overview of Java Programming
 The process of compiling and running your first Java program.
3. Compile the Program
– Open your command prompt or terminal.
– Navigate to the directory where you saved your HelloJava.java file.
– Type the following command to compile your code:
javac HelloJava.java
4. Run the Program:
– After successful compilation, run the program using this command:
java HelloJava
5. Output:
– You’ll see the message “Hello, World!” printed in the console.

Compiled by Bedasa OOP- CoSc2051 59


Overview of Java Programming
 The process of compiling and running your first Java program.
 To run your first program, type the following at the command prompt:
c:\java>java HelloWorld
 Although the file name includes the .class extension , this part of
the name must be left off when running the program with the Java
interpreter.

Compiled by Bedasa OOP- CoSc2051 60


Overview of Java Programming
 The process of compiling and running your first Java program.
• Compile the Program: Compiling Java

Source Code Byte Code


Javac Java
(.java) (.class)

public class Factorial {


public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
System.out.println(factorial(5)); // Output: 120
}
}
Compiled by Bedasa OOP- CoSc2051 61
Datatypes and Variables
 In Java, types refer to the kinds of values that can be stored and
manipulated in a program.
 Java is a statically-typed language, which means that the type of a
variable must be declared before it is used.
 There are different types of values that can be stored and manipulated:
 Integers (int): These store whole numbers without decimals.
 Floating-Point Numbers (float): These store numbers with decimals.
 Characters (char): Used to store single characters, such as 'A', 'b', or '5'.
 Boolean Values (boolean): These represent true or false conditions.
 Strings (String): Strings store text, like "Hello" or "Java is awesome!".
– A sequence of characters. In Java, strings are objects.

Compiled by Bedasa OOP- CoSc2051 62


Datatypes and Variables
 There are different types of values that can be stored and manipulated:
 Reference Data Types:
 Objects: Instances of classes.
Person person1 = new Person();
 Arrays: Collections of elements of the same type.
int[] numbers = {1, 2, 3, 4, 5};
 Enumerations (Enums):
 A special data type that enables a variable to be a set of predefined
constants.
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY
}
Day today = Day.MONDAY;
Compiled by Bedasa OOP- CoSc2051 63
Datatypes and Variables
 Data Types: Default Values
 It's not always necessary to assign a value when a field is declared.
 Fields that are declared but not initialized will be set to a reasonable
default by the compiler.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Compiled by Bedasa OOP- CoSc2051 64
Datatypes and Variables
 In Java, a variable is a named location in the computer's memory that
stores a value of a particular type.
 Variables are used to store and manipulate data in a program.
 Each variable has a data type, which determines the kind of values it can
hold and the operations that can be performed on it.
 Here are the key points about variables in Java:
1. Declaration and Initialization:
 Before using a variable, it must be declared with a specific data type.
Syntax: dataType variableName;
 You can also initialize the variable at the time of declaration:
Syntax: dataType variableName = initialValue;

Compiled by Bedasa OOP- CoSc2051 65


Datatypes and Variables
 Here are the key points about variables in Java:
2. Naming Rules: Variable names in Java must adhere to certain rules:
– Must start with a letter, underscore (_), or dollar sign ($).
– Can be followed by letters, digits, underscores, or dollar signs.
– Case-sensitive.
int myVariable;
double _price;
String $name;
3. Assignment:
– Values are assigned to variables using the assignment operator (=).
– The value on the right side is assigned to the variable on the left
int
side.x = 10;
double y = 2.5;
String greeting = "Hello, World!";
Compiled by Bedasa OOP- CoSc2051 66
Datatypes and Variables
 Here are the key points about variables in Java:
2. Scope: Variables have different scopes:
– Local variables:
– Declared inside a method or block; limited to that block.
– Instance variables(Non-Static Fields):
– Belong to an instance of a class; Available throughout the class.
– Class Variables (static) : Shared among all instances of a class.
– E.g: static int numGears = 6
– Parameters Variables :
– E.g: public static void main(String[] args).
– Here, the args variable is the parameter to this method.

Compiled by Bedasa OOP- CoSc2051 67


Datatypes and Variables
 Here are the key points about variables in Java:
2. Scope:
– Variables have different scopes:
public class MyClass {

// Instance variable
int instanceVar;

public void myMethod() {

// Local variable
int localVar = 5;

// Accessing instance variable


instanceVar = localVar;
}
}
Compiled by Bedasa OOP- CoSc2051 68
Operators
 In Java, operators are symbols that perform various operations on
variables and values.
 They enable you to perform computations, manipulate data, and make
decisions in your programs.
 Here are some of the key types of operators in Java:
Types Operators Examples Example
Arithmetic Operators +, -, *, / a + b
Comparison Operators ==, !=, >, <, >=, <= a != b
Logical Operators &&, ||, ! a && b
Assignment Operators +=, -=, *=, /= a += b
Increment and Decrement ++, -- a++
Operators
Bitwise Operators(shot &, | a & b
circuit)
Compiled by Bedasa OOP- CoSc2051 69
POP QUIZ
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3;
-12
2) What is the value of result?
int x = 8;
int y = 2;
boolean result = (15 == x * y); false

3) What is the value of result?


boolean x = 7;
boolean result = (x < 8) && (x > 4); true

4) What is the value of numCars?


int numBlueCars = 5;
int numGreenCars = 10;
int numCars = numGreenCars++ + numBlueCars + 27
++numGreeenCars;

Compiled by Bedasa OOP- CoSc2051 70


Arrays
 An array is a collection of similar types of data, allowing you to store
multiple values under a single variable name.
 You can make an array of any type int, double, String, etc..
 All elements of an array must have the same type.
 An array is an indexed list of values.
 The index starts at zero and ends at length-1.
 An array is defined using TYPE[].
 Arrays are just another type.
 int[] values; // array of int
 int[][] values; // int[] is a type

Compiled by Bedasa OOP- CoSc2051 71


Arrays
 To create an array of a given size, use the operator new :
int[] values = new int[5];
 or you may use a variable to specify the size:
int size = 12;
int[] values = new int[size];
 Array Initialization:
 Curly braces can be used to initialize an array.
 It can ONLY be used when you declare the variable.
int[] values = { 12, 24, -23, 47 };
☻ Quiz: Is there an error in this code?
int[] values = {1, 2.5, 3, 3.5, 4};

Compiled by Bedasa OOP- CoSc2051 72


Arrays
 Accessing Arrays
 To access the elements of an array, use the [] operator: values[index].
 Example:
int[] values = { 12, 24, -23, 47 };
values[3] = 18; // {12,24,-23,18}
int x = values[1] + 3; // {12,27,-23,18}
 The length variable
 Each array has a length variable built-in that contains the length of
the array.
 int size = values.length; // 4
 by using a loop:
int[] a = new int[100];
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
Compiled by Bedasa OOP- CoSc2051 73
Arrays
 Accessing Arrays
 The “for each” Loop:
 The enhanced for loop

for (variable : collection)


statement
 The collection expression must be an array
 loop through each element in an array (or any other collection of
elements) without having to fuss with index values.
• For example
for (int element : a)
System.out.println(element);
• prints each element of the array a on a separate line.

Compiled by Bedasa OOP- CoSc2051 74


Arrays
1. Which of the following sequences of statements does not create a new
array?
a. int[] arr = new int[4];
b. int[] arr;
arr = new int[4];
c. int[] arr = { 1, 2, 3, 4};
d. int[] arr;
2. Given this code fragment,
int[] data = new int[10];
System.out.println(data[j]);
• Which of the following is a legal value of j? [-1, 0, 3.5, 10]

Compiled by Bedasa OOP- CoSc2051 75


Arrays: 2-Dimensional Arrays
• In Java, a 2-dimensional array is essentially an array of arrays.
• In Java, 2D arrays are stored as arrays of arrays.
• It can be thought of as a matrix where each element is identified by two
indices - one for the row and another for the column.
• Creating a 2D Array:
– To create a two-dimensional array, you define a data type followed by
two sets of square brackets.
– Each array within the 2D array is enclosed in its own set of curly
braces.

int[][] matrix = new int[3][4];


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

Compiled by Bedasa OOP- CoSc2051 76


Arrays: 2-Dimensional Arrays
• Accessing Elements:
– To access elements within the matrix array, specify two indexes: one
for the outer array (which represents the row), and another for the
0 1
inner array (which represents the column).
0 8 4
– For instance:
1 9 7
int[][] values = { {1, 2, 3, 4}, {5, 6, 7}};
System.out.println(values[1][2]); // Outputs 7
• Changing Element Values: You can modify the value of an element
within the array.
values[1][2] = 9;
System.out.println(values[1][2]); // Outputs 9 instead of 7

Compiled by Bedasa OOP- CoSc2051 77


Control Structures
• In Java, control structures are constructs that allow you to alter the flow
of your program based on certain conditions or repetitions.
• The primary control structures in Java include:
• Conditional Branches
• if/else/else if:
– The if statement is fundamental for decision-making.
– You can also nest if and else blocks, but keep readability in mind.
• Switch:
– Useful when you have multiple cases to choose from.
• Loops:
– for, while and do-while loops.
– Both loops repeat a specific code block multiple times.
Compiled by Bedasa OOP- CoSc2051 78
Control Structures
• Conditional Branches:  if
• The if statement in Java is used to conditionally execute a block of
statements based on a specified condition.
• The syntax for the if statement is as follows:

if (CONDITION) {
// Statements to be executed if the condition is true
}
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
}
• In this example, if the condition x > 5 is true, the statement inside the
curly braces will be executed, and "x is greater than 5" will be printed to
the console.
Compiled by Bedasa OOP- CoSc2051 79
Control Structures
• Conditional Branches:  if else
• The else statement is used to execute a block of code if the same
condition from the if statement is false.
• The syntax for the if statement is as follows:
int y = 3;
if (y > 5) {
System.out.println("y is greater than 5");
} else {
System.out.println("y is not greater than 5");
}

• In this case, if y > 5 is false, the statements inside the else block will be
executed.
• Remember that the condition in the if statement should be a boolean
expression, which means it evaluates to either true or false.
Compiled by Bedasa OOP- CoSc2051 80
Control Structures
• Conditional Branches:  if else if
• In Java, the combination of if and else if statements is used when you
have multiple conditions to check, and you want to execute different
blocks of code based on the evaluation of these conditions.
• The if-else if structure allows you to create a series of conditions, and
the first one that evaluates to true will have its corresponding block of
code executed.
• Each fi or else if block contains a condition.
• If the condition in the if block is true, the statements within that block
will be executed, and the subsequent else if and else blocks will be
skipped.

Compiled by Bedasa OOP- CoSc2051 81


Control Structures
• Conditional Branches:  if else if
• If the condition in the if block is false, the program moves on to the next
else if block, and so on.
if (condition1) {
// Statements to be executed if condition1 is true
} else if (condition2) {
// Statements to be executed if condition2 is true
}
// ... add more else if blocks if needed
else {
// Statements to be executed if none of the
conditions is true
}

Compiled by Bedasa OOP- CoSc2051 82


Control Structures
• Conditional Branches:  switch
• The switch statement evaluates the expression once.
• It compares the value of the expression with the values of each case.
• If a match is found, the associated block of code executes.
• The break keyword is used to exit the switch block after executing a case.
• The default case is optional and runs when no other case matches.

switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
// More cases...
default:
// Code to execute if no case matches
}

Compiled by Bedasa OOP- CoSc2051 83


Control Structures
• Conditional Branches:  switch
int day = 4; // Assuming 1 represents Monday, 2 represents
Tuesday, and so on
switch (day) {
case 1:
System.out.println("Monday");
break;
case 4:
System.out.println("Thursday");
break;

default:
System.out.println("Invalid day");
}

• The break statement prevents fall-through behavior (i.e., executing


subsequent cases after a match).
• The default case handles situations where none of the specified cases match.
Compiled by Bedasa OOP- CoSc2051 84
Quiz
• Write a java program that prints letter grades based on
– 90 – 100 = A+
– 85 – 90 = A-
– 80 – 85 = A
– 75 – 80 = B+
– Else F by accepting value from a user.

Compiled by Bedasa OOP- CoSc2051 85


Control Structures
• Conditional Branches:  Loops
• Loops allow you to repeat a set of instructions as long as a specified
condition remains true.
• for Loop:
– The for loop provides a concise way to write a loop structure.
– It combines initialization, condition testing, and increment/decrement
in one line. The for loop is an entry control loop.
for (initialization; testing-condition; increment/decrement)
{
// Statements...
}
for (int j = 0; j <= 10; j++) {
System.out.print(j); // 012345678910
}
Compiled by Bedasa OOP- CoSc2051 86
Control Structures
• Conditional Branches:  Loops
• while Loop:
– The while loop executes a block of code while a given Boolean
condition is true.
while (boolean condition) {
// Loop statements...
}

– The while loop is an entry control loop (checks condition before


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

Compiled by Bedasa OOP- CoSc2051 87


Control Structures
• Conditional Branches:  Loops
• do-while Loop:
– The do-while loop executes a block of code at least once, even if the
condition is false.
– It checks the condition after executing the statements.
do {
// Statements...
} while (condition);

– The do-while loop is an exit control loop (checks condition after


execution). int k = 0;
do {
System.out.println(k);
k++;
} while (k <= 10);

Compiled by Bedasa OOP- CoSc2051 88


Quiz
• FizzBuzz Problem Statement
• FizzBuzz is a well-known coding problem that frequently appears in
entry-level job interviews.
• FizzBuzz problems test your logical thinking and how well you know
loops and control flow.
• Write a program that prints the numbers from 1 to 100.
• But for multiples of three print "Fizz" instead of the
number and for the Multiples of five print "Buzz".
• For numbers which are multiples of both three and five
print "FizzBuzz".

Compiled by Bedasa OOP- CoSc2051 89


End of Chapter 1

Next: Objects and Classes


https://docs.oracle.com/en/java

Compiled by Bedasa OOP- CoSc2051 90

You might also like