SlideShare a Scribd company logo
1 of 85
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 1
NOMINAL DURATION: 240hrs
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 2
LO1. Apply basic language syntax and layout
1.1 Introduction to Programming Language
As we know, to communicate with a person, we need a specific language, similarly to communicate with computers,
programmers also need a language is called Programming language.
Before learning the programming language, let's understand what is language?
What is Language?
Language is a mode of communication that is used to share ideas, opinions with each other. For example, if we
want to teach someone, we need a language that is understandable by both communicators.
1.1.1 What is a Programming Language?
A program is a set of instructions given to a computer to perform a specific operation. or computer is a
computational device which is used to process the data under the control of a computer program.
A programming language is a computer language that is used by programmers (developers) to communicate
with computers. It is a set of instructions written in any specific language ( C, C++, Java, Python) to perform a
specific task.
A programming language is mainly used to develop desktop applications, websites, and mobile applications.
 Types of programming language
 Low-level programming language
Low-level language is machine-dependent (0s and 1s) programming language. The processor runs low- level
programs directly without the need of a compiler or interpreter, so the programs written in low-level language can be
run very fast.
Low-level language is further divided into two parts –
i. Machine Language
Machine language is a type of low-level programming language. It is also called as machine code or object code.
Machine language is easier to read because it is normally displayed in binary or hexadecimal form (base 16) form. It
does not require a translator to convert the programs because computers directly understand the machine language
programs.
The advantage of machine language is that it helps the programmer to execute the programs faster than the high-
level programming language.
ii. Assembly Language
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 3
Assembly language (ASM) is also a type of low-level programming language that is designed for specific
processors. It represents the set of instructions in a symbolic and human-understandable form. It uses an
assembler to convert the assembly language to machine language.
The advantage of assembly language is that it requires less memory and less execution time to execute a program.
 High-level programming language
High-level programming language (HLL) is designed for developing user-friendly software programs and
websites. This programming language requires a compiler or interpreter to translate the program into machine
language (execute the program).
The main advantage of a high-level language is that it is easy to read, write, and maintain.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective C, Cobol, Perl,
Pascal, LISP, FORTRAN, and Swift programming language.
There are several approaches to programming processes in A high-level language. But the two most popular and
important ones are object-oriented programming and procedural programming.
I. Procedural Oriented programming language
Procedural Oriented Programming (POP) language is derived from structured programming and based upon the
procedure call concept. It divides a program into small procedures called routines or functions.
Procedural Oriented programming language is used by a software programmer to create a program that can be
accomplished by using a programming editor like IDE, Adobe Dreamweaver, or Microsoft Visual Studio.
The advantage of POP language is that it helps programmers to easily track the program flow and code can be
reused in different parts of the program.
The advantage of POP language is that it helps programmers to easily track the program flow and code can be
reused in different parts of the program.
Example: C, FORTRAN, Basic, Pascal, etc.
II Object-Oriented Programming language
Object-Oriented Programming (OOP) language is based upon the objects. In this programming language,
programs are divided into small parts called objects. It is used to implement real-world entities like
inheritance, polymorphism, abstraction, etc in the program to makes the program resusable, efficient, and easy-to-
use.
The main advantage of object-oriented programming is that OOP is faster and easier to execute, maintain, modify, as
well as debug.
Note: Object-Oriented Programming language follows a bottom-up approach.
Example: C++, Java, Python, C#, etc.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 4
 Differences between object-oriented and procedural programming
