Java 1& 2
Java 1& 2
4/15/2024 BY SHIMELIS A. 1
Chapter One & Two
Overview of O O P
4/15/2024 BY SHIMELIS A. 2
Syllabus
Programming fundamentals O-O programming
✓ Variable ✓ classes
✓ Data types ✓ Objects
✓ Operators ✓ Abstraction
✓ Encapsulation
✓ Conditions
✓ Inheritance
✓ Loops
✓ Polymorphism
✓ methods
✓ Abstract classes
✓ Interfaces
4/15/2024 BY SHIMELIS A. 3
INTRODUCTION
• Program(software)
• Set instruction that tell a computer what to do
✓ We use program to interact/ talk with computers.
✓ To write program we use a programing language
✓ Computers are machines that don’t understand human languages
✓ Programs are written in the language computer can understand by
using programming language
4/15/2024 BY SHIMELIS A. 4
Machine Language …CONTD
❖ A computers native language
❖ Use zeros and ones (0/1) i.e. binary language.
❖ Machine dependent
❖ Ever instruction should be written in machine language before it can be executed.
✓ All instruction written in other programming languages must be translated to machine
code instruction
Assembly language
❖ Was developed to make instruction easier Cant be executed
❖ Introduce keywords such as add, sub, ….
❖ Example to add 2 and 3 and get the result: add 2, 3 , result
✓ A program called assembler translate assembly code to machine code.
4/15/2024 BY SHIMELIS A. 5
…CONTD
High Level Programming Language
❖ A new generation of programming language
❖ Use English like word which makes it easy to learn and use
❖ Machine independent i.e. program will run on different machines
❖ A program written in a high level language is called a source program or a
source code
❖ To add 2 and 3 and get the result : sum = 2 + 3;
❖ A compiler or an interpreter is used to translate source code to machine code
✓ What is the difference between compiler and interpreter?
4/15/2024 BY SHIMELIS A. 6
Why we learn Java?
❖ High-level, General purpose, O-O programming Language
❖ Very popular
❖ C based language
4/15/2024 BY SHIMELIS A. 7
Programming Paradigm
❖ is a way of conceptualizing what it means to perform computation and
how tasks to be carried out and organized on a computer.
✓ Structured programming
✓ O-O programming
I. Structured Programing
❖ involve the analysis of processes, the production of a system and tasks
carried out is based on the procedural flow of the processes.
4/15/2024 BY SHIMELIS A. 8
...CONTD
II. O O P Approach
❖ Is a paradigm that employs “Objects” and their interaction as a
primary basis for software development.
❖ An object can be anything that can be conceived and be represented in
a computer
❖ A software object resembles so much like a real world object – it will
have the following three things:
✓ identity
✓ state and
✓ behavior
4/15/2024 BY SHIMELIS A. 9
...CONTD
Identity
❖ The identity is unique and may not be shared between different objects,
even at different time and does not change during the object lifetime
State
❖ The object state represents the different possible internal conditions
that the object may experience during its lifetime
Behavior
❖ The object behavior is the way a particular object will respond to
received messages
Eg. Radio
✓ State – On, Off, current channel, current volume
✓ Behavior – Turn Off/ On, Change Channel etc
4/15/2024 BY SHIMELIS A. 10
Basic concepts of OOP
4/15/2024 BY SHIMELIS A. 11
Basic concepts of OOP
4/15/2024 BY SHIMELIS A. 12
…CONTD
Class Structure
Class class_name {
Code block
}
keyword
4/15/2024 BY SHIMELIS A. 13
…CONTD
Attributes
❖ Attributes (or variables) refer to the characteristics of the object.
attributes.
4/15/2024 BY SHIMELIS A. 14
…CONTD
Method:
✓ A group of instruction to perform specific tasks
✓ Written inside class
✓ Example a method to add two integer.
Method Structure
✓ Each method consists of 4 main parts
return_type method_name (parameters) {
Code block;
}
Note: every method is written inside a class i.e. class is a container for
method
4/15/2024 BY SHIMELIS A. 15
…CONTD
Calling Method:
❖ Is basically using a method
method_name (give parameters);
❖ The code block of this method will be executed.
Note:
✓ The main ( ) method is automatically called when we run our java
program
✓ It is the first method that is called
✓ It is the starting point of our execution
4/15/2024 BY SHIMELIS A. 16
…CONTD
Access Modifiers
❖ The keywords that specify how to access class and method
✓ Public: Visible to the world public.
✓ Private: Visible to the class only private.
✓ Protected: Visible to the package and all subclasses.
✓ Default: Visible to the package.
4/15/2024 BY SHIMELIS A. 17
…CONTD
Naming convention
❖ How to write name in programming language
✓ Pascal case convention
MyFatherName –used to name class
✓ camel case convention
MyFatherName –used to name methods and variable
✓ snake case convention
My_father_name
4/15/2024 BY SHIMELIS A. 18
Java program structure
public Class main {
public static void main (String [] args) {
Code block
}
}
4/15/2024 BY SHIMELIS A. 19
OOP’s fundamental building blocks:
4/15/2024 BY SHIMELIS A. 20
I. Data Abstraction & Encapsulation
❖ The wrapping up of data and methods into a single unit (called class) is known as
encapsulation.
❖ This insulation of the data from direct access by the program is called data
hiding.
❖ Abstraction refers to representing essential features without including the
background details or explanations
❖ Classes use the concept of data abstraction, and they are known as Abstract
Data Types (ADT)
✓ They hide the private data structure details and communicate with the
outside using public methods which act as interfaces
4/15/2024 BY SHIMELIS A. 21
…CONTD
II. Inheritance
❖ Is the process by which objects of one class acquire the properties of
objects of another class.
❖ It provides the idea of reusability
4/15/2024 BY SHIMELIS A. 22
…CONTD
III. Polymorphism
❖ Is the ability to take more than one form.
4/15/2024 BY SHIMELIS A. 23
❖ Overloaded methods: methods with the same name signature but either a
different number of parameters or different types in the parameter list
❖ Overridden methods are methods that are redefined within an inherited or
subclass
✓ They have the same signature and the subclass definition is used
❖ Dynamic binding means that the code associated with a given procedure
call is not known until the time of the call at runtime.
✓ Memory is allocated at runtime not at compile time.
4/15/2024 BY SHIMELIS A. 24
Basics of J av a Programing
Language
4/15/2024 BY SHIMELIS A. 25
J a v a Overview
❖ Java is a general purpose, object-oriented programming language
developed by Sun Microsystems of USA in 1991.
❖ Java applications are object code portable as long as a Java virtual machine
is implemented for the target machine.
❖ The java object-oriented programming framework promotes reusability of
software and code.
4/15/2024 BY SHIMELIS A. 26
Java Features
Compiled and Interpreted
❖ Java combines both these approaches thus makes it a two-stage
system.
4/15/2024 BY SHIMELIS A. 27
J a v a Virtual Machine (JVM)
❖ Java compiler produces an intermediate code known as bytecode for a
machine that does not exist.
❖ This machine is known as Java Virtual Machine (JVM) & it exists only inside
computer memory.
❖ It is a simulated computer within the computer and does all major
functions of the real computer.
❖ TheJVM is responsible in interpreting bytecode to machine understandable
code (Machine code).
❖ Just In Time compiler(JIT), part of the JVM, is responsible for compiling
code as it is needed, during execution.
4/15/2024 BY SHIMELIS A. 28
Advantage of java
❖ Platform independent and Portable
✓ compile once and execute many times in many platforms”
❖ Object-oriented
✓ Java is true object-oriented programming language.
❖ Robust and Secure
❖ Distributed
❖ Simple, Small and Familiar
❖ Multithreaded and interactive
❖ Dynamic and Extensible
4/15/2024 BY SHIMELIS A. 29
Java Environment
❖ Java environment includes a large number of development tools and hundreds of
classes and Methods.
❖ The development tools are part of the system known as Java Development Kit
(JDK) and the classes and methods are part of the Java Standard Library (JSL),
also known as Application Programming Interface (API).
❖ JDK comes with a collection of tools that are used for developing and
running java programs:
✓ appleviewer (for viewing java applets )
✓ javac (java compiler)
✓ java (java interpreter)
✓ javap (java disassembler)
✓ javah (for C header files)
✓ javadoc (for creating HTML documents)
✓ jdb (Java debugger)
4/15/2024 BY SHIMELIS A. 30
Java API
❖ APIs are important software components bundled with the JDK.
❖ APIs in Java include classes, interfaces, and user Interfaces.
❖ They enable developers to integrate various applications and websites and
offer real-time information
❖ Most commonly used packages are:
✓ Language Support Package: a collection of classes and methods required for implementing
basic features of java.
✓ Utilities Package: a collection of classes to provide utility functions such as date and time
functions.
✓ Input/output Package: a collection of classes required for input/output manipulation.
✓ Networking Package: a collection of classes for communicating with other computers via
Internet.
✓ AWT Package (Abstract Window Tool kit package): contains classes that implements
platform-independent graphical user interface.
✓ Applet Package: includes set of classes that allows us to create java applets.
4/15/2024 BY SHIMELIS A. 31
Overview of J ava Programing
Language
4/15/2024 BY SHIMELIS A. 32
Introduction
❖ Java is a general-purpose, object-oriented programming language.
❖ We can develop two types of Java programs namely:
✓ Stand-alone application
✓ Web applets
❖ Executing stand-alone Java program involves two steps:
✓Compiling source code into byte code javac compiler.
✓ Executing the bytecode program using java interpreter.
❖ Applets are small programs developed for Internet applications.
❖ An applet located on a distant computer (server) can be downloaded
via Internet and executed on a local computer (client) using a Java-
capable browser.
4/15/2024 BY SHIMELIS A. 33
Two Ways of writing Java Programs
Compiler
4/15/2024 BY SHIMELIS A. 34
Simple Java Program
The simplest way to learn a new language is to write a few simple example
programs and execute them.
public class Sample {
public static void main (String args [])
{
System.out.print(“Java is better than C++.”);
}
}
4/15/2024 BY SHIMELIS A. 35
❖ Let us discuss the program line by line:
❖ Class Declaration: the first line class Sample declares a class, which is an object
constructor. Class is keyword and declares a new class definition and Sample is a
java identifier that specifies the name of the class to be defined.
❖ Opening Brace “{“: Every class definition in java begins with an opening brace and
ends with a closing brace “}”.
❖ The main line: the third line public static void main(String args[]) defines a method
named as main.
❖ Is the starting point for the interpreter to begin the execution of the
program.
4/15/2024
36 BY SHIMELIS A.
Note:
❖ A java program can have any number of classes but only one of them must
include the main method to initiate the execution.
❖ Java applets will not use the main method at all.
❖ The third line uses a number of keywords: public, static and void
❖ public: is an access specifier that declares the main method as “unprotected”
and therefore making it accessible to all other classes.
❖ static: declares that this method as one that belongs to the entire class and
not a part of any objects of the class.
❖ Main must always be declared as static since the interpreter uses this
method before any objects are created.
❖ void : states that the main method does not return any value (but prints some
text to the screen.)
4/15/2024 BY SHIMELIS A. 37
…CONTD
❖ All parameters to a method are declared inside a pair of parenthesis. Here, String
args [ ] declares a parameter named args, which contains array of objects of the
class type String.
❖ The Output Line: The only executable statement in the program is
System.out.println (“Java is better than C++.”);
❖ The println method is a member of the out object, which is a static data member of
System class.
4/15/2024 BY SHIMELIS A. 38
Java Program Structure
4/15/2024 BY SHIMELIS A. 39
Documentation Section
❖ comprises a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to refer at a
later stage.
❖ Java supports three types of comments:
I. Single line comment //
II. Multiple line comment / * … … … … … …
………………*/
III.Documentation comment /**….*/
✓ This form of comment is used for generating documentation automatically.
4/15/2024 BY SHIMELIS A. 40
…CONTD
Package Statements
❖ Is the first statement in Java file and is optional.
❖ It declares a package name and informs the compiler that the classes
defined here belong to this package.
Example: package student;
Import Statements
❖ Next to package statements (but before any class definitions) a number of import
statements may exist. This is similar to #include statements in C or C ++.
❖ Using import statements we can have access to classes that are part of other
named packages.
Example: import java.lang.Math;
4/15/2024 BY SHIMELIS A. 41
…CONTD
Interface Statements
❖ An interface is like a class but includes a group of method declarations.
❖ is also an optional section.
❖ is used only when we wish to implement the multiple inheritance features in the
program
Class Definitions
⦁ A Java program may contain multiple class definitions.
⦁ Classes are the primary and essential elements of a Java program.
⦁ These classes are used to map objects of real-world problems.
⦁ The number of classes depends on the complexity of the problem.
4/15/2024 BY SHIMELIS A. 42
…CONTD
M a i n Method C l a s s
❖ Since every Java stand-alone program requires a main method as its starting
point, this class is the essential part of a Java program.
❖ On reaching the end of main, the program terminates and control passes back
to the operating system.
4/15/2024 BY SHIMELIS A. 43
J ava Tokens
4/15/2024 BY SHIMELIS A. 44
Introduction
❖ A class in java is defined by a set of declaration statements and methods
containing executable statements.
❖ Most statements contain expressions, which describe the actions carried out on
data.
❖ Java has five types of tokens: Reserved Keywords, Identifiers, Literals, Separators and
Operators .
4/15/2024 BY SHIMELIS A. 45
1. Keywords
❖ Are essential part of a language definition and can not be used as names for
variables, classes, methods and so on.
4/15/2024 BY SHIMELIS A. 46
2. Identifiers
❖ Are programmer-designed tokens.
❖ Are used for naming classes, methods, variables, objects, labels, packages
and interfaces in a program.
1) $amount 5) score
2) 6tally 6) first Name
3) my*Name 7) total#
4) salary 8) cast
4/15/2024 BY SHIMELIS A. 48
3. Literals
❖ Literals in Java are a sequence of characters(digits, letters and other characters)
that represent constant values to be stored in variables.
4/15/2024 BY SHIMELIS A. 49
4. Separators
❖ Are symbols used to indicate where groups of code are divided and arranged.
4/15/2024 BY SHIMELIS A. 50
…Contd
III. Brackets[ ]:- are used to declare array types and for
IV.dereferencing array values.
V. Semicolon;:- used to separate statements.
VI. Comma,:- used to separate consecutive identifiers in a variable
declaration, also used to chain statements together inside a “for”
statement.
4/15/2024 BY SHIMELIS A. 51
5. Operators
❖ Are symbols that take one or more arguments (operands) and operates on
them to a produce a result.
❖ Are used to in programs to manipulate data and variables.
❖ They usually form a part of mathematical or logical expressions.
❖ Expressions can be combinations of variables, primitives and operators that
result in a value.
4/15/2024 BY SHIMELIS A. 52
Java Operators
❖ There are 8 different groups of operators in Java:
✓ Arithmetic operators
✓ Relational operators
✓ Logical operators
✓ Assignment operator
✓ Increment/Decrement operators
✓ Conditional operators
✓ Bitwise operators
✓ Special operators
4/15/2024 BY SHIMELIS A. 53
A. Arithmetic Operators
❖ Java has five basic arithmetic operators
4/15/2024 BY SHIMELIS A. 54
B . Relational Operators
❖ Relational operators compare two values
❖ Produces a boolean value (true or false) depending on the relationship.
❖ Java supports six relational operators:
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
4/15/2024
55 BY SHIMELIS A.
…CONTD
Examples of Relational Operations
int x = 3; int y = 5;
boolean result;
1) result = (x > y);
now result is assigned the value false because 3 is not greater than 5
2) result = (15 == x*y);
now result is assigned the value true because the product of 3 and 5 equals 15
3) result = (x != x*y);
now result is assigned the value true because the product of x and y (15) is not
equal to x (3)
4/15/2024 BY SHIMELIS A. 56
C . Logical Operators
Symbol Name
&& Logical AND
|| Logical OR
! Logical NOT
❖ The logical operators && and || are used when we want to form compound
conditions by combining two or more relations.
4/15/2024 BY SHIMELIS A. 57
Examples of Logiacal Operators
boolean x = true;
boolean y = false;
boolean result;
1. Let result = (x && y);
now resultis assigned the value false
(see truth table!)
4/15/2024 BY SHIMELIS A. 58
4. Assignment Operator
❖ Are used to assign the value of an expression to a variable.
❖ In addition to the usual assignment operator(=), java has a set of ‘shorthand’
assignment operators which are used in the form:
var op = expr ;
❖ Where var is a variable, op is a binary operator and expr is an expression.
❖ The operator op= is known as shorthand assignment operator.
❖ The assignment statement: var op= expr; is equivalent to var=var op(expr);
Examples:
x += y + 5; is equivalent to x= x+(y+5);
y *= 7;is equivalent to y = y * 7;
4/15/2024 BY SHIMELIS A. 59
5. Increment/Decrement Operators
count = count + 1;
can be written as:
++count; or count++;
++ is called the increment operator.
count = count - 1;
can be written as:
--count; or count--;
-- is called the decrement operator.
❖ Both ++ and -- are unary operators.
4/15/2024 BY SHIMELIS A. 60
…CONTD
The prefix form ++count,--count
first adds/subtracts1 to/from the variable and then continues to any other operator in the expression
int numOranges = 5; int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16 numOranges has value 6
The postfix form count++,count--
first evaluates the expression and then adds 1 to the variable
int numOranges = 5; int numApples = 10; int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15 numOranges has value 6
4/15/2024 BY SHIMELIS A. 61
6. Conditional Operators
⦁ The character pair ?: is a ternary operator available in java.
⦁ It is used to construct conditional expression of the form:
exp1 ? exp2: exp3; where exp1, exp2 and exp3 are expressions.
❖ The operator ?: works as follows:
✓ exp1 is evaluated first. If it is nonzero (true), then the expression
exp2 is evaluated and becomes the value of the conditional expression.
exp3 is evaluated and becomes the value of the conditional expression if exp1 is
false.
Example:
Given a=10, b=15 the expression
x=(a>b)? a:b; will assign the value of b to x. i.e. x=b=15;
4/15/2024 BY SHIMELIS A. 62
6. Bitwise Operators
❖ One of the unique features of java compared to other high-level languages is that
it allows direct manipulation of individual bits within a word.
❖ Bitwise operators are used to manipulate data at values of bit level.
❖ They are used for testing the bits, or shifting them to the right or left.
❖ They may not be applied to float or double data types.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
4/15/2024 BY SHIMELIS A. 63
7. Special Operators
⦁ Javasupports some special operators of interestsuch as instance of
operator and member selection operator(.).
Instance of Operator: is an object reference operator and returns true if
the object on the left-hand side is an instance of the
class given on the right-hand side.
Example :
person instance of student; is true if the object person belongs to the class
student; otherwise it is false
Dot Operator: is used to access the instance variables and methods of class
objects.
Example:
person.age; // Reference to the variable age.
person1.salary(); // Reference to the method salary.
4/15/2024 BY SHIMELIS A. 64
Type Conversion in Expressions
A. Automatic Type Conversion:
✓ If the operands of an expression are of different types, the ‘lower’ type is
automatically converted to the ‘higher’ type before the operation
proceeds.That is, the result is of the ‘higher’ type.
Example :
int a=110; float b=23.5;
✓ The expression a+b yields a floating point number 133.5 since the ‘higher’ type
here is float.
4/15/2024 BY SHIMELIS A. 65
…Contd
B. Casting a value: is used to force type conversion.
4/15/2024 BY SHIMELIS A. 66
//Demonstration of Java Expressions
public class DemoExpress
{
public static void main(String[] args)
{
System.out.println("===== BEGINNING OF THE PROGRAM =====\n");
//Declaration and Initialization int a=10,b=5,c=8,d=2;
float x=6.4f,y=3.0f;
//Order of Evaluation
int answer1=a*b+c/++d;
int answer2=--a*(b+++c)/d++;
//Type Conversion float answer3=a/c;
float answer4=(float)a/c; float answer5=a/y;
4/15/2024 BY SHIMELIS A. 67
//Modulo Operations
int answer6=a%c; float answer7=x%y;
//Logical Operations
boolean bool1=a>b && c>d; boolean bool2=a<b && c>d;
boolean bool3=a<b ||c>d; boolean bool4=!(a-b==c);
System.out.println("Order of Evaluation");
System.out.println("a*b+c/++d + "+answer1);
System.out.println("--a*(b+++c)/d++ = " +answer2);
System.out.println("================");
System.out.println("Type Conversion");
System.out.println(" a/c = "+answer3);
System.out.println("(float)a/c = " + answer4);
System.out.println(" a/y = " + answer5);
4/15/2024 BY SHIMELIS A. 68
System.out.println("================");
System.out.println("Modulo Operations");
System.out.println(" a%c = "+answer6);
System.out.println(" x%y = "+answer7);
System.out.println("================");
System.out.println("Logical Operations");
System.out.println(" a>b && c>d = "+bool1);
System.out.println(" a<b && c>d = "+bool2);
System.out.println(" a<b || c>d = "+bool3);
System.out.println(" !(a-b==c) = "+bool4);
System.out.println("================");
System.out.println("Bitwise Operations");
4/15/2024 BY SHIMELIS A. 69
//Shift O perators
int l=8, m=-8,n=2;
System.out.println(" n & 2= "+(n&2));
System.out.println(" l | n= "+(l|n));
System.out.println(" m | n= "+(m|n));
System.out.println(" l >> 2= "+(l>>2));
System.out.println(" l >>> 1= "+(l>>>1));
System.out.println(" l << 1= "+(l<<1));
System.out.println(" m >> 2= "+(m>>2));
System.out.println(" m >>> 1= "+(m>>>1));
System.out.println("\n===== END OF THE PROGRAM =====");
}
}
4/15/2024 BY SHIMELIS A. 70
POP QUIZ
4/15/2024 BY SHIMELIS A. 72
Variables
❖ Is an identifier that denotes a storage location used to store a data value.
❖ May have constant value or may take different values at different times during
the execution of the program.
⦁ Variable names may consist of alphabets, digits, the underscore (_) and dollar ($)
characters, subject to the following conditions:
1. They should not begin with a digit.
2. Keywords should not be used as a variable name.
3. White spaces are not allowed.
4. Uppercase and lowercase are distinct. i.e. A rose is not a Rose is not a
ROSE.
5. Variable names can be of any length.
4/15/2024 BY SHIMELIS A. 73
Data Types
❖ Every variable in Java has a data type.
❖ Data types specify the size and type of values that can be stored.
❖ Java data types are of two type:
✓ Primitive Data Types
✓ Non-Primitive data Types
4/15/2024 BY SHIMELIS A. 74
Data Types
❖ Every variable in Java has a data type.
❖ Data types specify the size and type of values that can be stored.
❖ Java data types are of two type:
✓ Primitive Data Types
✓ Non-Primitive data Types
4/15/2024 BY SHIMELIS A. 75
Primitive Data Types
❖ There are eight built-in data types in Java:
✓ 4 integer types (byte, short, int, long)
✓ 2 floating point types (float, double)
✓ Boolean (boolean)
✓ Character (char)
❖ All variables must be declared with a data type before they are used.
❖ Each variable'sdeclared type does not change over the course of the
program.
4/15/2024 BY SHIMELIS A. 76
Declaration of Variables
❖ After designing suitable variable names, we must declare them to the
compiler.
❖ Declaration does three things
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold
3. The place of declaration (in the program) declares the scope of the variable.
❖ A variable must be declared before it is used in the program.
❖ The general form of declaration of Variables is:
❖type variable1, variable2,...., variableN;
4/15/2024 BY SHIMELIS A. 77
Assigning Values to Variables
❖ A variable must be given a value after it has been declared but before it is used in
an expression in two ways:
✓ By using an assignment statement
✓ By using a read statement
Assignment Statement
❖ A simple method of giving value to a variable is through the assignment statement
as follows:
variableName = value;
Example: x = 123, y = -34;
❖ It is possible to assign a value to a variable at the time of declaration as:
type variableName = value;
81
4/15/2024 BY SHIMELIS A. 78
Keyboard Input(By using a read statement)
❖ To assign value for variables interactively through the keyboard, we first create a
Scanner object, that is attached to the System.in data stream object
✓ E.g. Scanner input = new Scanner(System.in);
❖ Then use the various methods of the Scanner class to read input.
✓ For example, the nextLine() method reads a line of string input
✓ E.g. System.out.print("What is your name? ");
String name = in.nextLine();
✓ nextInt(), nextDouble() etc are methods to read.
❖ We must import java.util.*; package so as to use the Scanner class.
4/15/2024 BY SHIMELIS A. 79
Sample Program for I/O
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("What is your name? "); String
name = in.nextLine(); // gets first input
System.out.print("How old are you? ");
int age = in.nextInt(); // gets second input
System.out.println("Hello, " + name + ". Next year, you'll be " +
(age + 1));
// display output on console
}
}
4/15/2024 BY SHIMELIS A. 80
Scope of Variables
1. Instance Variables
❖ are declared in a class, but outside a method, constructor or any block.
✓ are created when an object is created with the use of the key word 'new' and destroyed when the
object is destroyed.
✓ They take different values for each object
2. Class Variables:
❖ are also known as static variables, are declared with the static keyword in a class,
but outside a method, constructor or a block.
✓ Are global to a class and belong to the entire set of objects that class creates.
✓ Only one memory location is created for each class variable.
3. Local Variables:
❖ are variables declared and used inside methods.
✓ Can also be declared inside program blocks that are define between { and }.
4/15/2024 BY SHIMELIS A. 81
Control Structures
4/15/2024 BY SHIMELIS A. 82
Introduction
❖ The statements inside your source files are generally executed from top to
bottom, in the order that they appear.
❖ Control flow statements, however, break up the flow of execution by employing
decision making, looping, and branching, enabling your program to conditionally
execute particular blocks of code.
4/15/2024 BY SHIMELIS A. 83
Decision Making Statements
❖ allows the code to execute a statement or block of statements conditionally.
❖ Control the execution flow of a program causing a jump to any point from its
current location.
✓ if Statements
✓ switch Statements
4/15/2024 BY SHIMELIS A. 84
Decision Making with if Statement
❖ The if statement is a powerful decision making statement.
❖ It is basically a two-way decision making statement and is used in conjunction
with an expression.
4/15/2024 BY SHIMELIS A. 85
1. Simple if Statement
❖ An if statement consists of a Boolean expression followed by one or more
statements.
4/15/2024 BY SHIMELIS A. 86
2. if … else Statement
❖ The syntax of an if statement is:
if (expression)
{
True-block statement(s);
}
else
{
False-block statement(s);
}
rest_of_program;
❖ If expression is true, True-block statement is executed and followed
by rest_of_program block.
❖ If expression is false, False-block Statement is excuted followed by
rest_of_program block.
4/15/2024 BY SHIMELIS A. 87
3. If… else if (else if Ladder) Statement
❖ Is used when multiple decisions are involved.
❖ The syntax of an if … . else if statement is:
if (expression 1)
{
statement(s)-1;
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default-statement;
rest_of_program;
4/15/2024 BY SHIMELIS A. 88
4. Nested if… else Statement
❖ if…else statements can be put inside other if…else statements. such
statements are called nested if … else statements.
4/15/2024 BY SHIMELIS A. 89
Switch statement
❖ We can design a program with multiple alternatives using if statements to
control the selection.
❖ But the complexity of such programs increases dramatically when the number
alternatives increases.
❖ Java has a multiway decision statement called switch statement.
❖ The switch statement tastes the value of a given variable(expression) against a list
of case values and when a match is found, a block of statements associated with
that case is executed.
❖ The syntax of switch statement:
4/15/2024 BY SHIMELIS A. 90
Switch statement
❖ We can design a program with multiple alternatives using if statements to
control the selection.
❖ But the complexity of such programs increases dramatically when the number
alternatives increases.
❖ Java has a multiway decision statement called switch statement.
❖ The switch statement tastes the value of a given variable(expression) against a list
of case values and when a match is found, a block of statements associated with
that case is executed.
❖ The syntax of switch statement:
4/15/2024 BY SHIMELIS A. 91
...Contd
❖ The expression must evaluate to a char, short or int, but not long, float or double.
❖ The values value-1, value-2, … are constants or constant expressions (evaluable
to an integral constant) and are known as case labels.
❖ Each of the case labels should be unique within the switch statement.
❖ statement-block1,statement-block2,…. Are statement lists and may contain zero
or more statements.
❖ No need to put braces around the statement blocks of a switch statement
but it is important to note that case labels end with a colon (:).
❖ The break statement at the end of each block signals the end of a particular
case and causes an exit from the switch statement.
4/15/2024 BY SHIMELIS A. 92
class Main {
public static void main(String[] args) {
int number = 44;
String size;
// switch statement to check size
switch (number) {
case 42:
size = "Medium";
break;
// match the value of week
case 44:
size = "Large";
break;
default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}
4/15/2024 BY SHIMELIS A. 93
Exercise
1. Find out Errors in the following program and discuss ways for correction.
a) //Errors.java
public Class Errors{
public void main(String [] args){ int i, j = 32768;
short s = j;
double m = 5.3f, n = 2.1f; float x = 5.3, y =
2.1; byte z = 128;
System.out.println("x % y = "+x % y); boolean b = 1 ;
if (b) System.out.println(“b is true”);
else System.out.println(“b is false”);
}
}
4/15/2024 BY SHIMELIS A. 94
2. Write a Java application program that asks the user to enter two numbers obtains
the numbers from the user and prints the sum, product, difference and quotient
of the numbers?
3. Write a Java application program that asks the user to enter two integers,
obtains the numbers from the user and displays the larger number followed by
the words “is larger than “ the smaller number in the screen. If the numbers are
equal, print the message “These numbers are equal.”
4. Write four different Java statements that each add 1 to integer variable x.
5. Rewrite each of the following without using compound relations:
a) if(grade<=59 && grade>=50) second+=1;
b) if(num>100 || num<0) System.out.prinln(“Out of 6. Write a Java application program that
Range”); else reads the coefficients of a quadratic equation
(ax2+bx+c=0), generates and display the roots.
sum+=num;
Note:
c) If((M>60 && N>60)||T>200) An appropriate message should be generated when
y=1; the user types an invalid input to the equation.
Else
y=0;
4/15/2024 BY SHIMELIS A. 95
Looping
4/15/2024 BY SHIMELIS A. 96
Introduction
❖ The process of repeatedly executing a block of statements is known as looping.
❖ A loop allows you to execute a statement or block of statements repeatedly.
❖ The statements in the block may be executed any number of times, from zero
to infinite number.
4/15/2024 BY SHIMELIS A. 97
…Contd
❖ A program loop consists of two statements:
1. Body of the loop.
2. Control statements.
❖ The control statement tests certain conditions and then directs the repeated
execution of the statements contained in the body of the loop.
❖ A looping process, in general, would include the ff. four steps:
1. Setting and initialization of a counter .
2. Execution of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Increment/Decrement the counter.
4/15/2024 BY SHIMELIS A. 98
…Contd
❖ Depending on the position of the control statement in the loop, a control
structure can be either as the entry-controlled loop or as exit- controlled
loop.
❖ In entry-controlled loop, the control conditions are tested before the start of
the loop execution.
❖ In exit-controlled loop, the test is performed at the end of the body of the
loop and therefore the body is executed unconditionally for the first time.
❖ Three types of loops in java:
1. while loops:
2. do …while loops:
3. for loops:
4/15/2024 BY SHIMELIS A. 99
1. The while loop
❖ Is the simplest of all the looping structures in Java.
❖ The while loop is an entry-controlled loop statement.
❖ The while loop executes as long as the given logical expression between
parentheses is true. When expression is false, execution continues with the
statement immediately after the body of the loop block.
❖ We use the for loop if we know in advance for how many times the body of
the loop is going to be executed.
❖ But use do…. while loop if you know the body of the loop is going to be
executed at least once.
4/15/2024 BY SHIMELIS A. 104
...CONTD
Example
int sum=0;
for(n=1; n<=100; n++)
{
sum=sum+n;
}
System.out.println(“Sum is:”+sum);
Example:
for(sum=0, i=1; i<20 && sum<100; ++i)
{
sum=sum+i;
}
continue label;
❖ It may be used with or without a label.
❖ When used without a label, it causes the statement block of the innermost for, do, or while
statement to terminate and the loop’s boolean expression to be re-evaluated to determine
whether the next loop repetition should take place.
Example:
int sum = 0;
for(int i = 1; i <= 10; i++)
{
if(i % 3 == 0)
{
continue;
}
sum += i;
}
What is the value of sum?
ANS:- 1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
4/15/2024 BY SHIMELIS A. 111
3. The return Statement
❖ A return statement is used to transfer the program control to the caller of a
method.
return expression;
❖ If the method is declared to return a value, the expression used after the return
statement must evaluate to the return type of that method. Otherwise, the
expression is omitted.
a) c) 5
$ $ $ $ $ 454
$ $ $ $ 34543
$ $ $ 2345432
$ $ 123454321
$
b) 1
d) 1 2 3 4 5 4 3 2 1
1 2
1234321
1 2 3 12321
1 2 3 4 121
1 2 3 4 5 1
❖ Array indexing starts from 0 and ends at n-1, where n is the size of the array.
Example:
int number[]; float slaray[]; float[]
marks;
❖ when creating an array, each element of the array receives a default value zero (for
numeric types) ,false for boolean and null for references (any non primitive types).
❖ The Java interpreter checks array indices to ensure that they are valid
during execution.
❖ Arrays can also be initialized automatically in the same way as the ordinary
variables when they are declared, as shown below:
Array Le n gth
❖ In Java, all arrays store the allocated size in a variable named length.
❖ We can access the length ofthe array array1 using array1.length.
Example:
int size = array1.length;
Example:
int myarray[][]= int [3][4];
X[1]
X[2] x[1][3]
x[2][2]
4/15/2024 BY SHIMELIS A. 129
Strings in Java
BY SHIMELIS A. 133
STRING ARRAYS
❖ It is possible to create and use arrays that contain strings as follows:
String arrayname[] = new String[size];
Example:
String item[]= new String[3];
item[0]= “Orange”;
item[1]= “Banana”;
item[2]= “Apple”;
b) Write a single statement that sets the elements of array3 in row 1 and column 2 as zero.
d) Write a nested for statement that initializes each element of array3 to two.
e) Write a nested for statement that inputs the values for the elements of array3 from the
user.
f) Write a series of statements that determines and prints the smallest value in array3.
g) Write a statement that displays the elements of the first row of array3.
h) Write a statement that totals the elements of the third column array3.
3. Write a program which reads the values for two matrices and displays their product.
4. Write a program, which will read a string and rewrite it in alphabetical order.
5. Write a java application program which reads a paragraph and displays the number of
words within the paragraph.
NOTICE:
✓ submission date is 26-04-2024
✓ Being late will nullify your result