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

oop-1

The document outlines the course structure and rules for Object Oriented Programming (OOP) under the course code CoSc2051, including credit hours and ECTS. It introduces key concepts of OOP such as programming paradigms, classes, objects, methods, inheritance, encapsulation, and polymorphism. The document also discusses classroom rules and expectations for student behavior during lectures and labs.

Uploaded by

Woldeab Bisrat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

oop-1

The document outlines the course structure and rules for Object Oriented Programming (OOP) under the course code CoSc2051, including credit hours and ECTS. It introduces key concepts of OOP such as programming paradigms, classes, objects, methods, inheritance, encapsulation, and polymorphism. The document also discusses classroom rules and expectations for student behavior during lectures and labs.

Uploaded by

Woldeab Bisrat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Object Oriented Programming.

Credit Hour: 3 hrs.


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

OOP- CoSc1012 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

OOP- CoSc2051 2
Introduction to Object-
Oriented Programming

OOP- CoSc2051 3
Introductions
• Chapter 1: Introduction to O O P
– Types of programming paradigms
– Overview of O O principles
– Editing, Compiling and Interpreting

OOP- CoSc2051 4
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?

OOP- CoSc2051 5
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
OOP- CoSc2051 6
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.).

OOP- CoSc2051 7
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

OOP- CoSc2051 8
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 G O T O 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.
OOP- CoSc2051 9
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

OOP- CoSc2051 10
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 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;

OOP- CoSc2051 12
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.

OOP- CoSc2051 13
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.

OOP- CoSc2051 14
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.
OOP- CoSc2051 15
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

OOP- CoSc2051 16
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:

OOP- CoSc2051 17
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

OOP- CoSc2051 18
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.

OOP- CoSc2051 19
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 O O P 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.

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

OOP- CoSc2051 21
O O P 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).

OOP- CoSc2051 22
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

OOP- CoSc2051 23
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

OOP- CoSc2051 24
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()
{
...
}
}

OOP- CoSc2051 25
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.

OOP- CoSc2051 26
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.


OOP- CoSc2051 27
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.
OOP- CoSc2051 28
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)

OOP- CoSc2051 29
Inheritance – Example

Base class
Person
+Name: String
+Address: String

Derived class Derived class

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

OOP- CoSc2051 30
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.

OOP- CoSc2051 31
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; }

OOP- CoSc2051 32
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.

OOP- CoSc2051 33
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

OOP- CoSc2051 34
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

OOP- CoSc2051 35
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;
} }

OOP- CoSc2051 36
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%).

OOP- CoSc2051 37
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.

OOP- CoSc2051 38
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 JavaVirtual 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.

OOP- CoSc2051 39
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.
OOP- CoSc2051 40
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.
OOP- CoSc2051 41
Overview of Java Programming
▪ Basic structure of a Java program.
// Documentation section (optional)
// Package declaration (optional)
package IntroJavaProgram;
//Import statements (if needed)
import java.util.Scanner;
//Class definition
public class HelloJava {
// Class variable (optional)
static String greeting = "Hello, World!";

// Main method (entry point)


public static void main(String[] args) {
System.out.println(greeting);
}
}
OOP- CoSc2051 42
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”);
}
}
OOP- CoSc2051 43
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.

OOP- CoSc2051 44
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.
OOP- CoSc2051 45
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.


OOP- CoSc2051 46
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 MyFirstJava.java
4. Run the Program:
– After successful compilation, run the program using this command:
java MyFirstJava
5. Output:
– You’ll see the message “Hello, World!” printed in the console.

OOP- CoSc2051 47
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 MyFirstJava.java
▪ 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.

OOP- CoSc2051 48
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
}
}
OOP- CoSc2051 49
Input and Output…
Java applications are designed to work in a terminal (console) I/O
environment.
Every Java application has at its disposal three I/O streams that are
designed for terminal-based input and output, which simply sends or
receives data one character at a time.
The three streams are:
Standard input: A stream designed to receive input data. This
stream is usually connected to the keyboard at the computer where
the program is run.
Standard output: A stream designed to display text output on-
screen.
Standard error: Another stream designed for output. This stream is
also connected to the console window.
Input and Output…

System.out is known as the standard output object.


System.out defines the print() and println() methods which are used to
write data to the console.

Syntax:
System.out.print(message);
System.out.println(message);

Example
System.out.print("Hello world...\n");
System.out.println("Hello world...");
System.out.print( "The answer is: ");
System.out.print( 3.14 );
Input and Output…

Escape Sequence
The backslash (\) is called an escape character.
It indicates that a “special character” is to be output.

Sequence Description
\n Newline. Position the screen cursor to the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.

\r Carriage return. Position the screen cursor to the beginning of the


current line; do not advance to the next line. Any characters output after
the carriage return overwrite the characters previously output on that
line.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double-quote character. For example,
Input and Output…