The objective of procedural programming is to break down a program into a collection of variables, data structures
whereas the main aim of object-oriented programming is to break down a programming task into objects. In simple
words, procedural programming uses procedures to operate on data structures, while object-oriented uses objects for
the purpose.
In both programming paradigms, the nomenclature is different though have similar semantics:
Procedural Programming Object-oriented Programming
Procedure Method
Record Object
Module Class
Procedure call Message
Object-oriented programming?
Object-oriented programming combines a group of variables (properties) and functions (methods) into a unit
called an "object." These objects are organized into classes where individual objects can be grouped together.
OOP can help you consider objects in a program's code and the different actions that could happen in relation
to the objects.
This programming style widely exists in commonly used programming languages like Java, C++ and PHP.
These languages help simplify the structure and organization of software programs. Programmers often use
OOP when they need to create complex programs.
Self-Check -1 Written Test
Directions: Answer all the questions listed below. Use the Answer sheet provided in the next
page:(2 pts each)
1. What is program?
2. What is programing language?
3. Define low level and high level programing language?
4. Write The Deference between object oriented and Procedural programing language?
5. Write at least two example of object oriented programing language?
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 5
1.2. Understanding Basic language syntax rules and best practices
What are the Basic programming languages?
Some of the basic programming languages are:
 C, C++, JAVA, Visual Studio (Visual basic.Net, C-Sharp(C#), and Visual C++), and so on.
Syntax is a rule that specify how valid instructions (constructs) are written.
1.2.1 Introduction to Java programming
JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was
developed by James Gosling and Patrick Naughton. It is a simple programming language. Writing,
compiling and debugging a program is easy in java. It helps to create modular programs and reusable code.
• Simple Java is considered as one of simple language because it does not have complex features like
Operator overloading, multiple inheritance, pointers and Explicit memory allocation.
• Multithreading Java supports multithreading. Multithreading is a Java feature that allows concurrent
execution of two or more parts of a program for maximum utilisation of CPU.
• Portable The platform independent byte code can be carried to any platform for execution that makes
java code portable.
Java Virtual Machine (JVM)
This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program execution.
Phases are as follows: we write the program, then we compile the program and at last we run the program.
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler included in java
development kit (JDK).
It takes java program as input and generates java bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run phase.
So, now that we understood that the primary function of JVM is to execute the bytecode produced by
compiler. Each operating system has different JVM, however the output they produce after execution
of bytecode is same across all operating systems. That is why we call java as platform independent
language.
Bytecode As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it
can be executed by JVM. The bytecode is saved in a .class file by compiler.
Java Development Kit(JDK) As the name suggests this is complete java development kit that includes JRE
(Java Runtime Environment), compilers and various tools like Java debugger etc. In order to create, compile
and run Java program you would need JDK installed on your computer.
JVM Vs JRE Vs JDKJRE: JRE is the environment within which the java virtual machine runs. JRE
contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as
compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile the code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.
JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as
compiler, debugger etc
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 6
Java is a platform independent language
Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned above, JVM
executes the bytecode produced by compiler. This byte code can run on any platform such as Windows,
Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux and vice-
versa? Each operating system has different JVM, however the output they produce after execution of
bytecode is same across all operating systems. That is why we call java as platform independent
language.
JAVA Basic Syntax contains:
 Object
 Class
 Methods
 Data type
 Return type
 Variable
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 7
Java - Basic Syntax
• When we consider a Java program, it can be defined as a collection of objects that communicate via
invoking each other's methods. Let us now briefly look into what do class, object, methods, and
instance variables mean.
• Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well
as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
• Class − A class can be defined as a template/blueprint that describes the behavior/state that the object
of its type supports.
• Methods − A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
• Variable: A variable is the name for a memory location where you store some data. A variable in
Java must be declared (the type of variable) and defined (values assigned to a variable) before it can
be used in a program.
• Data type: A data type defines which kind of data will store in variables and also defines memory
storage of data. There are two kinds of data types User defined data types and Standard data types.
• Return type: Return type is used to terminate main( ) Method and causes it to return the value to its
type. If a Method is defined as having a return type of void, it should not return a value. If a Method
is defined as having a return type other than void, it should return a value.
Syntax
public class FirstJavaProgram {
public static void main(String[] args){
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class
Every line of code that runs in Java must be inside a class. In our example, we named the class
FirstJavaProgram. A class should always start with an uppercase first letter.
Note: Java is case-sensitive: " FirstJavaProgram " and " firstJavaprogram " has different meaning.
The name of the java file must match the class name. When saving the file, save it using the class name and
add ".java" to the end of the filename.
Let we see each line of code one by
public class FirstJavaProgram {
This is the first line of our java program. Every java application must have at least one class definition that
consists of class keyword followed by class name. When I say keyword, it means that it should not be
changed, we should use it as it is. However the class name can be anything.
We have made the class public by using public access modifier, we will cover access modifier in a separate
post, all you need to know now that a java file can have any number of classes but it can have only one
public class and the file name should be same as public class name.
The next is main method
public static void main(String[] args) {
This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from outside the class.
static: We do not need to create object for static methods to run. They can run itself.
void: It does not return anything.
main: It is the method name. This is the entry point method from which the JVM can run your program.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 8
(String[] args): Used for command line arguments that are passed as strings. We will cover that in a separate
post.
Next the method
System.out.println("This is my first program in java");
This method prints the contents inside the double quotes into the console and inserts a newline after.
Note: The curly braces {} marks the beginning and the end of a block of code.
Note: Each code statement must end with a semicolon
Self-Check -2 Written Test
Directions: Answer all the questions listed below. Use the Answer sheet provided in the next
page:(2 pts each)
1. Which one of the following is true about java programing language?
A. platform independent byte code can be carried to any platform
B. Java supports multithreading
C. is object oriented programing language
D. all
2. The correct phases of java program execution
A. Writing of the program execute the bytecode generated by compiler Compile
the program by javac compiler
B. Writing of the program Compile the program by javac compiler  execute the
bytecode generated by compiler
C. Compile the program by javac compiler Writing of the program execute the
bytecode generated by compiler
D. execute the bytecode generated by compiler Writing of the program Compile
the program by javac compiler
3. Java feature that allows concurrent execution of two or more parts of a program for
maximum utilisation of CPU.
A. Portable B. not complex C. Multithreading D. platform independent
4. The type of code generated after JDK compiles the java source code and save it into
a .class file to be can be executed by JVM.
A. Source code B. Byte code C. Machine code D. B&C
5. Which one is true
A. In order to create, compile and run Java program you would need JDK installed on
your computer.
B. Java Development Kit(JDK) includes JRE (Java Runtime Environment), compilers
and various tools like Java debugger
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 9
C. Java Runtime environment (JRE) contains Java virtual Machine(JVM), class
libraries but not compiler and debugger
D.All
6. Java - Basic Syntax is
A. Accessmodifier Class ClassName{
Public static Void Main(String[] args){
//body
}}
B. Accessmodifier Class MethodName(){
Public static Void Main(String[] args){
//method
}}
C. Accessmodifier DataType variableName{
Public static Void Main(String[] args){
//variables
}}
D. All
7. Which of the following option leads to the portability and security of Java?
A. Bytecode is executed by JVM
B. The applet makes the Java code secure and portable
C. Use of exception handling
D. Dynamic binding between object
1.3 Understanding Data-Types, Operators and Expressions
Data type: A data type defines which kind of data will store in variables and also defines memory storage of
data.
There are two kinds of data types User defined data types and Standard data types.
The Java language allows you to create and use data types other than the fundamental data types. These
types are called user-defined data types.
In Java language, there are four main data types
• char
• int
• float
• Boolean
1. Character data type
 A keyword char is used for character data type. This data type is used to represents letters or
symbols.
 A character variable occupies 1 byte on memory.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 10
2. Integer data types
Integers are those values which have no decimal part and they can be positive or negative. Like 12 or -12.
There are 3 data types for integers
a. int
b. short int
c. long int
 int keyword is used for integers. It takes two bytes in memory.
There are two more types of int data type.
i. Signed int or short int (2nd type of integer data type)
ii. Unsigned int or unsigned short int
Signed int: The range of storing value of signed int variable is -32768 to 32767.It can interact
with both positive and negative value.
Unsigned int: This type of integers cannot handle negative values. Its range is 0 to 65535.
Long int
 As its name implies, it is used to represent larger integers.
 It takes 4byte in memory and its range is -2147483648 to 2147483648.
3. Float: This type of data type is defined for fractional numbers.
There are two further type of data type for fractional numbers.
Below table is Displaying:
 Number of bytes or memory taken by numbers. Decimal places up to which they can represent value.
Data type Bytes Decimal places Range of values
float 4 6 3.4E -38 to3.4E+38
double 8 15 1.7E - 308 to1.7E +308
long double 10 19 3.4E -4932 to 304E +4932
Constant
Constant is a data type whose value is never changes and remains the same through the programme
execution.
Example: - Area of the circle A=πr2 ; const float π=3.14
- Total number of days in a week=7 ;
- Total hours in a day=24
- Body temperature of human=23C0;
Here the value of above listed can be treated as a constant through the program execution.
The four basic data types in java, their meaning, and their size are:
Type Meaning Size (bytes) Size (bits)
char a single byte, capable of holding one character 1 byte 8 bits
int an integer 2 bytes 16 bits
float single-precision floating point number 4 bytes 32 bits
double double-precision floating point number 8 bytes 64 bits
Byte is the smallest addressable memory unit. Bit, which comes from BInary digiT, is a memory unit that
can store either a 0 or a 1. A byte has 8 bits.
Operators in Java
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 11
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
Java is rich in built-in operators and provides following type of operators:
 Arithmetic Operators
 Relational Operators
 Increment Operator
 Decrement Operator
 Scope resolution operator
 Logical Operators
 Assignment Operators
 Arithmetic Operators:
The following arithmetic operators are supported by Java language:
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
%
Modulus Operator and remainder of after an integer
division
B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9
 RelationalOperators:
The following relational operators are supported byJava language:
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
== Checks if the value of two operands is equal or not, (A == B) is not true.
!= Checks if the value of two operands is equal or not, (A != B) is true.
>
Checks if the value of left operand is greater than
the value of right operand,
(A > B) is not true.
<
Checks if the value of left operand is less than the
value of right operand,
(A < B) is true.
>=
Checks if the value of left operand is greater than or
equal to the value of right operand,
(A >= B) is not true.
<=
Checks if the value of left operand is less than or
equal to the value of right operand,
(A <= B) is true.
Logical/Boolean operator:
The following logical operators are supported by Java language:
Assume variable A holds 1 and variable B holds 0 then:
Operator Description Example
&&
If both the operands are non-zero then condition
becomes true.
(A && B) is false.
||
If any of the two operands is non-zero then
condition becomes true.
(A || B) is true.
!
Use to reverses the logical state of its operand. If a
condition is true then Logical NOT operator will
make false.
!(A && B) is true.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 12
Assignment Operators:
Assignment operator is used for assign/initialize a value to the variable during the program execution.
The following assignment operators are supported by Java language:
Operator Description Example
=
Simple assignment operator, Assigns values from
right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right
operand to the left operand and assign the result to
left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts
right operand from the left operand and assign the
result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies
right operand with the left operand and assign the
result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left
operand with the right operand and assign the result
to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes
modulus using two operands and assign the result to
left operand
C %= A is equivalent to C = C % A
Increment Operator (++): This operator is used for increment the value of an operand.
Example: assume that A=20 and B=12, then ++A=21, ++B=12 and A++=20, B++=12
Decrement Operators (--):This operator is used for decrement the value of an operand.
Example: assume that B=14 and C=10, then –B=13, --C=9 and B-- =14, C--=10
Scope resolution operator (::)
This operator is used to differentiate a local variable from the global variable. The variable having the same
name can have different meaning at different block.
Expression:
Expressions are formed by combining operators and operands together following the programming language.
Compile & Execute Java Program:
Let’s look at how to save the file, compile and run the program. Please follow the steps given below:
 Open a text editor and write the code
 Save the file as : hello.java
 Compile it to check if it has error
 Debug the code.
 You will be able to see ' Hello World '
printed on the window.
Semicolons & Blocks in Java:
In Java, the semicolon is a statement terminator. Each individual statement must be ended with a semicolon.
For example, following are three different statements: x = y;
y = y+1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing braces. For
example:
{
System.out.println( "Hello World"); // prints Hello World
return 0;}
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 13
Self-Check -3 Written Test
Directions: Answer all the questions listed below. Use the Answer sheet provided in the next
page:(2 pts each)
1. Decrement operator, −−, decreases the value of variable by what number?
A. 1 B. 2 C. 3 D.4
2. Which of these statements are incorrect?
A. Assignment operators are more efficiently implemented by Java run-time system
than their equivalent long forms
B. Assignment operators run faster than their equivalent long forms
C. Assignment operators can be used only with numeric and character data type
D.None of the mentioned
3. Can 8 byte long data type be automatically type cast to 4 byte float data type?
A. True B. False
4. To change the order in which expressions areevaluated …………………. areplaced around the
expression that is to be evaluated first.
A) ampersand B) equals C) parentheses D) greater than
5. What will bethe result of the expression of 8/8.
A) 16 B) 1 C) 8 D) 64
6. If j and k are int typevariables, what will bethe result of the expression j%k when j=10
and k=3?
A) 0 B) 1 C) 2 D) 3
7. Which of the following assignment operator does not exist in Java?
A. > B. %= C >>> D <
8. Modulus operator, %, can be applied to which of these?
A. Both Integers and floating - point numbers
B. Integers
C. Floating - point numbers
D. None of the mentioned
1.4 Using the Appropriate Language Syntax for Sequence, Selection
and Iteration Constructs
Control Structures in java is a Statement that used to control the flow of execution in a program.
There are three types of Control Structures:
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 14
1. Sequence structure
2. Selection structure
3. Loops/ Repetition/ Iteration
Sequence Structure in java
The sequence structure is built into java statements that execute one after the other in the order in which they
are written—that is, in sequence. Break and continue statements are example of sequence control structure.
The ‘break’ statement causes an immediate exit from the inner most ‘while’, ‘do…while’, ‘for loop’ or from
a ‘switch- case’ statement.
If you are using nested loops (ie. one loop inside another loop), the break statement will stop the execution of
the innermost loop and start executing the next line of code after the block.
Flow Diagram:
Example:
public class FirstJavaProgram {
public static void main(String[] args){
int a = 10; // Local variable declaration:
do{ // do loop execution
System.out.println("value of a: "+a);
a = a + 1;
if( a > 15)
{
break;
}
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 15
The goto statement provides an unconditional jump from the goto to a labeled statement in the same
function.
Syntax of a goto statement in java:
goto label;
..
.
label: statement;
Where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is
preceded by an identifier followed by a colon (:).
Flow Diagram:
Example:
public class FirstJavaProgram {
public static void main(String[] args){
int a = 10; // Local variable declaration:
LOOP:do // do loop execution
{
if( a == 15)
{
a = a + 1;// skip the iteration.
goto LOOP;
}
System.out.println("value of a: " +a );
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 16
value of a: 17
value of a: 18
value of a: 19
The continue statement is similar to ‘break’ statement but instead of terminating the loop, the continue
statement returns the loop execution if the test condition is satisfied.
Flow Diagram:
Example:
public class FirstJavaProgram {
public static void main(String[] args){
int a = 10; // Local variable declaration:
do{ // do loop execution
if( a == 15)
{
a = a + 1; // skip the iteration.
continue;
}
System.out.println("value of a: " +a );
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Selection statements in java
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 17
There are basically two types of control statements in java that allows the programmer to modify the regular
sequential execution of statements. They are selection and iteration statements.
The selection statements allow to choose a set of statements for execution depending on a condition.
If statement and switch statement are the two selection statements.
If ... else statement:
Syntax: if (expression or condition)
{
Statement 1;
Statement 2;
}
Else
{
Statement 3;
Statement 4;
}
If the condition is true, statement1 and statement2 is executed; otherwise statement 3 and statement 4 is
executed.
The expression or condition is any expression built using relational operators which either yields true or false
condition.
Flow Diagram:
If the condition evaluates to true, then the if block of code will be executed otherwise else block of code
will be executed. Following program implements the if statement.
public class FirstJavaProgram {
public static void main(String[] args){
int num=12;
if ((num%2) == 0)
System.out.println("is a even number ");
else
System.out.println("a number is odd");
}
The above program accepts a number from the user and divides it by 2 and if the remainder (remainder is
obtained by modulus operator) is zero, it displays the number is even, otherwise it is odd.
you must use the relational operator ‘ ==’ to compare whether remainder is equal to zero or not.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 18
Switch statement
One alternative to nested if statement is the switch statement which allows a variable to be tested for equality
against a list of values. Each value is called a case, and the variable being switched on is checked for each
case.
Syntax:
Switch (variablename)
{
case value1: statement1; break;
case value2: statement2; break;
case value3: statement3; break;
default: statement4;
}
Flow Diagram:
Example:
public class
FirstJavaProgram {
public static void
main(String[] args){
int
choice=3;
switch
(choice)
{
case 1:
System.out.println(""First
item selected!" );
break;
case 2:
System.out.println(""second item selected!" );
break;
case 3: System.out.println(""third item selected!" );
break;
default: System.out.println("Invalid selection!!" ); }
}}
Iteration statements in java
Iteration or loops statements are important statements in java, which helps to accomplish repeatitive
execution of programming statements.
There are three loop statements in java. They are - while loop, do while loop and for loop.
While Loop
The while loop construct is a way of repeating loop body over and over again while a certain condition
remains true. Once the condition becomes false, the control comes out of the loop. Loop body will execute
only if condition is true.
Syntax: While (condition or expression)
{
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 19
Statement1;
Statement 2;
}
Flow Diagram:
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is
executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the
condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to display
the output.
Example:
public class FirstJavaProgram {
public static void main(String[] args){ {
int n=10, i=1, sum=0;
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println( " sum of the series is "+ sum);
}
Do …While loop
The do... while statement is the same as while loop except that the condition is checked after the execution of
statements in the do..while loop.
Syntax: do{
Statement;
While (test condition);
Statement;
}
Flow Diagram:
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 20
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated
after the execution of statement. Hence in do..while loop, Loop body execute once even if the condition is
false.
Example:
public class FirstJavaProgram {
public static void main(String[] args){
int n=10, i=1, sum=0;
{
int n, i=1, sum=0;
do{
sum=sum+i;
i++;
} while(i<=n);
System.out.println( " sum of the series is "+ sum);
}}
For loop:
The for loop statements (loops or iteration statement) in java allow a program to execute a single statement
multiple times (repeatedly) , given the initial value, the condition, and increment/decrement value.
Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is:
for (initialExpression; testExpression; updateExpression) { // body of the loop }
Here,
• The initialExpression initializes and/or declares variables and executes only once.
• The condition is evaluated. If the condition is true, the body of the for loop is executed.
• The updateExpression updates the value of initialExpression.
syntax:
for ( initial value ; test condition ; increment/decrement)
{
Statement;
}
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 21
Flow Diagram:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
Example: public class FirstJavaProgram {
public static void main(String[] args){
int n=10, i=1, sum=0;
{
for(i=1;i<=n; i++)
{
sum=sum+i;
}
System.out.println( " sum of the series is "+ sum);
}}
Nested Loop in Java
If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the
nested for loop.
Syntax for Nested For loop:
for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of
inside loop } // statement of outer loop }
// outer loop
for (int i = 1; i <= 5; ++i) {
// codes // inner loop
for(int j = 1; j <=2; ++j) {
// codes } .. }
class Main
{ public static void main(String[] args) {
int weeks = 3;
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 22
int days = 7;
// outer loop prints weeks
for (int i = 1; i <= weeks; ++i) { System.out.println("Week: " + i);
// inner loop prints days
for (int j = 1; j <= days; ++j) {
System.out.println(" Day: " + j); } } } }
output
Week: 1
Day: 1
Day: 2
Day: 3
Day:4
.....
.. ....
Week: 2
Day: 1
Day: 2
Day: 3
In the above example, the outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates 7 times
and prints the 7 days.
Self-Check -4 Written Test
Directions: Answer all the questions listed below. Use the Answer sheet provided in the next
page:(2 pts each)
1. The while loop repeats a set of code while the condition is not met?
A) True B) False
2. What is true about a break?
A. Break stops the execution of entire program
B. Break halts the execution and forces the control out of the loop
C. Break forces the control out of the loop and starts the execution of next
iteration
D. Break halts the execution of the loop for certain time frame
3. What is true about do statement?
A. do statement executes the code of a loop at least once
B. do statement does not get execute if condition is not matched in the first
iteration
C. do statement checks the condition at the beginning of the loop
D. do statement executes the code more than once always
4. Which of the following is used with the switch statement?
A) Continue B) Exit C) break D) do
5. From where break statement causes an exit?
a) Only from innermost loop
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 23
b) Terminates a program
c) Only from innermost switch
d) From innermost loops or switches
6. Which of the following is not a valid flow control statement?
a) exit() b) break c) continue d) return
1.5 Using modular programming approach
Many programs are too long or complex to write as a single unit. Programming becomes much simpler when
the code is divided into small functional units (modules).
Modular programming is a programming style that breaks down program functions into modules, each of
which accomplishes one function and contains all the source code and variables needed to accomplish that
function.
Modular programs are usually easier to code, compile, debug, and change than large and complex programs.
The benefits of modular programming are:
 Efficient Program Development
Programs can be developed more quickly with the modular approach since small subprograms are
easier to understand, design, and test than large and complex programs.
 Multiple Use of Subprograms
Code written for one program is often useful in others.
 Ease of Debugging and Modifying
Modular programs is generally easier to compile and debug than monolithic (large and complex)
programs.
1.5.1 Modularity in Java
If you've been a developer for any length of time, you'll have very likely realized that the word module is
perhaps one of the most over used terms in software development. A module can mean anything ranging
from a group of code entities, components, or UI types, to framework elements to complete reusable
libraries. Sometimes, we use the word to imply multiple meanings in the same context!
There is a good reason for that. When writing code, we typically try to break the code base down into smaller
units in order to manage complexity. For anything more than very simple programs, having a monolithic
code base is not a good idea. That's why modular programming is a generally favored software design
approach. There are two important goals that modularity in software development usually achieves, which
are as follows:
Divide and conquer approach
What do you do when you need to solve a large and seemingly insurmountable problem? You break it
down! You'll very likely split it into smaller problems and solve them individually.
The principles of modularity encourages separating large code bases into smaller encapsulated units of
functionality that are then composed to work together as a bigger unit. This aligns well with the approach we
humans usually take to solve large problems. Also, once you've got a bunch of smaller modules with
specialized concerns, you can use those to solve various other problems. Thus, we also achieve reusability!
When you build modules, you have the ability to hide the internal implementation from the consumers of
your module. The hidden implementation details are usually referred to as being encapsulated, and what you
expose to the consumers of your module is usually called the interface of your module.
Achieving encapsulationand well-defined interfaces
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 24
When you build modules, you have the ability to hide the internal implementation from the consumers of
your module. The hidden implementation details are usually referred to as being encapsulated, and what you
expose to the consumers of your module is usually called the interface of your module.
Although Java developers have leveraged many different patterns and best practices over the years in order
to write and structure modular and maintainable code, the language has never had native support to create
modular units and build modular applications, until Java 9. With Java 9, Java developers now have the ability
to create smaller units of code with a new construct called Java modules that they can group together like
building blocks in order to compose larger applications. In addition to introducing this feature to the
language, Java 9 also comes with what is probably the biggest overhaul to the core Java code bases itself.
The Java Runtime Environment (JRE) and the Java Development Kit (JDK) have been rewritten to use
the concepts of modularity so that the core Java Platform itself is modularized.
When learning about Java 9 module features, it's important to understand what those new features add to the
language when compared to the other features the language already has. Can't we write well organized code
in Java 8? In fact, one of the benefits of object-oriented programming is indeed the idea of breaking down
functionality into sub-units called objects or classes. We've been writing code like this in Java since version
1. Every Java class contains a portion of the overall application functionality that happens to belongs
together. We have the ability to encapsulate some functionality as internal to a class (as private) and some
others as external (or public).
And then there's something in between with protected, thanks to the concept of packages.
1.6 Using arrays and arrays of objects
An Array is a collection of similar data items which shares a common name within the consecutive memory.
An Array can be any data type, but it should be the collection of similar items.
Each item in an array is termed as ‘element’, but each element in an array can be accessed individually.
The number of element in an array must be declared clearly in the definition.
The size or number of elements in the array can be varied according to the user needs.
Syntax for array declaration:
DataType ArrayName [number of element in the array]
Example: int a[5]; - ‘int’ is the data type.
- ‘a’ is the array name.
- 5 is number of elements or size.
int a[5] means a[0], a[1], a[2], a[3], a[4] or
int Int int int int
a[0] a[1] a[2] a[3] a[4]
- 0, 1, 2, 3, 4 are called subscript which is used to define an array element position and is called
Dimension.
- Array index in java starts from 0 to n-1 if the size of array is n.
An individual element of an array is identified by its own unique index (or subscript).
NOTE: The elements field within brackets [], which represents the number of elements the array is going to
hold, must be a constant value.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 25
Arrays of variables of type “class” are known as "Array of objects". The "identifier" used to refer the array
of objects is a user defined data type.
Self-Check -6 Written Test
Directions: Answer all the questions listed below. Use the Answer sheet provided in the next
page:(2 pts each)
1. Which of these distinctions of modular programs over non modular are true?
a) They are not that easier to understand and explain
b) They are not easier to document
c) They are easier to change
d) Testing and Debugging is complex comparatively
2. Which of these comes under the Modularity principle?
a) Small modules b) Coupling c) Cohesion d) All of the mentioned
3. An array Index starts with.?
a) -1 b) 0 c) 1 d) 2
4. Objects in a sequence that have the same type, is called
a). Arrays b). Operators c). Functions d). Stacks
5. Choose one of the best option from the following Position number contained within a
square brackets e.g. my_array [5], is referred as ____?
a) Sub-scripts b) Post-scripts c) Elements of an array d) None of them
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 26
LO2. Apply basic OOP principles in the target language
2.1 Object Oriented Programming in java
Java is an object oriented language because it provides the features to implement an object oriented model.
Java is an object-oriented programming language. The core concept of the object-oriented approach is to
break complex problems into smaller objects.
It is used to implement real-world entities like inheritance, polymorphism, abstraction; etc in the program to
makes the program resusable, efficient, and easy-to-use.
An object is any entity that has a state and behavior. For example, a bicycle is an object. It has
States: idle, first gear, etc
Behaviors: braking, accelerating, etc.
Before we learn about objects, let's first know about classes in Java.
2.2 Introduction to Java Class
A class can be considered as a blueprint using which you can create as many objects as you like. For
example, here we have a class Website that has two data members (also known as fields, instance variables
and object states). This is just a blueprint, it does not represent any website, however using this we can create
Website objects (or instances) that represents the websites. We have created two objects, while creating
objects we provided separate properties to the objects using constructor.
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors,
windows, etc. Based on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a class.
OOPS is about developing an application around its data, i.e. objects which provides the access to their
properties and the possible operations in their own way.
A class in java is an encapsulation of data members and functions that manipulate the data.
In terms of variables, a class would be the type, and an object would be the variable.
2.2.1 Classesand Objects
A class is a type, and an object of this class is just a variable.
Before we can use an object, it must be created.
Classes are generally declared using the keyword class.
Syntax
Acces modifier class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of the object respectively.
Fields are used to store data
Methods are used to perform some operations
Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this
class. The body of the declaration can contain members that can be either data or function declarations, or
optionally access modifier.
These modifier modify the access:
 Public: Access to all code in the program.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 27
public members are accessible from anywhere where the object is visible.
 Private: Access to only members of the same class
 Protected: Access to members of same class and its derived classes
For example our bicycle object, we can create the class as
Example:
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
In the above example, we have created a class named Bicycle. It contains a field named gear and a method
named braking ().
Here, Bicycle is a prototype. Now, we can create any number of bicycles using the prototype. And, all the
bicycles will share the fields and methods of the prototype.
Note: We have used keywords private and public. These are known as access modifiers.
Variables in Java
 Types of Variables in Java
There are three types of variables in Java.
1) Local variable
2) Static (or class) variable
3) Instance variable
Static (or class) Variable
Static variables are also known as class variable because they are associated with the class and common for all the
instances of class. For example, If I create three objects of a class and access this static variable, it would be
common for all, the changes made to the variable using one of the object would reflect when you access it through
other objects.
Example of static variable
public class StaticVarExample {
public static String myClassVar="class or static variable";
public static void main(String args[]){
StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();
//All three will display "class or static variable"
System.out.println(obj.myClassVar);
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 28
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
//changing the value of static variable using obj2
obj2.myClassVar = "Changed Text";
//All three will display "Changed Text"
System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar); }}
Output:
class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text
As you can see all three statements displayed the same output irrespective of the instance through which it is being
accessed. That’s is why we can access the static variables without using the objects like this:
System.out.println(myClassVar); Do note that only static variables can be accessed like this. This doesn’t apply for
instance and local variables.
Instance variable
Each instance(objects) of class has its own copy of instance variable. Unlike static variable, instance variables have
their own separate copy of instance variable. We have changed the instance variable value using object obj2 in the
following program and when we displayed the variable using all three objects, only the obj2 value got changed,
others remain unchanged. This shows that they have their own copy of instance variable.
Example of Instance variable
public class InstanceVarExample {
String myInstanceVar="instance variable";
public static void main(String args[]){
InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();
System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
obj2.myInstanceVar = "Changed Text";
System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar); }}
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 29
Output:
instance variable
Instance variable
instance variable
instance variable
Changed Text
instance variable
Local Variable
These variables are declared inside method of the class. Their scope is limited to the method which means that You
can’t change their values and access them outside of the method.
In this example, I have declared the instance variable with the same name as local variable, this is to demonstrate the
scope of local variables.
Example of Local variable
public class VariableExample {
// instance variable
public String myVar="instance variable";
public void myMethod(){
// local variable
String myVar = "Inside Method";
System.out.println(myVar); }
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();
/* We are calling the method, that changes the
* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself. */
System.out.println("Calling Method"); obj.myMethod();
System.out.println(obj.myVar); }}
Output:
Calling Method
Inside Method
instance variable
Java Constructor
Constructorlooks like a method but it is in fact not a method. It’s name is same as class name and it does
not return any value. You must have seen this statement in almost all the programs I have shared above:
MyClass obj = new MyClass();
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 30
If you look at the right side of this statement, we are calling the default constructor of class myClass to create
a new object (or instance).
We can also have parameters in the constructor, such constructors are known as parametrized constructors.
To understand the working of constructor, lets take an example. lets say we have a class MyClass.
When we create the object of MyClass like this:
MyClass obj = new MyClass() The new keyword here creates the object of class MyClass and invokes the
constructor to initialize this newly created object.
 Types of Constructors