In Java, console input is accomplished by reading from System.in.


System.in refers to standard input, which is the keyboard by default.
System.in has a method called read() which returns an integer whose
value can be in the range of 0-255.
Example:
int a = System.in.read();

Accepting input using System.in directly is very inflexible because it


deals with bytes instead of characters.
As a result, it is not used commonly.
Instead other input accepting mechanisms are used of which one is the
Scanner class.
Input and Output…

Scanner Class
Scanner class is introduced to simplify the task of getting input
from the user
To use Scanner class, you must declare a Scanner variable and
create an instance of the Scanner class.
Example
static Scanner sc = new Scanner(System.in);

Scanner is defined in a package import java.util.Scanner.


Hence, you have to import import java.util.Scanner to use Scanner
to accept input.
Input and Output…

To read an input value from the user, you can use one of the
methods of the Scanner class.
There is a method to accept every primitive data type.

Method Explanation
boolean nextBoolean() Reads a boolean value from the user
byte nextByte() Reads a byte value from the user
double nextDouble() Reads a double value from the user
float nextFloat() Reads a float value from the user
int nextInt() Reads an int value from the user
String nextLine() Reads a String value from the user
long nextLong() Reads a long value from the user
short nextShort() Reads a short value from the user
Input and Output…

Example:
import java.util.Scanner;
public class ScannerApp {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
int x = sc.nextInt();
System.out.println("You entered " + x);
}
}
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.

OOP- CoSc2051 57
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;
OOP- CoSc2051 58
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 null
object)
boolean false

OOP- CoSc2051 59
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;

OOP- CoSc2051 60
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
isindte.x = 10;
double y = 2.5;
String greeting = "Hello, World!";
OOP- CoSc2051 61
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.

OOP- CoSc2051 62
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;
}
}
OOP- CoSc2051 63
Variables and Data Types…

Type Conversion and Casting


Sometimes, you need to convert numeric data of one type to
another.
E.g. convert a double value to an integer, or vice versa.
Some conversions can be done automatically if the two numbers
are compatible.
Others are done using a technique called casting.

Casting
To create a conversion between two incompatible types, you
must use a cast.
A cast is simply an explicit type conversion.
Casting is similar to conversion, but isn’t done automatically.
Variables and Data Types…

The general syntax is:


variable = (data-type) value;
Here, data-type specifies the desired type to convert the
specified value to.
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
Variables and Data Types…

String to Number
To convert a string to a primitive type, you use a parse
method of the appropriate wrapper class.

Wrapper class Parse Method Example


Integer parseInt(String) int x = Integer.parseInt(“100”);
Short parseShort(String) short x = Short.parseShort(“100”);
Long parseLong(String) long x = Long.parseLong(“100”);
Byte parseByte(String) byte x = Byte.parseByte(“100”);
Float parseFloat(String) float x = Float.parseFloat (“19.95”);
Double parseDouble(String) double x =
Double.parseDouble(“19.95”);
Boolean parseBoolean(String) boolean x =
Boolean.parseBoolean(“true”);
Variables and Data Types…

Constant
A constant is a variable whose value you can’t change once
it has been initialized.
It is also called final variable
To declare a constant, you add the final keyword to the
variable declaration, like this:
final double PI = 5;

Constants are useful for values that are used in several


places throughout a program and that don’t change during
the course of the program.
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)
OOP- CoSc2051 68
POP QUIZ
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3;

2) What is the value of result?


int x = 8;
int y = 2;
boolean result = (15 == x * y);

3) What is the value of result?


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

4) What is the value of numCars?


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

OOP- CoSc2051 69
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

OOP- CoSc2051 70
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};

OOP- CoSc2051 71
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]);
OOP- CoSc2051 72
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.

OOP- CoSc2051 73
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}};
OOP- CoSc2051 75
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
inner array (which represents the column). 0 1
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

OOP- CoSc2051 76
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.
OOP- CoSc2051 77
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.
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.
OOP- CoSc2051 79
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 Achenef OOP- CoSc2051 80


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
}

OOP- CoSc2051 81
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
}

OOP- CoSc2051 82
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.
OOP- CoSc2051 83
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.

OOP- CoSc2051 84
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
}
OOP- CoSc2051 85
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++;
}

OOP- CoSc2051 86
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);

OOP- CoSc2051 87
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".

OOP- CoSc2051 88
Assignment

1. Write a program that produces the following shape. The output produced
by this program is shown here:
*********
********
*******
******
*****
****
***
**
*
2. Write a program that adds the odd integers between 1 and
99, using a for structure. Display the sum on a console.
Assignment

3. Write a program accepts a number from user and then displays all
even numbers between 1 and the number accepted.
4. Write a program that accepts three numbers a, b, and c and then
display the largest of the three.
End of Chapter 1

Next: Objects and Classes


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

OOP- CoSc2051 91

You might also like