There are three types of constructors:
Default, No-arg constructor and Parameterized.
Default constructor
• If you do not implement any constructor in your class, Java compiler inserts a default constructor into
your code on your behalf. This constructor is known as default constructor.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 31
• You would not find it in your source code(the java file) as it would be inserted into the code during
compilation and exists in .class file.
• This process is shown in the diagram below:
If you implement any constructor then you no longer receive a default constructor from Java compiler.
no-arg constructor:
Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the constructor is
empty.
Although you may see some people claim that that default and no-arg constructor is same but in fact they are
not, even if you write public Demo() { } in your class Demo it cannot be called default constructor since you
have written the code of it.
Example: no-arg constructor
class Demo{
public Demo() {
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo(); }}
Output:
This is a no argument constructor
Parameterized constructor
Constructor with arguments(or you can say parameters) is known as Parameterized constructor
Example: parameterized constructor
In this example we have a parameterized constructor with two parameters id and name. While creating the
objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after creation of obj1
and obj2.
public class Employee {
int empId;
String empName;
//parameterized constructor with two parameters
Employee(int id, String name){
this.empId = id;
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 32
this.empName = name; }
void info(){
System.out.println("Id: "+empId+" Name: "+empName); }
 Java method
A Java method is a collection of statements that are grouped together to perform an operation. When you call
the System.out.println() method, for example, the system actually executes several statements in order to
display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method with or
without parameters, and apply method abstraction in the program design.
A method is a block of code that performs a specific task.
Suppose you need to create a program to create a circle and color it. You can create two methods to solve
this problem:
a method to draw the circle
a method to color the circle
Dividing a complex problem into smaller chunks makes your program easy to understand and reusable.
In Java, there are two types of methods:
User-defined Methods: We can create our own method based on our requirements.
Standard Library Methods: These are built-in methods in Java that are available to use.
Let's first learn about user-defined methods.
Declaring a Java Method
The syntax to declare a method is:
returnType methodName()
{ // method body }
Here,
returnType - It specifies what type of value a method returns For example if a method has an
int return type then it returns an integer value.
If the method does not return a value, its return type is void.
methodName - It is an identifier that is used to refer to the particular method in a program.
method body - It includes the programming statements that are used to perform some tasks. The method
body is enclosed inside the curly braces { }.
For example,
int addNumbers()
{ // code }
In the above example, the name of the method is adddNumbers(). And, the return type is int. We will learn
more about return types later in this tutorial.
This is the simple syntax of declaring a method. However, the complete syntax of declaring a method is
modifie returnType nameOfMethod (parameter1, parameter2, ...) {
// method body
}
Here,
modifier - It defines access types whether the method is public, private, and so on. To learn more, visit Java
Access Specifier.
static - If we use the static keyword, it can be accessed without creating objects.
For example, the sqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt()
without creating an instance of Math class.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 33
parameter1/parameter2 - These are values passed to a method. We can pass any number of arguments to a
method.
Calling a Method in Java
In the above example, we have declared a method named addNumbers(). Now, to use the method, we need to
call it.
Here's is how we can call the addNumbers() method.
// calls the method addNumbers();
Example 1: Java Methods
class Main {
// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value return sum;
}
public static void main(String[] args) {
int num1 = 25; int num2 = 15;
// create an object of Main
Main obj = new Main();
// calling method
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result); } }
Output
Sum is: 40
Java Method Return Type
A Java method may or may not return a value to the function call. We use the return statement to return any
value. For example,
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 34
int addNumbers()
{ ... return sum; }
Here, we are returning the variable sum. Since the return type of the function is int. The sum variable should
be of int type. Otherwise, it will generate an error.
Example 2: Method Return Type
class Main {
// create a method
public static int square(int num) {
// return statement
return num * num; }
public static void main(String[] args) {
int result;
// call the method
// store returned value to result
result = square(10);
System.out.println("Squared value of 10 is: " + result); } }
Output:
Squared value of 10 is: 100
In the above program, we have created a method named square(). The method takes a number as its
parameter and returns the square of the number.
Here, we have mentioned the return type of the method as int. Hence, the method should always return an
integer value.
public void square(int a) {
int square = a * a;
System.out.println("Square is: " + square ); }
Method Parameters in Java
A method parameter is a value accepted by the method. As mentioned earlier, a method can also have
any number of parameters. For example,
// method with two parameters
int addNumbers(int a, int b) {
// code }
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 35
// method with no parameter
int addNumbers(){
// code }
If a method is created with parameters, we need to pass the corresponding values while calling the method.
For example,
// calling the method with two parameters addNumbers(25, 15);
// calling the method with no parameters addNumbers()
Example 3: Method Parameters
class Main {
// method with no parameter
public void display1() {
System.out.println("Method without parameter");
}
// method with single parameter
public void display2(int a) { System.out.println("Method with a single parameter: " + a);
}
public static void main(String[] args) {
// create an object of Main
Main obj = new Main();
// calling method with no parameter obj.display1();
// calling method with the single parameter obj.display2(24); } }
Output
Method with parameter Method with a single parameter: 24
Standard Library Methods
The standard library methods are built-in methods in Java that are readily available for use.
These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with
JVM and JRE.
For example,
print() is a method of java.io.PrintSteam. The print("...") method prints the string inside quotation marks.
sqrt() is a method of Math class. It returns the square root of a number.
Here's a working example:
Example 4: Java Standard Library Method
public class Main {
public static void main(String[] args) {
// using the sqrt() method System.out.print("Square root of 4 is: " + Math.sqrt(4)); } }
Output:
Square root of 4 is: 2.0
Output
Method with parameter Method with a single parameter: 24
 ModelClasses andObjects real-life beings to software entities
Let's take an example of developing a pet management system, specially meant for dogs.
You will need various information about the dogs like different breeds of the dogs, the age, size, etc.
You need to model real-life beings, i.e., dogs into software entities
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 36
Moreover, the million dollar question is, how you design such software?
Here is the solution-First, let's do an exercise.
You can see the picture of three different breeds of dogs below.
Stop here right now! List down the differences between them.
Some of the differences you might have listed out maybe breed, age, size, color, etc.
If you think for a minute, these differences are also some common characteristics shared by these
dogs.
These characteristics (breed, age, size, color) can form a data members for your object.
common characteristics
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 37
common behaviors of these dogs
Next, list out the common behaviors of these dogs like sleep, sit, eat, etc.
So these will be the actions of our software objects.
So far we have defined following things,
 Class – Dogs
 Data members or objects- size, age, color, breed, etc.
 Methods- eat, sleep, sit and run.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 38
Now, for different values of data members (breed size, age, and color) in Java class, you will get
different dog objects.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 39
Know you can design program using oop approach
You can design any program using this OOPs approach.
While creating a class, one must follow the following principles.
• // Class Declaration
• public class Dog {
• // Instance Variables
• String breed;
• String size;
• int age;
• String color;
• // method 1
• public String getInfo() {
• return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color);
• }
• public static void main(String[] args) {
• Dog maltese = new Dog();
• maltese.breed="Maltese";
• maltese.size="Small";
• maltese.age=2;
• maltese.color="white";
• System.out.println(maltese.getInfo());
• }
• }
• Out put: Breed is: Maltese Size is:Small Age is:2 color is: white
 Types of method
Static Methods
Static methods are methods in java that can be called without actually creating an object of that class.
By declaring a method using the static keyword, you can call it without first creating an object because it
becomes part of the class or a class method(a method that belongs to a class rather than to an object).
They are designed with aim to be shared with all objects created with that class.
One reason why you might want to use a static method is when you want a common operation to be
performed through out the class.
Static methods cannot be overridden.
Syntax:
Static keyword followed by return type, followed by method name.
static return_type method_name();
EXAMPLE:
class Car{
static void display(){
System.out.println(“this is my favorite car”);
}
public static void main(String[], args){
.display();
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 40
}
}
Instance Methods
Instance methods are methods that require an object of its class to be created before it can be called.
Instance methods belong to object of the class and not the class. Every object individual object created from
the class has its own copy of the instance methods of that class.
They can be overridden.
class JavaExample{
static int i = 100;
static String s = “sawla";
//Static method
static void display() {
System.out.println("i:"+i);
System.out.println("i:"+s); }
//non-static method
void funcn() {
//Static method called in non-static method
display(); }
//static method
public static void main(String args[]) {
JavaExample obj = new JavaExample();
//You need to have object to call this non-static method
obj.funcn();
//Static method called in another static method
display(); }}
2.3 Object constructionin Java class
 Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class
then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as objects of the class.
Here is how we can create an object of a class.
className object = new className();
// for Bicycle class
Bicycle sportsBicycle = new Bicycle();
Bicycle touringBicycle = new Bicycle();
We have used the new keyword along with the constructor of the class to create an object. Constructors are
similar to methods and have the same name as the class. For example, Bicycle() is the constructor of
the Bicycle class.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 41
Here, sportsBicycle and touringBicycle are the names of objects. We can use them to access fields and
methods of the class.
As you can see, we have created two objects of the class. We can create multiple objects of a single class in
Java.
Note: Fields and methods of a class are also called members of the class.
Self-Check -5 Written Test
Directions: Answer all the questions listed below. Use the Answer sheet provided in the next
page:(2 pts each)
1. Properties are implemented using ___ in Java.
a) Methods b) Variables c) Interfaces d) All the above
2. Which is the file extension used for a public Java class source code?
a) .j b) .class c) .java d) None
3. After compilation, ajava -Class is kept in a ___ file in Java programming.
a) .java b) .cls c) .class d) .interface
4. In Java, the keyword used to declare a class is ___.
a) Class b) Java c) class d) java
5. A Java class can contain___.
a) Variables b) Methods, Constructors c) Inner Classes d) All the above
6. Creating an object from a class is also called ____.
a) Initializing b) Instantiating c) Interfacing d) None of the above
7. The keyword used to create a new object in Java is ___.
a) class b) java c) new d) create
8. Choose the correct statements about choosing a name for a class in Java.
a) The class name can start with only a letter or underscore or dollar sign.
b) The class name can contain numbers
c) The class name can not start with a number
d) All the above
9. An object is created at __ time in Java.
a) Compile-time b) Run time c) Assembling time d) None of the above
10. A Java constructor is like a method without ___.
a) statements b) return type c) argument list d) None
11. The name of a constructor and the name of a class are ___.
a) Same as with class name b) Different with class name c) a&b
12. All Java methods must have a return type. (TRUE / FALSE)
a) true b) false
13. Java method signature is a combination of ___.
a) Return type b) Method name c) Argument List d) All the above
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 42
2.4 Object Oriented Programming features in java
These features include inheritance, polymorphism, encapsulation and Abstraction .
These four features are the main OOPs Concepts that you must learn to understand the Object Oriented
Programming in Java
Inheritance
The process by which one class acquires the properties and functionalities of another class is
called inheritance. Inheritance provides the idea of reusability of code and each sub class defines only those
features that are unique to it, rest of the features can be inherited from the parent class.
Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods.
Inheritance allows us to reuse of code, it improves reusability in your java application.
The parent class is called the base class or super class. The child class that extends the base class is called
the derived class or sub class or child class.
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class A is child class and class B is parent class.
class A extends B
{
}
Inheritance Example
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 43
In this example, we have a parent class Teacher and a child class MathTeacher. In the MathTeacher class we
need not to write the same code which is already present in the present class. Here we have college name,
sawla and does() method that is common for all the teachers, thus MathTeacher class does not need to write
this code, the common data members and methods can inherited from the Teacher class.
class Teacher {
String designation = "Teacher";
String college = “sawla";
void does(){
System.out.println("Teaching");
}
}
public class MathTeacher extends Teacher{
String mainSubject = "Maths";
public static void main(String args[]){
MathTeacher obj = new MathTeacher();
System.out.println(obj.college);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
• Output:
• sawla
• Teacher
• Maths
• Teaching
Forms/types of Inheritance:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
1. Single inheritance: - If a class is derived from a single base class, it is called as single inheritance.
In Single Inheritance, there is only one Super Class and Only one Sub Class Means they have one to one
Communication between them.
2. Multiple Inheritances: - If a class is derived from more than one base class, it is known as multiple
inheritances.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 44
3. Multilevel Inheritance:
When a derived class is created from another derived class, then that inheritance is called as multi level
inheritance.
4. HierarchicalInheritance:
If a number of classes are derived from a single base class, it is called as hierarchical inheritance.
This means a Base Class will have Many Sub Classes or a Base Class will be inherited by many Sub
Classes.
5. Hybrid Inheritance: This is a Mixture of two or More Inheritance types.
I.e.: Any combination of single, hierarchical and multi-level inheritances is called as hybrid
inheritance.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 45
 Polymorphism in Java
The process of representing one form in multiple forms is known as Polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
Real life example of polymorphism in Java
Suppose if you are in class room that time you behave like a student, when you are in market at that time you
behave like a customer, when you at your home at that time you behave like a son or daughter, Here one
person present in different-different behaviors.
How to achieve Polymorphism in Java ?
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 46
In java programming the Polymorphism principal is implemented with method overriding concept of java.
Polymorphism principal is divided into two sub principal they are:
Static or Compile time polymorphism
Dynamic or Runtime polymorphism
Static Polymorphism:
Polymorphism that is resolved during compiler time is known as static polymorphism. Method overloading
can be considered as static polymorphism example.
Method Overloading: This allows us to have more than one methods with same name in a class that differs in
signature.
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
public class ExampleOverloading
{
public static void main(String args[])
{
DisplayOverloading obj= newDisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
Dynamic Polymorphism
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an overridden
method is resolved at runtime rather, thats why it is called runtime polymorphism.
Example
class Animal{
public void animalSound(){
System.out.println("Default Sound");
}
public class Dog extends Animal{
public void animalSound(){
System.out.println("Woof");
}
public class Dog extends Animal{
public void animalSound(){
System.out.println("Woof");
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 47
}
public static void main(String args[]){
Animal obj = newDog();
obj.animalSound();
}
}
Output:
• Woof
Since both the classes, child class and parent class have the same method animalSound. Which of the method will be
called is determined at runtime by JVM.
 Abstraction
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a process where you show only
“relevant” data and “hide” unnecessary details of an object from the user.
The abstract keyword is a non-access modifier, used for classes and methods:
• Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).
• Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided
by the subclass (inherited from).
• Syntax Abstract Class
• abstract class A{
• abstract void myMethod();
• void anotherMethod(){
• //Does something
• }
• }
Note 1: There can be some scenarios where it is difficult to implement all the methods in the base class. In such
scenarios one can define the base class as an abstract class which signifies that this base class is a special kind of
class which is not complete on its own.
A class derived from the abstract base class must implement those methods that are not implemented (means they
are abstract) in the abstract class.
Abstract class cannot be instantiated which means you cannot create the object of abstract class. To use this class,
you need to create another class that extends this abstract class provides the implementation of abstract methods,
then you can use the object of that child class to call non-abstract parent class methods as well as implemented
methods(those that were abstract in parent but implemented in child class).
If a child does not implement all the abstract methods of parent class(the abstract class), then the child class must
need to be declared abstract.
Example of Abstract class and Methods
Here we have an abstract class Animal that has an abstract method animalSound(), since the animal sound differs
from one animal to another, there is no point in giving the implementation to this method as every child class must
override this method to give its own implementation details. That’s why we made it abstract.
• //abstract class
• abstract class Animal{
• //abstract method
• public abstract void animalSound();
• }
• public class Dog extends Animal{
•
• public void animalSound(){
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 48
• System.out.println("Woof");
• }
• public static void main(String args[]){
• Animal obj = new Dog();
• obj.animalSound();
• }
• }
• Output:
• Woof
 Encapsulation
Encapsulation is the method of combining the data and functions inside a class. This hides the data from being
accessed from outside a class directly, only through the Methods inside the class is able to access the information.
Encapsulation is the term given to the process of hiding all the details of an object that do not necessary to its user.
Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.
Features and Advantages of the concept of Encapsulation:
- Makes Maintenance of Application Easier
- Improves the Understandability of the Application
- Enhanced Security
- Protection of data from accidental corruption
- Flexibility and extensibility of the code and reduction in complexity
Encapsulation example in Java
How to
1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can
only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
 class EmployeeCount
 {
 private int numOfEmployees = 0;
 public void setNoOfEmployees (int count)
 {
 numOfEmployees = count;
 }
 public double getNoOfEmployees ()
 {
 return numOfEmployees;
 }
 }
 public class EncapsulationExample
 {
 public static void main(String args[])
 {
 EmployeeCount obj = new EmployeeCount ();
 obj.setNoOfEmployees(5613);
 System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 49
 }
 }
 Output:
 No Of Employees: 5613
The class EncapsulationExample that is using the Object of class EmployeeCount will not able to get the
NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value.
The class EncapsulationExample that is using the Object of class EmployeeCount will not able to get the
NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value.
So what is the benefit of encapsulation in java programming
Well, at some point of time, if you want to change the implementation details of the class EmployeeCount, you can
freely do so without affecting the classes that are using it.
Introduction to Exception Handling
An exception is a special condition that changes the normal flow of program execution.
Exceptional conditions are things that occur in a system that are not expected or are not a part of normal system
operation. When the system handles these exceptional conditions improperly, it can lead to failures and system
crashes.
Exception handling is the method of building a system to detect and recover from exceptional conditions.
Exceptional conditions are any unexpected occurrences that are not accounted for in a system's normal operation.
Some examples of exceptional conditions:
- incorrect inputs from the user
- bit level memory or data corruption
If these exceptional conditions are not properly caught and handled, they can cause an error or failure in the system.
An exception is a problem that arises during the execution of a program. A Java exception is a response to an
exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. Java exception handling is built
upon three keywords: try, catch, and throw.
 throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
 catch: A program catches an exception with an exception handler at the place in a program where you want
to handle the problem. The catch keyword indicates the catching of an exception.
 try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by
one or more catch blocks
Basic syntax:
try{
}
catch(Exception e){
}
Example:
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
System.out.println(a/i);
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 50
}catch(ArithmeticException e){
System.out.println(e);
}
}
}
Output:
3
5
10
java.lang.ArithmeticException: / by zero
try block contains the code that might throw an exception. Don’t write anything extra in try as statements after the
exception will not get executed if the exception occurred. Try must be immediately followed by catch or finally
block.
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
System.out.println(a/i);
}
}
}
Compile time error:
prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations
try{
^
1 error
The catch block is used to catch the exception thrown by statements in the try block. The catch must follow try else
it will give a compile-time error.
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
System.out.println(a/i);
}
System.out.println("between try and catch");
catch(ArithmeticException e){
System.out.println(e);
}
}
}
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 51
Compile Time Error:
prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations
try{
^
prog.java:9: error: 'catch' without 'try'
catch(ArithmeticException e){
^
2 errors
Things to Remember
Do not keep any code after the statement which is prone to exception. Because if an exception occurred then it will
straight away jump to the catch or finally block, ignoring all other statements in the try block.
class Main {
public static void main (String[] args) {
try
{
System.out.println(4/0);
//will not get printed
System.out.println("end of try!");
}
catch(ArithmeticException e)
{
System.out.println("divide by 0");
}
}
}
Output:
divide by 0
While catching the exception in the catch block, either you can have directly the class of exception or its superclass.
Example: Exact Exception
class Main {
public static void main (String[] args) {
try{
System.out.println(4/0);
}
//ArithmeticException
catch(ArithmeticException e){
System.out.println("divide by 0");
}
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 52
}
}
Output:
divide by 0
 Java GUI Programming
One of the big advances that Java made when it was introduced in 1995 was the inclusion of standardized "graphical
user interface" ("GUI") libraries. This was a tremendous leap forward over the bewildering array of incompatible
third-party libraries that were the only avenues previously open to GUI developers. The Java GUI library was also
one of the first major software packages to explicitly describe its architecture in terms of the then-brand-new
language of Design Patterns.
GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java applications. It is
mainly made of graphical components like buttons, labels, windows, etc. through which the user can interact with an
application. GUI plays an important role to build easy interfaces for Java applications.
Main Packages
One confusing aspect of the Java GUI system however is a legacy issue where the system underwent a large-scale
upgrade in 1997, so some of the classes involved are spread over the (relatively) older java.awt packages and
the newer javax.swing packages. In general, if the class name starts with "J", then it is in the Swing package.
Since some functionality appears to be duplicated in the Swing packages, such as frames and buttons, always use the
Swing component over the older AWT components when there is a choice.
 java.awt -- Contains the main super classes for the GUI components plus a number of
utility type classes, such as Color and Point.
 java.awt.event -- Contains the classes and interfaces for managing events from the
GUI components, e.g. button clicks and mouse movements.
 javax.swing -- Contains most of the visible GUI components that are used such as
buttons, text fields, frames and panels.
Class Hierarchy
Java uses the Composite Design Pattern to create GUI components that can also serve as containers to hold
more GUI components. Here is a UML diagram showing the class relations between a few of the more
commonly used GUI components:
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 53
Above, the commonly used container components are in orange while the non-container components are in blue.
Note that technically, all javax.swing components are capable of holding other Components, but in practice,
only JFrame, JApplet, and JPanel, plus a few not shown above (JSplitPane, JTabbedPane and JScrollPane) are
commonly used for that purpose.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 54
Commonly Used Classes
 Simple Components
javax.swing.JLabel -- A piece of non-editable text on the screen.
javax.swing.JButton -- A button that can be clicked. Clicking the button will cause
its actionPerformed event to be fired which will call all
installed ActionListener's actionPerformed methods.
javax.swing.JTextField -- A single line of user-editable text.
javax.swing.JTextArea -- A box with multiple lines of text displayed. Can be set for editable or non-
editable.
javax.swing.JRadioButton, javax.swing.JCheckBox -- Small round or square boxes that can be
clicked on to indicate the selection of something, such as an option of some sort. Clicking the radio button or check
box will fire a particular type of event. Radio buttons can be grouped together using an invisible (to the user) class
called javax.swing.ButtonGroup to create a set where only one button can be set at a time.
javax.swing.JComboBox -- A drop-list of items. A JComboBox holds a set of Objects, not
just Strings. The displayed texts are the return values of the item's toString() method. Thus
a JComboBox can be used to hold arbitrary entities without the GUI knowing what those entities are. Events are
fired only when the selected item changes, though the currently selected item and its index can always be retrieved.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 55
 Container Components
javax.swing.JFrame -- a stand-alone "window" or "frame" with a title and the usual abilities to be moved, resized,
minimized, maximized and closed. For most people, this is the top-level container in their system. Thus
a JFrame cannot hold another JFrame. While a JFrame can hold any type of component, typically,
a JFrame holds JPanels, which are arranged to group together sets of the components used in the window (frame).
The default layout manager of a JFrame is the BorderLayout. A JFrame has a couple of unique and important
methods that are worth pointing out:
 void getContentPane().add(Component c) -- adds a component to the frame. Note that
a JFrame acts slightly differently than a JPanel here because JFrames have a little-used feature of
multiple layers (panes) of components that can be quickly switched in and out of visibility. There are
overridden forms of this method inherited from java.awt.Container that allow parameters for the
layout manager to be passed along, such as specifying the component's position in a BorderLayout.
 void setDefaultCloseOperation(int option) -- sets the behavior of the frame when it is
closed. See the web page on Setting the Behavior When Closing a JFrame.
javax.swing.JApplet -- Allows a Java program to be run as a component in a web page. Note that an applet and a
frame are not the same thing and are not interchangeable, though there are some work-arounds for that which allow
the same code to run as either a stand-alone application or an applet in a web page.
javax.swing.JPanel -- The basic building block for laying components out in a frame or inside of other
panels. A JAva GUI consists of a frame with panels holding panels holding panels, etc. Note that "panels" here
could also be scroll panes, split panes and/or tabbed panes (see below). The default layout manager for
a JPanel is the FlowLayout.
javax.swing.JScrollPane -- Allows you to display a single panel with scroll bars on the sides, allowing
more or larger components to be displayed than will fit on the screen.
javax.swing.JSplitPane -- Allows two panels to be displayed with either a vertical or horizonatal, user-
moveable bar separating them.
javax.swing.JTabbedPane -- Allows multiple panels to be displayed in a "tabbed" format.
Commonly Used Methods in GUI Containers
void add(Component c) -- adds another component to the container to be laid out as per the currently
installed layout manager. There are overridden forms of this method inherited from java.awt.Container that
allow parameters for the layout manager to be passed along, such as specifying the component's position in
a BorderLayout.
void setLayout(LayoutManager lm) -- installs a new layout manager into the container.
Utility Classes
java.awt.Graphics --This abstract class is rarely instantiated by the developer's code. A machine-
dependent instance of this class is handed to the paintComponent method of a visible GUI component during
the screen painting process -- it is NOT instantiated by the developer's code but rather by the Java GUI sub-
system.
The developer can writed code that will use that supplied Graphics object instance to draw lines, shapes and images
onto the screen. For advanced graphics work, it should be noted that the supplied Graphics object can always be
safely downcast to the more capable java.awt.Graphcs2D class.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 56
NEVER CALL paintComponent DIRECTLY FROM YOUR OWN CODE. Likewise, NEVER
INSTANTIATE A Graphics OBJECT--the Java GUI system will automatically hand your code
the Graphics object that it needs.
java.awt.Color -- Represents a color. Has static fields predefined to common colors plus can be expressed in
a number of different formats, such as 3-bit RGB values.
java.awt.Point -- Represents an point on 2-dimensional plane as specified by integer-valued Cartesian
coordinates.. Has fields to retrieve the x and y coordinates plus methods for operations such as calculating the
distance between two points. For floating point-valued Cartesian coordinates, use
the java.awt.geom.Point2D class.
Layout Managers
Java containers use the Strategy Design Pattern to implement automatic layout management of GUI components
on the screen. The management of the size and positions of the contained components is delegated to a "layout
manager", which can be set at design time or dynamically changed. Here are a couple of common layouts:
java.awt.BorderLayout -- Separates the component into 5 distinct areas, 4 non-resizeable areas on the
edges ("North", "East", "South", and "West") and one re-sizeable area in the center ("Center"). Each
area can only contain 1 component, so typically, panels are used in each area to hold multiple components.
A typical statement that adds a component to a container that is known to have a BorderLayout installed would
be
myContainer.add(myComponent, BorderLayout.NORTH);
java.awt.FlowLayout -- Holds multiple components in a horizontally arranged line that will wrap around if
the width of the container is too small. A FlowLayout does not require any additional parameters when a
component is added to the container -- the components will display left-to-right in the order in which they were
added.
javax.swing.BoxLayout -- Holds components in either a vertical or horizontal arrangement that is fixed,
independent of the size of container. The width and height of the contained components are all identical and are
automatically set tocompletely fill the container.
Event Handling in Java GUIs
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 57
Java uses the Observer-Observable Design Pattern to handle events from GUI components, e.g. button clicks and
mouse movements. Components supply methods to add various types of listeners, e.g. "void
addActionListener(ActionListener al)" and "void
addMouseMotionListener(MouseMotionListener mml)". Multiple listeners can be added and all will
be called when the associated event occurs, though there is no guarantee as to the order in which the installed
listeners will be called.
java.awt.event.ActionListener -- Interface used to detect a simple action on a component, such as clicking a button
or hitting Enter on a text field.
java.awt.event.MouseListener -- Interface used for event listeners watching for mouse click events. This event
allows more detailed capture of the mouse click than an ActionListener event, for instance, distinguishing between a
mouse button pressed vs. a mouse button released events. A convenience class, MouseAdapter, is also available
that no-ops all the methods, freeing the developer to only write the code that overrides the desired methods.
java.awt.event.MouseMotionListener -- Interface used for event listeners watching for mouse motion events, e.g.
dragging. A convenience class, MouseMotionAdapter, is also available that no-ops all the methods, freeing the
developer to only write the code that overrides the desired methods.
How to start a GUI-based program
In general, a GUI-based program will start whenever the first GUI component is shown (visibility set to true).
Typically that would be one of the frames in the system, so one would have a line of code like such:
myFrame.setVisible(true);
This a quickie starts for a GUI program would have a main method like such:
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
(new MyFrameClass("The title")).setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
(Note: The above code correctly instantiates the frame on the GUI thread as specified by the official Java
requirements. The code can be simplified a little bit by using a lambda function instead of the anonymous inner
class implemenation of a Runnable.)
In Model-View-Controller architectures however, it is not recommended that the view, i.e. the main frame, be
started by simply setting its visibility to true. It is much better to define a "start()" method on the frame or
main view class, where all final initializations and checks are performed and whose last line of code is
the setVisible(true) statement.
Sawla Polytechnic College ICT Database Administration Level IV
Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 58
A typical controller in an MVC wills instantiate the model and the view, connecting them together with their
respective adapters. After all that is done, the controller's last act will be to call the view's start method.
NEVER START THE GUI FROM THE CONSTRUCTOR OF THE FRAME! This is simply asking for
trouble as many of the other components in the system are probably not fulling instantiated or intialized yet. But as
soon as the first frame becomes visible, events will start firing, and those listeners will expect fully operational
objects to be present but won't find them, causing, at best, a flurry of null pointer errors.
 Java GUI Example
Now in this Swing Java Tutorial, let's understand GUI with Java Swing examples.
Example: To learn Java GUI programming in this Java GUI tutorial
Step 1) Copy the following code into a text editor like notepad
import javax.swing.*;
class SPTC{
public static void main(String args[]){
JFrame frame = new JFrame("Sawla Polytechnic college");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("SPTC_BUTTON");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
}}
Step 2) Save, Compile, and Run the code using javac and java commands in to cmd.
Step 3) now let's Add a Button to our frame. Copy following code into an editor from given Java GUI Example
import javax.swing.*;
class SPTC{
public static void main(String args[]){
JFrame frame = new JFrame("Sawla Polytechnic college");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("SPTC_BUTTON");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
}}
Step 4) Execute the code. You will get a big button
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc
ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc

More Related Content

Similar to ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc

La5 ict-topic-5-programming
La5 ict-topic-5-programmingLa5 ict-topic-5-programming
La5 ict-topic-5-programmingKak Yong
 
Grade 8: Introduction To Java
Grade 8: Introduction To JavaGrade 8: Introduction To Java
Grade 8: Introduction To Javanandanrocker
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Md. Imran Hossain Showrov
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programmingGwyneth Calica
 
Trend of Visual Programming Language
Trend of Visual Programming LanguageTrend of Visual Programming Language
Trend of Visual Programming LanguageTeddy Marcus
 
La 5 Programming1
La 5   Programming1La 5   Programming1
La 5 Programming1Cma Mohd
 
La5 ict-topic-5-programming
La5 ict-topic-5-programmingLa5 ict-topic-5-programming
La5 ict-topic-5-programmingAzmiah Mahmud
 
Ppt about programming in methodology
Ppt about programming in methodology Ppt about programming in methodology
Ppt about programming in methodology Vaishnavirakshe2
 
Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)Chao-Lung Yang
 
Procedural Programming Of Programming Languages
Procedural Programming Of Programming LanguagesProcedural Programming Of Programming Languages
Procedural Programming Of Programming LanguagesTammy Moncrief
 
The Concept Of Abstract Data Types
The Concept Of Abstract Data TypesThe Concept Of Abstract Data Types
The Concept Of Abstract Data TypesKaty Allen
 

Similar to ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc (20)

La5 ict-topic-5-programming
La5 ict-topic-5-programmingLa5 ict-topic-5-programming
La5 ict-topic-5-programming
 
Grade 8: Introduction To Java
Grade 8: Introduction To JavaGrade 8: Introduction To Java
Grade 8: Introduction To Java
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Trend of Visual Programming Language
Trend of Visual Programming LanguageTrend of Visual Programming Language
Trend of Visual Programming Language
 
La 5 Programming1
La 5   Programming1La 5   Programming1
La 5 Programming1
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Notacd07
Notacd07Notacd07
Notacd07
 
Nota programming
Nota programmingNota programming
Nota programming
 
Programming Part 01
Programming Part 01Programming Part 01
Programming Part 01
 
Notacd071
Notacd071Notacd071
Notacd071
 
Ict topic 5
Ict topic 5Ict topic 5
Ict topic 5
 
La5 programming
La5  programmingLa5  programming
La5 programming
 
La5 ict-topic-5-programming
La5 ict-topic-5-programmingLa5 ict-topic-5-programming
La5 ict-topic-5-programming
 
Ppt about programming in methodology
Ppt about programming in methodology Ppt about programming in methodology
Ppt about programming in methodology
 
Introduction to programing languages part 1
Introduction to programing languages   part 1Introduction to programing languages   part 1
Introduction to programing languages part 1
 
Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)Introduction to Computer Programming (general background)
Introduction to Computer Programming (general background)
 
Procedural Programming Of Programming Languages
Procedural Programming Of Programming LanguagesProcedural Programming Of Programming Languages
Procedural Programming Of Programming Languages
 
The Concept Of Abstract Data Types
The Concept Of Abstract Data TypesThe Concept Of Abstract Data Types
The Concept Of Abstract Data Types
 
Programming
ProgrammingProgramming
Programming
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

ICT-DBA4 -05-0811-Apply-Object-Oriented-Programming-Language-Skills.doc

  • 1. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 1 NOMINAL DURATION: 240hrs
  • 2. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 2 LO1. Apply basic language syntax and layout 1.1 Introduction to Programming Language As we know, to communicate with a person, we need a specific language, similarly to communicate with computers, programmers also need a language is called Programming language. Before learning the programming language, let's understand what is language? What is Language? Language is a mode of communication that is used to share ideas, opinions with each other. For example, if we want to teach someone, we need a language that is understandable by both communicators. 1.1.1 What is a Programming Language? A program is a set of instructions given to a computer to perform a specific operation. or computer is a computational device which is used to process the data under the control of a computer program. A programming language is a computer language that is used by programmers (developers) to communicate with computers. It is a set of instructions written in any specific language ( C, C++, Java, Python) to perform a specific task. A programming language is mainly used to develop desktop applications, websites, and mobile applications.  Types of programming language  Low-level programming language Low-level language is machine-dependent (0s and 1s) programming language. The processor runs low- level programs directly without the need of a compiler or interpreter, so the programs written in low-level language can be run very fast. Low-level language is further divided into two parts – i. Machine Language Machine language is a type of low-level programming language. It is also called as machine code or object code. Machine language is easier to read because it is normally displayed in binary or hexadecimal form (base 16) form. It does not require a translator to convert the programs because computers directly understand the machine language programs. The advantage of machine language is that it helps the programmer to execute the programs faster than the high- level programming language. ii. Assembly Language
  • 3. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 3 Assembly language (ASM) is also a type of low-level programming language that is designed for specific processors. It represents the set of instructions in a symbolic and human-understandable form. It uses an assembler to convert the assembly language to machine language. The advantage of assembly language is that it requires less memory and less execution time to execute a program.  High-level programming language High-level programming language (HLL) is designed for developing user-friendly software programs and websites. This programming language requires a compiler or interpreter to translate the program into machine language (execute the program). The main advantage of a high-level language is that it is easy to read, write, and maintain. High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language. There are several approaches to programming processes in A high-level language. But the two most popular and important ones are object-oriented programming and procedural programming. I. Procedural Oriented programming language Procedural Oriented Programming (POP) language is derived from structured programming and based upon the procedure call concept. It divides a program into small procedures called routines or functions. Procedural Oriented programming language is used by a software programmer to create a program that can be accomplished by using a programming editor like IDE, Adobe Dreamweaver, or Microsoft Visual Studio. The advantage of POP language is that it helps programmers to easily track the program flow and code can be reused in different parts of the program. The advantage of POP language is that it helps programmers to easily track the program flow and code can be reused in different parts of the program. Example: C, FORTRAN, Basic, Pascal, etc. II Object-Oriented Programming language Object-Oriented Programming (OOP) language is based upon the objects. In this programming language, programs are divided into small parts called objects. It is used to implement real-world entities like inheritance, polymorphism, abstraction, etc in the program to makes the program resusable, efficient, and easy-to- use. The main advantage of object-oriented programming is that OOP is faster and easier to execute, maintain, modify, as well as debug. Note: Object-Oriented Programming language follows a bottom-up approach. Example: C++, Java, Python, C#, etc.
  • 4. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 4  Differences between object-oriented and procedural programming The objective of procedural programming is to break down a program into a collection of variables, data structures whereas the main aim of object-oriented programming is to break down a programming task into objects. In simple words, procedural programming uses procedures to operate on data structures, while object-oriented uses objects for the purpose. In both programming paradigms, the nomenclature is different though have similar semantics: Procedural Programming Object-oriented Programming Procedure Method Record Object Module Class Procedure call Message Object-oriented programming? Object-oriented programming combines a group of variables (properties) and functions (methods) into a unit called an "object." These objects are organized into classes where individual objects can be grouped together. OOP can help you consider objects in a program's code and the different actions that could happen in relation to the objects. This programming style widely exists in commonly used programming languages like Java, C++ and PHP. These languages help simplify the structure and organization of software programs. Programmers often use OOP when they need to create complex programs. Self-Check -1 Written Test Directions: Answer all the questions listed below. Use the Answer sheet provided in the next page:(2 pts each) 1. What is program? 2. What is programing language? 3. Define low level and high level programing language? 4. Write The Deference between object oriented and Procedural programing language? 5. Write at least two example of object oriented programing language?
  • 5. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 5 1.2. Understanding Basic language syntax rules and best practices What are the Basic programming languages? Some of the basic programming languages are:  C, C++, JAVA, Visual Studio (Visual basic.Net, C-Sharp(C#), and Visual C++), and so on. Syntax is a rule that specify how valid instructions (constructs) are written. 1.2.1 Introduction to Java programming JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was developed by James Gosling and Patrick Naughton. It is a simple programming language. Writing, compiling and debugging a program is easy in java. It helps to create modular programs and reusable code. • Simple Java is considered as one of simple language because it does not have complex features like Operator overloading, multiple inheritance, pointers and Explicit memory allocation. • Multithreading Java supports multithreading. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU. • Portable The platform independent byte code can be carried to any platform for execution that makes java code portable. Java Virtual Machine (JVM) This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program execution. Phases are as follows: we write the program, then we compile the program and at last we run the program. 1) Writing of the program is of course done by java programmer like you and me. 2) Compilation of program is done by javac compiler, javac is the primary java compiler included in java development kit (JDK). It takes java program as input and generates java bytecode as output. 3) In third phase, JVM executes the bytecode generated by compiler. This is called program run phase. So, now that we understood that the primary function of JVM is to execute the bytecode produced by compiler. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language. Bytecode As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. The bytecode is saved in a .class file by compiler. Java Development Kit(JDK) As the name suggests this is complete java development kit that includes JRE (Java Runtime Environment), compilers and various tools like Java debugger etc. In order to create, compile and run Java program you would need JDK installed on your computer. JVM Vs JRE Vs JDKJRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger. Which means you can run the code in JRE but you can’t develop and compile the code in JRE. JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE. JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc
  • 6. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 6 Java is a platform independent language Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned above, JVM executes the bytecode produced by compiler. This byte code can run on any platform such as Windows, Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux and vice- versa? Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language. JAVA Basic Syntax contains:  Object  Class  Methods  Data type  Return type  Variable
  • 7. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 7 Java - Basic Syntax • When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean. • Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class. • Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports. • Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. • Variable: A variable is the name for a memory location where you store some data. A variable in Java must be declared (the type of variable) and defined (values assigned to a variable) before it can be used in a program. • Data type: A data type defines which kind of data will store in variables and also defines memory storage of data. There are two kinds of data types User defined data types and Standard data types. • Return type: Return type is used to terminate main( ) Method and causes it to return the value to its type. If a Method is defined as having a return type of void, it should not return a value. If a Method is defined as having a return type other than void, it should return a value. Syntax public class FirstJavaProgram { public static void main(String[] args){ System.out.println("This is my first program in java"); }//End of main }//End of FirstJavaProgram Class Every line of code that runs in Java must be inside a class. In our example, we named the class FirstJavaProgram. A class should always start with an uppercase first letter. Note: Java is case-sensitive: " FirstJavaProgram " and " firstJavaprogram " has different meaning. The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename. Let we see each line of code one by public class FirstJavaProgram { This is the first line of our java program. Every java application must have at least one class definition that consists of class keyword followed by class name. When I say keyword, it means that it should not be changed, we should use it as it is. However the class name can be anything. We have made the class public by using public access modifier, we will cover access modifier in a separate post, all you need to know now that a java file can have any number of classes but it can have only one public class and the file name should be same as public class name. The next is main method public static void main(String[] args) { This is our next line in the program, lets break it down to understand it: public: This makes the main method public that means that we can call the method from outside the class. static: We do not need to create object for static methods to run. They can run itself. void: It does not return anything. main: It is the method name. This is the entry point method from which the JVM can run your program.
  • 8. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 8 (String[] args): Used for command line arguments that are passed as strings. We will cover that in a separate post. Next the method System.out.println("This is my first program in java"); This method prints the contents inside the double quotes into the console and inserts a newline after. Note: The curly braces {} marks the beginning and the end of a block of code. Note: Each code statement must end with a semicolon Self-Check -2 Written Test Directions: Answer all the questions listed below. Use the Answer sheet provided in the next page:(2 pts each) 1. Which one of the following is true about java programing language? A. platform independent byte code can be carried to any platform B. Java supports multithreading C. is object oriented programing language D. all 2. The correct phases of java program execution A. Writing of the program execute the bytecode generated by compiler Compile the program by javac compiler B. Writing of the program Compile the program by javac compiler  execute the bytecode generated by compiler C. Compile the program by javac compiler Writing of the program execute the bytecode generated by compiler D. execute the bytecode generated by compiler Writing of the program Compile the program by javac compiler 3. Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU. A. Portable B. not complex C. Multithreading D. platform independent 4. The type of code generated after JDK compiles the java source code and save it into a .class file to be can be executed by JVM. A. Source code B. Byte code C. Machine code D. B&C 5. Which one is true A. In order to create, compile and run Java program you would need JDK installed on your computer. B. Java Development Kit(JDK) includes JRE (Java Runtime Environment), compilers and various tools like Java debugger
  • 9. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 9 C. Java Runtime environment (JRE) contains Java virtual Machine(JVM), class libraries but not compiler and debugger D.All 6. Java - Basic Syntax is A. Accessmodifier Class ClassName{ Public static Void Main(String[] args){ //body }} B. Accessmodifier Class MethodName(){ Public static Void Main(String[] args){ //method }} C. Accessmodifier DataType variableName{ Public static Void Main(String[] args){ //variables }} D. All 7. Which of the following option leads to the portability and security of Java? A. Bytecode is executed by JVM B. The applet makes the Java code secure and portable C. Use of exception handling D. Dynamic binding between object 1.3 Understanding Data-Types, Operators and Expressions Data type: A data type defines which kind of data will store in variables and also defines memory storage of data. There are two kinds of data types User defined data types and Standard data types. The Java language allows you to create and use data types other than the fundamental data types. These types are called user-defined data types. In Java language, there are four main data types • char • int • float • Boolean 1. Character data type  A keyword char is used for character data type. This data type is used to represents letters or symbols.  A character variable occupies 1 byte on memory.
  • 10. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 10 2. Integer data types Integers are those values which have no decimal part and they can be positive or negative. Like 12 or -12. There are 3 data types for integers a. int b. short int c. long int  int keyword is used for integers. It takes two bytes in memory. There are two more types of int data type. i. Signed int or short int (2nd type of integer data type) ii. Unsigned int or unsigned short int Signed int: The range of storing value of signed int variable is -32768 to 32767.It can interact with both positive and negative value. Unsigned int: This type of integers cannot handle negative values. Its range is 0 to 65535. Long int  As its name implies, it is used to represent larger integers.  It takes 4byte in memory and its range is -2147483648 to 2147483648. 3. Float: This type of data type is defined for fractional numbers. There are two further type of data type for fractional numbers. Below table is Displaying:  Number of bytes or memory taken by numbers. Decimal places up to which they can represent value. Data type Bytes Decimal places Range of values float 4 6 3.4E -38 to3.4E+38 double 8 15 1.7E - 308 to1.7E +308 long double 10 19 3.4E -4932 to 304E +4932 Constant Constant is a data type whose value is never changes and remains the same through the programme execution. Example: - Area of the circle A=πr2 ; const float π=3.14 - Total number of days in a week=7 ; - Total hours in a day=24 - Body temperature of human=23C0; Here the value of above listed can be treated as a constant through the program execution. The four basic data types in java, their meaning, and their size are: Type Meaning Size (bytes) Size (bits) char a single byte, capable of holding one character 1 byte 8 bits int an integer 2 bytes 16 bits float single-precision floating point number 4 bytes 32 bits double double-precision floating point number 8 bytes 64 bits Byte is the smallest addressable memory unit. Bit, which comes from BInary digiT, is a memory unit that can store either a 0 or a 1. A byte has 8 bits. Operators in Java
  • 11. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 11 An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Java is rich in built-in operators and provides following type of operators:  Arithmetic Operators  Relational Operators  Increment Operator  Decrement Operator  Scope resolution operator  Logical Operators  Assignment Operators  Arithmetic Operators: The following arithmetic operators are supported by Java language: Assume variable A holds 10 and variable B holds 20 then: Operator Description Example + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiply both operands A * B will give 200 / Divide numerator by de-numerator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 ++ Increment operator, increases integer value by one A++ will give 11 -- Decrement operator, decreases integer value by one A-- will give 9  RelationalOperators: The following relational operators are supported byJava language: Assume variable A holds 10 and variable B holds 20 then: Operator Description Example == Checks if the value of two operands is equal or not, (A == B) is not true. != Checks if the value of two operands is equal or not, (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, (A <= B) is true. Logical/Boolean operator: The following logical operators are supported by Java language: Assume variable A holds 1 and variable B holds 0 then: Operator Description Example && If both the operands are non-zero then condition becomes true. (A && B) is false. || If any of the two operands is non-zero then condition becomes true. (A || B) is true. ! Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.
  • 12. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 12 Assignment Operators: Assignment operator is used for assign/initialize a value to the variable during the program execution. The following assignment operators are supported by Java language: Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A Increment Operator (++): This operator is used for increment the value of an operand. Example: assume that A=20 and B=12, then ++A=21, ++B=12 and A++=20, B++=12 Decrement Operators (--):This operator is used for decrement the value of an operand. Example: assume that B=14 and C=10, then –B=13, --C=9 and B-- =14, C--=10 Scope resolution operator (::) This operator is used to differentiate a local variable from the global variable. The variable having the same name can have different meaning at different block. Expression: Expressions are formed by combining operators and operands together following the programming language. Compile & Execute Java Program: Let’s look at how to save the file, compile and run the program. Please follow the steps given below:  Open a text editor and write the code  Save the file as : hello.java  Compile it to check if it has error  Debug the code.  You will be able to see ' Hello World ' printed on the window. Semicolons & Blocks in Java: In Java, the semicolon is a statement terminator. Each individual statement must be ended with a semicolon. For example, following are three different statements: x = y; y = y+1; add(x, y); A block is a set of logically connected statements that are surrounded by opening and closing braces. For example: { System.out.println( "Hello World"); // prints Hello World return 0;}
  • 13. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 13 Self-Check -3 Written Test Directions: Answer all the questions listed below. Use the Answer sheet provided in the next page:(2 pts each) 1. Decrement operator, −−, decreases the value of variable by what number? A. 1 B. 2 C. 3 D.4 2. Which of these statements are incorrect? A. Assignment operators are more efficiently implemented by Java run-time system than their equivalent long forms B. Assignment operators run faster than their equivalent long forms C. Assignment operators can be used only with numeric and character data type D.None of the mentioned 3. Can 8 byte long data type be automatically type cast to 4 byte float data type? A. True B. False 4. To change the order in which expressions areevaluated …………………. areplaced around the expression that is to be evaluated first. A) ampersand B) equals C) parentheses D) greater than 5. What will bethe result of the expression of 8/8. A) 16 B) 1 C) 8 D) 64 6. If j and k are int typevariables, what will bethe result of the expression j%k when j=10 and k=3? A) 0 B) 1 C) 2 D) 3 7. Which of the following assignment operator does not exist in Java? A. > B. %= C >>> D < 8. Modulus operator, %, can be applied to which of these? A. Both Integers and floating - point numbers B. Integers C. Floating - point numbers D. None of the mentioned 1.4 Using the Appropriate Language Syntax for Sequence, Selection and Iteration Constructs Control Structures in java is a Statement that used to control the flow of execution in a program. There are three types of Control Structures:
  • 14. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 14 1. Sequence structure 2. Selection structure 3. Loops/ Repetition/ Iteration Sequence Structure in java The sequence structure is built into java statements that execute one after the other in the order in which they are written—that is, in sequence. Break and continue statements are example of sequence control structure. The ‘break’ statement causes an immediate exit from the inner most ‘while’, ‘do…while’, ‘for loop’ or from a ‘switch- case’ statement. If you are using nested loops (ie. one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. Flow Diagram: Example: public class FirstJavaProgram { public static void main(String[] args){ int a = 10; // Local variable declaration: do{ // do loop execution System.out.println("value of a: "+a); a = a + 1; if( a > 15) { break; } }while( a < 20 ); return 0; } When the above code is compiled and executed, it produces following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
  • 15. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 15 The goto statement provides an unconditional jump from the goto to a labeled statement in the same function. Syntax of a goto statement in java: goto label; .. . label: statement; Where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is preceded by an identifier followed by a colon (:). Flow Diagram: Example: public class FirstJavaProgram { public static void main(String[] args){ int a = 10; // Local variable declaration: LOOP:do // do loop execution { if( a == 15) { a = a + 1;// skip the iteration. goto LOOP; } System.out.println("value of a: " +a ); a = a + 1; }while( a < 20 ); return 0; } When the above code is compiled and executed, it produces following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16
  • 16. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 16 value of a: 17 value of a: 18 value of a: 19 The continue statement is similar to ‘break’ statement but instead of terminating the loop, the continue statement returns the loop execution if the test condition is satisfied. Flow Diagram: Example: public class FirstJavaProgram { public static void main(String[] args){ int a = 10; // Local variable declaration: do{ // do loop execution if( a == 15) { a = a + 1; // skip the iteration. continue; } System.out.println("value of a: " +a ); a = a + 1; }while( a < 20 ); return 0; } When the above code is compiled and executed, it produces following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 Selection statements in java
  • 17. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 17 There are basically two types of control statements in java that allows the programmer to modify the regular sequential execution of statements. They are selection and iteration statements. The selection statements allow to choose a set of statements for execution depending on a condition. If statement and switch statement are the two selection statements. If ... else statement: Syntax: if (expression or condition) { Statement 1; Statement 2; } Else { Statement 3; Statement 4; } If the condition is true, statement1 and statement2 is executed; otherwise statement 3 and statement 4 is executed. The expression or condition is any expression built using relational operators which either yields true or false condition. Flow Diagram: If the condition evaluates to true, then the if block of code will be executed otherwise else block of code will be executed. Following program implements the if statement. public class FirstJavaProgram { public static void main(String[] args){ int num=12; if ((num%2) == 0) System.out.println("is a even number "); else System.out.println("a number is odd"); } The above program accepts a number from the user and divides it by 2 and if the remainder (remainder is obtained by modulus operator) is zero, it displays the number is even, otherwise it is odd. you must use the relational operator ‘ ==’ to compare whether remainder is equal to zero or not.
  • 18. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 18 Switch statement One alternative to nested if statement is the switch statement which allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Syntax: Switch (variablename) { case value1: statement1; break; case value2: statement2; break; case value3: statement3; break; default: statement4; } Flow Diagram: Example: public class FirstJavaProgram { public static void main(String[] args){ int choice=3; switch (choice) { case 1: System.out.println(""First item selected!" ); break; case 2: System.out.println(""second item selected!" ); break; case 3: System.out.println(""third item selected!" ); break; default: System.out.println("Invalid selection!!" ); } }} Iteration statements in java Iteration or loops statements are important statements in java, which helps to accomplish repeatitive execution of programming statements. There are three loop statements in java. They are - while loop, do while loop and for loop. While Loop The while loop construct is a way of repeating loop body over and over again while a certain condition remains true. Once the condition becomes false, the control comes out of the loop. Loop body will execute only if condition is true. Syntax: While (condition or expression) {
  • 19. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 19 Statement1; Statement 2; } Flow Diagram: The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to display the output. Example: public class FirstJavaProgram { public static void main(String[] args){ { int n=10, i=1, sum=0; while(i<=n) { sum=sum+i; i++; } System.out.println( " sum of the series is "+ sum); } Do …While loop The do... while statement is the same as while loop except that the condition is checked after the execution of statements in the do..while loop. Syntax: do{ Statement; While (test condition); Statement; } Flow Diagram:
  • 20. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 20 Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement. Hence in do..while loop, Loop body execute once even if the condition is false. Example: public class FirstJavaProgram { public static void main(String[] args){ int n=10, i=1, sum=0; { int n, i=1, sum=0; do{ sum=sum+i; i++; } while(i<=n); System.out.println( " sum of the series is "+ sum); }} For loop: The for loop statements (loops or iteration statement) in java allow a program to execute a single statement multiple times (repeatedly) , given the initial value, the condition, and increment/decrement value. Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is: for (initialExpression; testExpression; updateExpression) { // body of the loop } Here, • The initialExpression initializes and/or declares variables and executes only once. • The condition is evaluated. If the condition is true, the body of the for loop is executed. • The updateExpression updates the value of initialExpression. syntax: for ( initial value ; test condition ; increment/decrement) { Statement; }
  • 21. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 21 Flow Diagram: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Example: public class FirstJavaProgram { public static void main(String[] args){ int n=10, i=1, sum=0; { for(i=1;i<=n; i++) { sum=sum+i; } System.out.println( " sum of the series is "+ sum); }} Nested Loop in Java If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop. Syntax for Nested For loop: for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop } // outer loop for (int i = 1; i <= 5; ++i) { // codes // inner loop for(int j = 1; j <=2; ++j) { // codes } .. } class Main { public static void main(String[] args) { int weeks = 3;
  • 22. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 22 int days = 7; // outer loop prints weeks for (int i = 1; i <= weeks; ++i) { System.out.println("Week: " + i); // inner loop prints days for (int j = 1; j <= days; ++j) { System.out.println(" Day: " + j); } } } } output Week: 1 Day: 1 Day: 2 Day: 3 Day:4 ..... .. .... Week: 2 Day: 1 Day: 2 Day: 3 In the above example, the outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates 7 times and prints the 7 days. Self-Check -4 Written Test Directions: Answer all the questions listed below. Use the Answer sheet provided in the next page:(2 pts each) 1. The while loop repeats a set of code while the condition is not met? A) True B) False 2. What is true about a break? A. Break stops the execution of entire program B. Break halts the execution and forces the control out of the loop C. Break forces the control out of the loop and starts the execution of next iteration D. Break halts the execution of the loop for certain time frame 3. What is true about do statement? A. do statement executes the code of a loop at least once B. do statement does not get execute if condition is not matched in the first iteration C. do statement checks the condition at the beginning of the loop D. do statement executes the code more than once always 4. Which of the following is used with the switch statement? A) Continue B) Exit C) break D) do 5. From where break statement causes an exit? a) Only from innermost loop
  • 23. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 23 b) Terminates a program c) Only from innermost switch d) From innermost loops or switches 6. Which of the following is not a valid flow control statement? a) exit() b) break c) continue d) return 1.5 Using modular programming approach Many programs are too long or complex to write as a single unit. Programming becomes much simpler when the code is divided into small functional units (modules). Modular programming is a programming style that breaks down program functions into modules, each of which accomplishes one function and contains all the source code and variables needed to accomplish that function. Modular programs are usually easier to code, compile, debug, and change than large and complex programs. The benefits of modular programming are:  Efficient Program Development Programs can be developed more quickly with the modular approach since small subprograms are easier to understand, design, and test than large and complex programs.  Multiple Use of Subprograms Code written for one program is often useful in others.  Ease of Debugging and Modifying Modular programs is generally easier to compile and debug than monolithic (large and complex) programs. 1.5.1 Modularity in Java If you've been a developer for any length of time, you'll have very likely realized that the word module is perhaps one of the most over used terms in software development. A module can mean anything ranging from a group of code entities, components, or UI types, to framework elements to complete reusable libraries. Sometimes, we use the word to imply multiple meanings in the same context! There is a good reason for that. When writing code, we typically try to break the code base down into smaller units in order to manage complexity. For anything more than very simple programs, having a monolithic code base is not a good idea. That's why modular programming is a generally favored software design approach. There are two important goals that modularity in software development usually achieves, which are as follows: Divide and conquer approach What do you do when you need to solve a large and seemingly insurmountable problem? You break it down! You'll very likely split it into smaller problems and solve them individually. The principles of modularity encourages separating large code bases into smaller encapsulated units of functionality that are then composed to work together as a bigger unit. This aligns well with the approach we humans usually take to solve large problems. Also, once you've got a bunch of smaller modules with specialized concerns, you can use those to solve various other problems. Thus, we also achieve reusability! When you build modules, you have the ability to hide the internal implementation from the consumers of your module. The hidden implementation details are usually referred to as being encapsulated, and what you expose to the consumers of your module is usually called the interface of your module. Achieving encapsulationand well-defined interfaces
  • 24. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 24 When you build modules, you have the ability to hide the internal implementation from the consumers of your module. The hidden implementation details are usually referred to as being encapsulated, and what you expose to the consumers of your module is usually called the interface of your module. Although Java developers have leveraged many different patterns and best practices over the years in order to write and structure modular and maintainable code, the language has never had native support to create modular units and build modular applications, until Java 9. With Java 9, Java developers now have the ability to create smaller units of code with a new construct called Java modules that they can group together like building blocks in order to compose larger applications. In addition to introducing this feature to the language, Java 9 also comes with what is probably the biggest overhaul to the core Java code bases itself. The Java Runtime Environment (JRE) and the Java Development Kit (JDK) have been rewritten to use the concepts of modularity so that the core Java Platform itself is modularized. When learning about Java 9 module features, it's important to understand what those new features add to the language when compared to the other features the language already has. Can't we write well organized code in Java 8? In fact, one of the benefits of object-oriented programming is indeed the idea of breaking down functionality into sub-units called objects or classes. We've been writing code like this in Java since version 1. Every Java class contains a portion of the overall application functionality that happens to belongs together. We have the ability to encapsulate some functionality as internal to a class (as private) and some others as external (or public). And then there's something in between with protected, thanks to the concept of packages. 1.6 Using arrays and arrays of objects An Array is a collection of similar data items which shares a common name within the consecutive memory. An Array can be any data type, but it should be the collection of similar items. Each item in an array is termed as ‘element’, but each element in an array can be accessed individually. The number of element in an array must be declared clearly in the definition. The size or number of elements in the array can be varied according to the user needs. Syntax for array declaration: DataType ArrayName [number of element in the array] Example: int a[5]; - ‘int’ is the data type. - ‘a’ is the array name. - 5 is number of elements or size. int a[5] means a[0], a[1], a[2], a[3], a[4] or int Int int int int a[0] a[1] a[2] a[3] a[4] - 0, 1, 2, 3, 4 are called subscript which is used to define an array element position and is called Dimension. - Array index in java starts from 0 to n-1 if the size of array is n. An individual element of an array is identified by its own unique index (or subscript). NOTE: The elements field within brackets [], which represents the number of elements the array is going to hold, must be a constant value.
  • 25. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 25 Arrays of variables of type “class” are known as "Array of objects". The "identifier" used to refer the array of objects is a user defined data type. Self-Check -6 Written Test Directions: Answer all the questions listed below. Use the Answer sheet provided in the next page:(2 pts each) 1. Which of these distinctions of modular programs over non modular are true? a) They are not that easier to understand and explain b) They are not easier to document c) They are easier to change d) Testing and Debugging is complex comparatively 2. Which of these comes under the Modularity principle? a) Small modules b) Coupling c) Cohesion d) All of the mentioned 3. An array Index starts with.? a) -1 b) 0 c) 1 d) 2 4. Objects in a sequence that have the same type, is called a). Arrays b). Operators c). Functions d). Stacks 5. Choose one of the best option from the following Position number contained within a square brackets e.g. my_array [5], is referred as ____? a) Sub-scripts b) Post-scripts c) Elements of an array d) None of them
  • 26. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 26 LO2. Apply basic OOP principles in the target language 2.1 Object Oriented Programming in java Java is an object oriented language because it provides the features to implement an object oriented model. Java is an object-oriented programming language. The core concept of the object-oriented approach is to break complex problems into smaller objects. It is used to implement real-world entities like inheritance, polymorphism, abstraction; etc in the program to makes the program resusable, efficient, and easy-to-use. An object is any entity that has a state and behavior. For example, a bicycle is an object. It has States: idle, first gear, etc Behaviors: braking, accelerating, etc. Before we learn about objects, let's first know about classes in Java. 2.2 Introduction to Java Class A class can be considered as a blueprint using which you can create as many objects as you like. For example, here we have a class Website that has two data members (also known as fields, instance variables and object states). This is just a blueprint, it does not represent any website, however using this we can create Website objects (or instances) that represents the websites. We have created two objects, while creating objects we provided separate properties to the objects using constructor. A class is a blueprint for the object. Before we create an object, we first need to define the class. We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object. Since many houses can be made from the same description, we can create many objects from a class. OOPS is about developing an application around its data, i.e. objects which provides the access to their properties and the possible operations in their own way. A class in java is an encapsulation of data members and functions that manipulate the data. In terms of variables, a class would be the type, and an object would be the variable. 2.2.1 Classesand Objects A class is a type, and an object of this class is just a variable. Before we can use an object, it must be created. Classes are generally declared using the keyword class. Syntax Acces modifier class ClassName { // fields // methods } Here, fields (variables) and methods represent the state and behavior of the object respectively. Fields are used to store data Methods are used to perform some operations Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members that can be either data or function declarations, or optionally access modifier. These modifier modify the access:  Public: Access to all code in the program.
  • 27. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 27 public members are accessible from anywhere where the object is visible.  Private: Access to only members of the same class  Protected: Access to members of same class and its derived classes For example our bicycle object, we can create the class as Example: class Bicycle { // state or field private int gear = 5; // behavior or method public void braking() { System.out.println("Working of Braking"); } } In the above example, we have created a class named Bicycle. It contains a field named gear and a method named braking (). Here, Bicycle is a prototype. Now, we can create any number of bicycles using the prototype. And, all the bicycles will share the fields and methods of the prototype. Note: We have used keywords private and public. These are known as access modifiers. Variables in Java  Types of Variables in Java There are three types of variables in Java. 1) Local variable 2) Static (or class) variable 3) Instance variable Static (or class) Variable Static variables are also known as class variable because they are associated with the class and common for all the instances of class. For example, If I create three objects of a class and access this static variable, it would be common for all, the changes made to the variable using one of the object would reflect when you access it through other objects. Example of static variable public class StaticVarExample { public static String myClassVar="class or static variable"; public static void main(String args[]){ StaticVarExample obj = new StaticVarExample(); StaticVarExample obj2 = new StaticVarExample(); StaticVarExample obj3 = new StaticVarExample(); //All three will display "class or static variable" System.out.println(obj.myClassVar);
  • 28. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 28 System.out.println(obj2.myClassVar); System.out.println(obj3.myClassVar); //changing the value of static variable using obj2 obj2.myClassVar = "Changed Text"; //All three will display "Changed Text" System.out.println(obj.myClassVar); System.out.println(obj2.myClassVar); System.out.println(obj3.myClassVar); }} Output: class or static variable class or static variable class or static variable Changed Text Changed Text Changed Text As you can see all three statements displayed the same output irrespective of the instance through which it is being accessed. That’s is why we can access the static variables without using the objects like this: System.out.println(myClassVar); Do note that only static variables can be accessed like this. This doesn’t apply for instance and local variables. Instance variable Each instance(objects) of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable. We have changed the instance variable value using object obj2 in the following program and when we displayed the variable using all three objects, only the obj2 value got changed, others remain unchanged. This shows that they have their own copy of instance variable. Example of Instance variable public class InstanceVarExample { String myInstanceVar="instance variable"; public static void main(String args[]){ InstanceVarExample obj = new InstanceVarExample(); InstanceVarExample obj2 = new InstanceVarExample(); InstanceVarExample obj3 = new InstanceVarExample(); System.out.println(obj.myInstanceVar); System.out.println(obj2.myInstanceVar); System.out.println(obj3.myInstanceVar); obj2.myInstanceVar = "Changed Text"; System.out.println(obj.myInstanceVar); System.out.println(obj2.myInstanceVar); System.out.println(obj3.myInstanceVar); }}
  • 29. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 29 Output: instance variable Instance variable instance variable instance variable Changed Text instance variable Local Variable These variables are declared inside method of the class. Their scope is limited to the method which means that You can’t change their values and access them outside of the method. In this example, I have declared the instance variable with the same name as local variable, this is to demonstrate the scope of local variables. Example of Local variable public class VariableExample { // instance variable public String myVar="instance variable"; public void myMethod(){ // local variable String myVar = "Inside Method"; System.out.println(myVar); } public static void main(String args[]){ // Creating object VariableExample obj = new VariableExample(); /* We are calling the method, that changes the * value of myVar. We are displaying myVar again after * the method call, to demonstrate that the local * variable scope is limited to the method itself. */ System.out.println("Calling Method"); obj.myMethod(); System.out.println(obj.myVar); }} Output: Calling Method Inside Method instance variable Java Constructor Constructorlooks like a method but it is in fact not a method. It’s name is same as class name and it does not return any value. You must have seen this statement in almost all the programs I have shared above: MyClass obj = new MyClass();
  • 30. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 30 If you look at the right side of this statement, we are calling the default constructor of class myClass to create a new object (or instance). We can also have parameters in the constructor, such constructors are known as parametrized constructors. To understand the working of constructor, lets take an example. lets say we have a class MyClass. When we create the object of MyClass like this: MyClass obj = new MyClass() The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object.  Types of Constructors There are three types of constructors: Default, No-arg constructor and Parameterized. Default constructor • If you do not implement any constructor in your class, Java compiler inserts a default constructor into your code on your behalf. This constructor is known as default constructor.
  • 31. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 31 • You would not find it in your source code(the java file) as it would be inserted into the code during compilation and exists in .class file. • This process is shown in the diagram below: If you implement any constructor then you no longer receive a default constructor from Java compiler. no-arg constructor: Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty. Although you may see some people claim that that default and no-arg constructor is same but in fact they are not, even if you write public Demo() { } in your class Demo it cannot be called default constructor since you have written the code of it. Example: no-arg constructor class Demo{ public Demo() { System.out.println("This is a no argument constructor"); } public static void main(String args[]) { new Demo(); }} Output: This is a no argument constructor Parameterized constructor Constructor with arguments(or you can say parameters) is known as Parameterized constructor Example: parameterized constructor In this example we have a parameterized constructor with two parameters id and name. While creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after creation of obj1 and obj2. public class Employee { int empId; String empName; //parameterized constructor with two parameters Employee(int id, String name){ this.empId = id;
  • 32. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 32 this.empName = name; } void info(){ System.out.println("Id: "+empId+" Name: "+empName); }  Java method A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design. A method is a block of code that performs a specific task. Suppose you need to create a program to create a circle and color it. You can create two methods to solve this problem: a method to draw the circle a method to color the circle Dividing a complex problem into smaller chunks makes your program easy to understand and reusable. In Java, there are two types of methods: User-defined Methods: We can create our own method based on our requirements. Standard Library Methods: These are built-in methods in Java that are available to use. Let's first learn about user-defined methods. Declaring a Java Method The syntax to declare a method is: returnType methodName() { // method body } Here, returnType - It specifies what type of value a method returns For example if a method has an int return type then it returns an integer value. If the method does not return a value, its return type is void. methodName - It is an identifier that is used to refer to the particular method in a program. method body - It includes the programming statements that are used to perform some tasks. The method body is enclosed inside the curly braces { }. For example, int addNumbers() { // code } In the above example, the name of the method is adddNumbers(). And, the return type is int. We will learn more about return types later in this tutorial. This is the simple syntax of declaring a method. However, the complete syntax of declaring a method is modifie returnType nameOfMethod (parameter1, parameter2, ...) { // method body } Here, modifier - It defines access types whether the method is public, private, and so on. To learn more, visit Java Access Specifier. static - If we use the static keyword, it can be accessed without creating objects. For example, the sqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt() without creating an instance of Math class.
  • 33. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 33 parameter1/parameter2 - These are values passed to a method. We can pass any number of arguments to a method. Calling a Method in Java In the above example, we have declared a method named addNumbers(). Now, to use the method, we need to call it. Here's is how we can call the addNumbers() method. // calls the method addNumbers(); Example 1: Java Methods class Main { // create a method public int addNumbers(int a, int b) { int sum = a + b; // return value return sum; } public static void main(String[] args) { int num1 = 25; int num2 = 15; // create an object of Main Main obj = new Main(); // calling method int result = obj.addNumbers(num1, num2); System.out.println("Sum is: " + result); } } Output Sum is: 40 Java Method Return Type A Java method may or may not return a value to the function call. We use the return statement to return any value. For example,
  • 34. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 34 int addNumbers() { ... return sum; } Here, we are returning the variable sum. Since the return type of the function is int. The sum variable should be of int type. Otherwise, it will generate an error. Example 2: Method Return Type class Main { // create a method public static int square(int num) { // return statement return num * num; } public static void main(String[] args) { int result; // call the method // store returned value to result result = square(10); System.out.println("Squared value of 10 is: " + result); } } Output: Squared value of 10 is: 100 In the above program, we have created a method named square(). The method takes a number as its parameter and returns the square of the number. Here, we have mentioned the return type of the method as int. Hence, the method should always return an integer value. public void square(int a) { int square = a * a; System.out.println("Square is: " + square ); } Method Parameters in Java A method parameter is a value accepted by the method. As mentioned earlier, a method can also have any number of parameters. For example, // method with two parameters int addNumbers(int a, int b) { // code }
  • 35. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 35 // method with no parameter int addNumbers(){ // code } If a method is created with parameters, we need to pass the corresponding values while calling the method. For example, // calling the method with two parameters addNumbers(25, 15); // calling the method with no parameters addNumbers() Example 3: Method Parameters class Main { // method with no parameter public void display1() { System.out.println("Method without parameter"); } // method with single parameter public void display2(int a) { System.out.println("Method with a single parameter: " + a); } public static void main(String[] args) { // create an object of Main Main obj = new Main(); // calling method with no parameter obj.display1(); // calling method with the single parameter obj.display2(24); } } Output Method with parameter Method with a single parameter: 24 Standard Library Methods The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE. For example, print() is a method of java.io.PrintSteam. The print("...") method prints the string inside quotation marks. sqrt() is a method of Math class. It returns the square root of a number. Here's a working example: Example 4: Java Standard Library Method public class Main { public static void main(String[] args) { // using the sqrt() method System.out.print("Square root of 4 is: " + Math.sqrt(4)); } } Output: Square root of 4 is: 2.0 Output Method with parameter Method with a single parameter: 24  ModelClasses andObjects real-life beings to software entities Let's take an example of developing a pet management system, specially meant for dogs. You will need various information about the dogs like different breeds of the dogs, the age, size, etc. You need to model real-life beings, i.e., dogs into software entities
  • 36. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 36 Moreover, the million dollar question is, how you design such software? Here is the solution-First, let's do an exercise. You can see the picture of three different breeds of dogs below. Stop here right now! List down the differences between them. Some of the differences you might have listed out maybe breed, age, size, color, etc. If you think for a minute, these differences are also some common characteristics shared by these dogs. These characteristics (breed, age, size, color) can form a data members for your object. common characteristics
  • 37. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 37 common behaviors of these dogs Next, list out the common behaviors of these dogs like sleep, sit, eat, etc. So these will be the actions of our software objects. So far we have defined following things,  Class – Dogs  Data members or objects- size, age, color, breed, etc.  Methods- eat, sleep, sit and run.
  • 38. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 38 Now, for different values of data members (breed size, age, and color) in Java class, you will get different dog objects.
  • 39. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 39 Know you can design program using oop approach You can design any program using this OOPs approach. While creating a class, one must follow the following principles. • // Class Declaration • public class Dog { • // Instance Variables • String breed; • String size; • int age; • String color; • // method 1 • public String getInfo() { • return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color); • } • public static void main(String[] args) { • Dog maltese = new Dog(); • maltese.breed="Maltese"; • maltese.size="Small"; • maltese.age=2; • maltese.color="white"; • System.out.println(maltese.getInfo()); • } • } • Out put: Breed is: Maltese Size is:Small Age is:2 color is: white  Types of method Static Methods Static methods are methods in java that can be called without actually creating an object of that class. By declaring a method using the static keyword, you can call it without first creating an object because it becomes part of the class or a class method(a method that belongs to a class rather than to an object). They are designed with aim to be shared with all objects created with that class. One reason why you might want to use a static method is when you want a common operation to be performed through out the class. Static methods cannot be overridden. Syntax: Static keyword followed by return type, followed by method name. static return_type method_name(); EXAMPLE: class Car{ static void display(){ System.out.println(“this is my favorite car”); } public static void main(String[], args){ .display();
  • 40. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 40 } } Instance Methods Instance methods are methods that require an object of its class to be created before it can be called. Instance methods belong to object of the class and not the class. Every object individual object created from the class has its own copy of the instance methods of that class. They can be overridden. class JavaExample{ static int i = 100; static String s = “sawla"; //Static method static void display() { System.out.println("i:"+i); System.out.println("i:"+s); } //non-static method void funcn() { //Static method called in non-static method display(); } //static method public static void main(String args[]) { JavaExample obj = new JavaExample(); //You need to have object to call this non-static method obj.funcn(); //Static method called in another static method display(); }} 2.3 Object constructionin Java class  Java Objects An object is called an instance of a class. For example, suppose Bicycle is a class then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as objects of the class. Here is how we can create an object of a class. className object = new className(); // for Bicycle class Bicycle sportsBicycle = new Bicycle(); Bicycle touringBicycle = new Bicycle(); We have used the new keyword along with the constructor of the class to create an object. Constructors are similar to methods and have the same name as the class. For example, Bicycle() is the constructor of the Bicycle class.
  • 41. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 41 Here, sportsBicycle and touringBicycle are the names of objects. We can use them to access fields and methods of the class. As you can see, we have created two objects of the class. We can create multiple objects of a single class in Java. Note: Fields and methods of a class are also called members of the class. Self-Check -5 Written Test Directions: Answer all the questions listed below. Use the Answer sheet provided in the next page:(2 pts each) 1. Properties are implemented using ___ in Java. a) Methods b) Variables c) Interfaces d) All the above 2. Which is the file extension used for a public Java class source code? a) .j b) .class c) .java d) None 3. After compilation, ajava -Class is kept in a ___ file in Java programming. a) .java b) .cls c) .class d) .interface 4. In Java, the keyword used to declare a class is ___. a) Class b) Java c) class d) java 5. A Java class can contain___. a) Variables b) Methods, Constructors c) Inner Classes d) All the above 6. Creating an object from a class is also called ____. a) Initializing b) Instantiating c) Interfacing d) None of the above 7. The keyword used to create a new object in Java is ___. a) class b) java c) new d) create 8. Choose the correct statements about choosing a name for a class in Java. a) The class name can start with only a letter or underscore or dollar sign. b) The class name can contain numbers c) The class name can not start with a number d) All the above 9. An object is created at __ time in Java. a) Compile-time b) Run time c) Assembling time d) None of the above 10. A Java constructor is like a method without ___. a) statements b) return type c) argument list d) None 11. The name of a constructor and the name of a class are ___. a) Same as with class name b) Different with class name c) a&b 12. All Java methods must have a return type. (TRUE / FALSE) a) true b) false 13. Java method signature is a combination of ___. a) Return type b) Method name c) Argument List d) All the above
  • 42. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 42 2.4 Object Oriented Programming features in java These features include inheritance, polymorphism, encapsulation and Abstraction . These four features are the main OOPs Concepts that you must learn to understand the Object Oriented Programming in Java Inheritance The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it, rest of the features can be inherited from the parent class. Inheritance is a process of defining a new class based on an existing class by extending its common data members and methods. Inheritance allows us to reuse of code, it improves reusability in your java application. The parent class is called the base class or super class. The child class that extends the base class is called the derived class or sub class or child class. Syntax: Inheritance in Java To inherit a class we use extends keyword. Here class A is child class and class B is parent class. class A extends B { } Inheritance Example
  • 43. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills ByAmanuelKassa Page 43 In this example, we have a parent class Teacher and a child class MathTeacher. In the MathTeacher class we need not to write the same code which is already present in the present class. Here we have college name, sawla and does() method that is common for all the teachers, thus MathTeacher class does not need to write this code, the common data members and methods can inherited from the Teacher class. class Teacher { String designation = "Teacher"; String college = “sawla"; void does(){ System.out.println("Teaching"); } } public class MathTeacher extends Teacher{ String mainSubject = "Maths"; public static void main(String args[]){ MathTeacher obj = new MathTeacher(); System.out.println(obj.college); System.out.println(obj.designation); System.out.println(obj.mainSubject); obj.does(); } } • Output: • sawla • Teacher • Maths • Teaching Forms/types of Inheritance: - Single Inheritance - Multiple Inheritance - Multilevel Inheritance - Hierarchical Inheritance - Hybrid Inheritance 1. Single inheritance: - If a class is derived from a single base class, it is called as single inheritance. In Single Inheritance, there is only one Super Class and Only one Sub Class Means they have one to one Communication between them. 2. Multiple Inheritances: - If a class is derived from more than one base class, it is known as multiple inheritances.
  • 44. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 44 3. Multilevel Inheritance: When a derived class is created from another derived class, then that inheritance is called as multi level inheritance. 4. HierarchicalInheritance: If a number of classes are derived from a single base class, it is called as hierarchical inheritance. This means a Base Class will have Many Sub Classes or a Base Class will be inherited by many Sub Classes. 5. Hybrid Inheritance: This is a Mixture of two or More Inheritance types. I.e.: Any combination of single, hierarchical and multi-level inheritances is called as hybrid inheritance.
  • 45. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 45  Polymorphism in Java The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. Real life example of polymorphism in Java Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person present in different-different behaviors. How to achieve Polymorphism in Java ?
  • 46. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 46 In java programming the Polymorphism principal is implemented with method overriding concept of java. Polymorphism principal is divided into two sub principal they are: Static or Compile time polymorphism Dynamic or Runtime polymorphism Static Polymorphism: Polymorphism that is resolved during compiler time is known as static polymorphism. Method overloading can be considered as static polymorphism example. Method Overloading: This allows us to have more than one methods with same name in a class that differs in signature. class DisplayOverloading { public void disp(char c) { System.out.println(c); } public void disp(char c, int num) { System.out.println(c + " "+num); } } public class ExampleOverloading { public static void main(String args[]) { DisplayOverloading obj= newDisplayOverloading(); obj.disp('a'); obj.disp('a',10); } } Output: a a 10 Dynamic Polymorphism It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime rather, thats why it is called runtime polymorphism. Example class Animal{ public void animalSound(){ System.out.println("Default Sound"); } public class Dog extends Animal{ public void animalSound(){ System.out.println("Woof"); } public class Dog extends Animal{ public void animalSound(){ System.out.println("Woof");
  • 47. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 47 } public static void main(String args[]){ Animal obj = newDog(); obj.animalSound(); } } Output: • Woof Since both the classes, child class and parent class have the same method animalSound. Which of the method will be called is determined at runtime by JVM.  Abstraction One of the most fundamental concept of OOPs is Abstraction. Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. The abstract keyword is a non-access modifier, used for classes and methods: • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). • Syntax Abstract Class • abstract class A{ • abstract void myMethod(); • void anotherMethod(){ • //Does something • } • } Note 1: There can be some scenarios where it is difficult to implement all the methods in the base class. In such scenarios one can define the base class as an abstract class which signifies that this base class is a special kind of class which is not complete on its own. A class derived from the abstract base class must implement those methods that are not implemented (means they are abstract) in the abstract class. Abstract class cannot be instantiated which means you cannot create the object of abstract class. To use this class, you need to create another class that extends this abstract class provides the implementation of abstract methods, then you can use the object of that child class to call non-abstract parent class methods as well as implemented methods(those that were abstract in parent but implemented in child class). If a child does not implement all the abstract methods of parent class(the abstract class), then the child class must need to be declared abstract. Example of Abstract class and Methods Here we have an abstract class Animal that has an abstract method animalSound(), since the animal sound differs from one animal to another, there is no point in giving the implementation to this method as every child class must override this method to give its own implementation details. That’s why we made it abstract. • //abstract class • abstract class Animal{ • //abstract method • public abstract void animalSound(); • } • public class Dog extends Animal{ • • public void animalSound(){
  • 48. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 48 • System.out.println("Woof"); • } • public static void main(String args[]){ • Animal obj = new Dog(); • obj.animalSound(); • } • } • Output: • Woof  Encapsulation Encapsulation is the method of combining the data and functions inside a class. This hides the data from being accessed from outside a class directly, only through the Methods inside the class is able to access the information. Encapsulation is the term given to the process of hiding all the details of an object that do not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object. Features and Advantages of the concept of Encapsulation: - Makes Maintenance of Application Easier - Improves the Understandability of the Application - Enhanced Security - Protection of data from accidental corruption - Flexibility and extensibility of the code and reduction in complexity Encapsulation example in Java How to 1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class. 2) Have getter and setter methods in the class to set and get the values of the fields.  class EmployeeCount  {  private int numOfEmployees = 0;  public void setNoOfEmployees (int count)  {  numOfEmployees = count;  }  public double getNoOfEmployees ()  {  return numOfEmployees;  }  }  public class EncapsulationExample  {  public static void main(String args[])  {  EmployeeCount obj = new EmployeeCount ();  obj.setNoOfEmployees(5613);  System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
  • 49. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 49  }  }  Output:  No Of Employees: 5613 The class EncapsulationExample that is using the Object of class EmployeeCount will not able to get the NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value. The class EncapsulationExample that is using the Object of class EmployeeCount will not able to get the NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value. So what is the benefit of encapsulation in java programming Well, at some point of time, if you want to change the implementation details of the class EmployeeCount, you can freely do so without affecting the classes that are using it. Introduction to Exception Handling An exception is a special condition that changes the normal flow of program execution. Exceptional conditions are things that occur in a system that are not expected or are not a part of normal system operation. When the system handles these exceptional conditions improperly, it can lead to failures and system crashes. Exception handling is the method of building a system to detect and recover from exceptional conditions. Exceptional conditions are any unexpected occurrences that are not accounted for in a system's normal operation. Some examples of exceptional conditions: - incorrect inputs from the user - bit level memory or data corruption If these exceptional conditions are not properly caught and handled, they can cause an error or failure in the system. An exception is a problem that arises during the execution of a program. A Java exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. Java exception handling is built upon three keywords: try, catch, and throw.  throw: A program throws an exception when a problem shows up. This is done using a throw keyword.  catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.  try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks Basic syntax: try{ } catch(Exception e){ } Example: public class ExceptionDemo { public static void main (String[] args) { int a=10; for(int i=3;i>=0;i--) try{ System.out.println(a/i);
  • 50. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 50 }catch(ArithmeticException e){ System.out.println(e); } } } Output: 3 5 10 java.lang.ArithmeticException: / by zero try block contains the code that might throw an exception. Don’t write anything extra in try as statements after the exception will not get executed if the exception occurred. Try must be immediately followed by catch or finally block. public class ExceptionDemo { public static void main (String[] args) { int a=10; for(int i=3;i>=0;i--) try{ System.out.println(a/i); } } } Compile time error: prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations try{ ^ 1 error The catch block is used to catch the exception thrown by statements in the try block. The catch must follow try else it will give a compile-time error. public class ExceptionDemo { public static void main (String[] args) { int a=10; for(int i=3;i>=0;i--) try{ System.out.println(a/i); } System.out.println("between try and catch"); catch(ArithmeticException e){ System.out.println(e); } } }
  • 51. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 51 Compile Time Error: prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations try{ ^ prog.java:9: error: 'catch' without 'try' catch(ArithmeticException e){ ^ 2 errors Things to Remember Do not keep any code after the statement which is prone to exception. Because if an exception occurred then it will straight away jump to the catch or finally block, ignoring all other statements in the try block. class Main { public static void main (String[] args) { try { System.out.println(4/0); //will not get printed System.out.println("end of try!"); } catch(ArithmeticException e) { System.out.println("divide by 0"); } } } Output: divide by 0 While catching the exception in the catch block, either you can have directly the class of exception or its superclass. Example: Exact Exception class Main { public static void main (String[] args) { try{ System.out.println(4/0); } //ArithmeticException catch(ArithmeticException e){ System.out.println("divide by 0"); }
  • 52. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 52 } } Output: divide by 0  Java GUI Programming One of the big advances that Java made when it was introduced in 1995 was the inclusion of standardized "graphical user interface" ("GUI") libraries. This was a tremendous leap forward over the bewildering array of incompatible third-party libraries that were the only avenues previously open to GUI developers. The Java GUI library was also one of the first major software packages to explicitly describe its architecture in terms of the then-brand-new language of Design Patterns. GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java applications. It is mainly made of graphical components like buttons, labels, windows, etc. through which the user can interact with an application. GUI plays an important role to build easy interfaces for Java applications. Main Packages One confusing aspect of the Java GUI system however is a legacy issue where the system underwent a large-scale upgrade in 1997, so some of the classes involved are spread over the (relatively) older java.awt packages and the newer javax.swing packages. In general, if the class name starts with "J", then it is in the Swing package. Since some functionality appears to be duplicated in the Swing packages, such as frames and buttons, always use the Swing component over the older AWT components when there is a choice.  java.awt -- Contains the main super classes for the GUI components plus a number of utility type classes, such as Color and Point.  java.awt.event -- Contains the classes and interfaces for managing events from the GUI components, e.g. button clicks and mouse movements.  javax.swing -- Contains most of the visible GUI components that are used such as buttons, text fields, frames and panels. Class Hierarchy Java uses the Composite Design Pattern to create GUI components that can also serve as containers to hold more GUI components. Here is a UML diagram showing the class relations between a few of the more commonly used GUI components:
  • 53. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 53 Above, the commonly used container components are in orange while the non-container components are in blue. Note that technically, all javax.swing components are capable of holding other Components, but in practice, only JFrame, JApplet, and JPanel, plus a few not shown above (JSplitPane, JTabbedPane and JScrollPane) are commonly used for that purpose.
  • 54. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 54 Commonly Used Classes  Simple Components javax.swing.JLabel -- A piece of non-editable text on the screen. javax.swing.JButton -- A button that can be clicked. Clicking the button will cause its actionPerformed event to be fired which will call all installed ActionListener's actionPerformed methods. javax.swing.JTextField -- A single line of user-editable text. javax.swing.JTextArea -- A box with multiple lines of text displayed. Can be set for editable or non- editable. javax.swing.JRadioButton, javax.swing.JCheckBox -- Small round or square boxes that can be clicked on to indicate the selection of something, such as an option of some sort. Clicking the radio button or check box will fire a particular type of event. Radio buttons can be grouped together using an invisible (to the user) class called javax.swing.ButtonGroup to create a set where only one button can be set at a time. javax.swing.JComboBox -- A drop-list of items. A JComboBox holds a set of Objects, not just Strings. The displayed texts are the return values of the item's toString() method. Thus a JComboBox can be used to hold arbitrary entities without the GUI knowing what those entities are. Events are fired only when the selected item changes, though the currently selected item and its index can always be retrieved.
  • 55. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 55  Container Components javax.swing.JFrame -- a stand-alone "window" or "frame" with a title and the usual abilities to be moved, resized, minimized, maximized and closed. For most people, this is the top-level container in their system. Thus a JFrame cannot hold another JFrame. While a JFrame can hold any type of component, typically, a JFrame holds JPanels, which are arranged to group together sets of the components used in the window (frame). The default layout manager of a JFrame is the BorderLayout. A JFrame has a couple of unique and important methods that are worth pointing out:  void getContentPane().add(Component c) -- adds a component to the frame. Note that a JFrame acts slightly differently than a JPanel here because JFrames have a little-used feature of multiple layers (panes) of components that can be quickly switched in and out of visibility. There are overridden forms of this method inherited from java.awt.Container that allow parameters for the layout manager to be passed along, such as specifying the component's position in a BorderLayout.  void setDefaultCloseOperation(int option) -- sets the behavior of the frame when it is closed. See the web page on Setting the Behavior When Closing a JFrame. javax.swing.JApplet -- Allows a Java program to be run as a component in a web page. Note that an applet and a frame are not the same thing and are not interchangeable, though there are some work-arounds for that which allow the same code to run as either a stand-alone application or an applet in a web page. javax.swing.JPanel -- The basic building block for laying components out in a frame or inside of other panels. A JAva GUI consists of a frame with panels holding panels holding panels, etc. Note that "panels" here could also be scroll panes, split panes and/or tabbed panes (see below). The default layout manager for a JPanel is the FlowLayout. javax.swing.JScrollPane -- Allows you to display a single panel with scroll bars on the sides, allowing more or larger components to be displayed than will fit on the screen. javax.swing.JSplitPane -- Allows two panels to be displayed with either a vertical or horizonatal, user- moveable bar separating them. javax.swing.JTabbedPane -- Allows multiple panels to be displayed in a "tabbed" format. Commonly Used Methods in GUI Containers void add(Component c) -- adds another component to the container to be laid out as per the currently installed layout manager. There are overridden forms of this method inherited from java.awt.Container that allow parameters for the layout manager to be passed along, such as specifying the component's position in a BorderLayout. void setLayout(LayoutManager lm) -- installs a new layout manager into the container. Utility Classes java.awt.Graphics --This abstract class is rarely instantiated by the developer's code. A machine- dependent instance of this class is handed to the paintComponent method of a visible GUI component during the screen painting process -- it is NOT instantiated by the developer's code but rather by the Java GUI sub- system. The developer can writed code that will use that supplied Graphics object instance to draw lines, shapes and images onto the screen. For advanced graphics work, it should be noted that the supplied Graphics object can always be safely downcast to the more capable java.awt.Graphcs2D class.
  • 56. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 56 NEVER CALL paintComponent DIRECTLY FROM YOUR OWN CODE. Likewise, NEVER INSTANTIATE A Graphics OBJECT--the Java GUI system will automatically hand your code the Graphics object that it needs. java.awt.Color -- Represents a color. Has static fields predefined to common colors plus can be expressed in a number of different formats, such as 3-bit RGB values. java.awt.Point -- Represents an point on 2-dimensional plane as specified by integer-valued Cartesian coordinates.. Has fields to retrieve the x and y coordinates plus methods for operations such as calculating the distance between two points. For floating point-valued Cartesian coordinates, use the java.awt.geom.Point2D class. Layout Managers Java containers use the Strategy Design Pattern to implement automatic layout management of GUI components on the screen. The management of the size and positions of the contained components is delegated to a "layout manager", which can be set at design time or dynamically changed. Here are a couple of common layouts: java.awt.BorderLayout -- Separates the component into 5 distinct areas, 4 non-resizeable areas on the edges ("North", "East", "South", and "West") and one re-sizeable area in the center ("Center"). Each area can only contain 1 component, so typically, panels are used in each area to hold multiple components. A typical statement that adds a component to a container that is known to have a BorderLayout installed would be myContainer.add(myComponent, BorderLayout.NORTH); java.awt.FlowLayout -- Holds multiple components in a horizontally arranged line that will wrap around if the width of the container is too small. A FlowLayout does not require any additional parameters when a component is added to the container -- the components will display left-to-right in the order in which they were added. javax.swing.BoxLayout -- Holds components in either a vertical or horizontal arrangement that is fixed, independent of the size of container. The width and height of the contained components are all identical and are automatically set tocompletely fill the container. Event Handling in Java GUIs
  • 57. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 57 Java uses the Observer-Observable Design Pattern to handle events from GUI components, e.g. button clicks and mouse movements. Components supply methods to add various types of listeners, e.g. "void addActionListener(ActionListener al)" and "void addMouseMotionListener(MouseMotionListener mml)". Multiple listeners can be added and all will be called when the associated event occurs, though there is no guarantee as to the order in which the installed listeners will be called. java.awt.event.ActionListener -- Interface used to detect a simple action on a component, such as clicking a button or hitting Enter on a text field. java.awt.event.MouseListener -- Interface used for event listeners watching for mouse click events. This event allows more detailed capture of the mouse click than an ActionListener event, for instance, distinguishing between a mouse button pressed vs. a mouse button released events. A convenience class, MouseAdapter, is also available that no-ops all the methods, freeing the developer to only write the code that overrides the desired methods. java.awt.event.MouseMotionListener -- Interface used for event listeners watching for mouse motion events, e.g. dragging. A convenience class, MouseMotionAdapter, is also available that no-ops all the methods, freeing the developer to only write the code that overrides the desired methods. How to start a GUI-based program In general, a GUI-based program will start whenever the first GUI component is shown (visibility set to true). Typically that would be one of the frames in the system, so one would have a line of code like such: myFrame.setVisible(true); This a quickie starts for a GUI program would have a main method like such: public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { (new MyFrameClass("The title")).setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } (Note: The above code correctly instantiates the frame on the GUI thread as specified by the official Java requirements. The code can be simplified a little bit by using a lambda function instead of the anonymous inner class implemenation of a Runnable.) In Model-View-Controller architectures however, it is not recommended that the view, i.e. the main frame, be started by simply setting its visibility to true. It is much better to define a "start()" method on the frame or main view class, where all final initializations and checks are performed and whose last line of code is the setVisible(true) statement.
  • 58. Sawla Polytechnic College ICT Database Administration Level IV Applying Object-Oriented Programming Language Skills By Amanuel Kassa Page 58 A typical controller in an MVC wills instantiate the model and the view, connecting them together with their respective adapters. After all that is done, the controller's last act will be to call the view's start method. NEVER START THE GUI FROM THE CONSTRUCTOR OF THE FRAME! This is simply asking for trouble as many of the other components in the system are probably not fulling instantiated or intialized yet. But as soon as the first frame becomes visible, events will start firing, and those listeners will expect fully operational objects to be present but won't find them, causing, at best, a flurry of null pointer errors.  Java GUI Example Now in this Swing Java Tutorial, let's understand GUI with Java Swing examples. Example: To learn Java GUI programming in this Java GUI tutorial Step 1) Copy the following code into a text editor like notepad import javax.swing.*; class SPTC{ public static void main(String args[]){ JFrame frame = new JFrame("Sawla Polytechnic college"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button = new JButton("SPTC_BUTTON"); frame.getContentPane().add(button); // Adds Button to content pane of frame frame.setVisible(true); }} Step 2) Save, Compile, and Run the code using javac and java commands in to cmd. Step 3) now let's Add a Button to our frame. Copy following code into an editor from given Java GUI Example import javax.swing.*; class SPTC{ public static void main(String args[]){ JFrame frame = new JFrame("Sawla Polytechnic college"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button = new JButton("SPTC_BUTTON"); frame.getContentPane().add(button); // Adds Button to content pane of frame frame.setVisible(true); }} Step 4) Execute the code. You will get a big button