Chapter 1 - OOP Using Java

Share Embed Donate


Short Description

Chapter 1 : Fundamental Programming Structures in Java...

Description

Admas University Faculty of Informatics Department of Information and Communication Technology Course Title: Object Oriented Programming Course Code: ICT 332 Credit Hours: 4 Course Objective: At the end of the course, the student will be able to:  Use the basics of the Java programming language in developing object oriented applications  Master the fundamental elements of OOP and related Java features.  Solve problems the object-oriented way of programming  Develop the ability to use the most common object oriented structures, facilities and tools. Course Description: The course covers Introduction to OOP, classes, objects, overloading, type conversion constructor, abstraction, inheritance, templates, & Polymorphism.

Course Outline 1. Fundamental Programming Structures in Java            

Java Fundamentals Data Types and Literals Variables Constants Assignments Initializations Operators Strings Control of Flow Arrays The main() method Code Examples & Exercises

2. Classes and Objects in Java           

Classes & Objects OOP Principles Instantiation Encapsulation Instance Variables Class Variables Constructors Instance Methods Class Methods Method Overloading Code Examples & Exercises

PAGE

1

3. Object Design and Programming with Java       

Abstraction Inheritance Polymorphism Method Overriding Associations Delegation Code Examples & Exercises

4. Java Interfaces     

Purpose of Interfaces When to use them Interface Declaration Implementing an Interface Code Examples & Exercises

5. Java Exception Handling        

Standard Exception Handling Options Exception Class Hierarchy Checked vs. Unchecked Exceptions Catching an Exception:- try and catch blocks Methods Which Throw Exceptions:- the throws clause Handling vs. Declaring Exceptions Writing Custom Exceptions Code Examples & Exercises

6. Java Input/Output API (Optional)      

Streams & Files Input & Output Streams File Streams Object Streams Readers & Writers Code Examples & Exercises

PAGE

2

Chapter One Outline Fundamental Programming Structures in Java 1) Java Fundamentals 2) Data Types and Literals 3) Variables 4) Constants 5) Assignments 6) Initializations 7) Operators 8) Strings 9) Control of Flow 10) Arrays 11) The main() method 12) Code Examples & Exercises

PAGE

3

JAVA PROGRAMMING LANGUAGE INTRODUCTION Introduction: WHAT IS A PROGRAMME?

DEFINITION: A program is a collection of commands & data, which tells the computer to do "something". This collection of commands is usually called source code or just code. Commands are "keywords" of a programme. Keywords are a basic building block of the language. Programming is a core activity in the process of performing tasks or solving problems with the aid of a computer. An idealised picture of this is:

[Problem or task specification]

- COMPUTER

-

[solution or completed task]

Unfortunately things are not (yet) that simple. In particular, the "specification" cannot be given to the computer using natural language. Moreover, it cannot (yet) just be a description of the problem or task, but has to contain information about how the problem is to be solved or the task is to be executed. Hence we need programming languages.

There are many different programming languages, and many ways to classify them. For example, "high-level" programming languages are languages whose syntax is relatively close to natural language, where as the syntax of "low-level" languages includes many technical references to the ZEROS and ONES ( binary 0's and 1's ) of the computer.

Languages enable the programmer to minimise his or her ACCOUNT or EFFORT of how the computer is to solve a problem or produce a particular output. "OBJECT-ORIENTED LANGUAGES" reflect a particular way of thinking about problems and tasks in terms of identifying and describing the behaviour of the relevant "objects".

PAGE

4

What is Java? Java is an object-oriented programming language originally developed by Sun Microsystems and released in 1995. Java was originally developed by James Gosling at Sun Microsystems (which has since merge into Oracle Corporation). Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have implementation dependencies as possible. Java programs are platform independent which means they can be run on any operating system with any type of processor as long as the Java interpreter is available on that system. Java code that runs on one platform does not need to be recompiled to run on another platform, it’s called “write once, run anywhere” (WORA). Java is as follows (Properties or Facts about Java):

1) Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model. 2) Platform Independent: unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. 3) Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master. 4) Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. 5) Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. 6) Portable: Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. 7) Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. 8) Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. 9) Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. 10) High Performance: With the use of Just-In-Time compilers, Java enables high performance. 11) Distributed: Java is designed for the distributed environment of the internet. 12) Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

PAGE

5

What you will need to run Java programe? JAVA JDK INSTALLATION:

1) Check the computer bit configuration. 2) Install the jdk verison you require & check the C DRIVE to see whether the java is installed or not. Change the path wether it's 64 or 32:  

C:\Program Files\Java\jdk1.6.0_31\bin C:\Program Files\Java\jdk1.6.0_22\bin

64 path 32 path

3) By using a sample programme you can : A-compile : javac ******.java B-RUN : java *****

WHAT IS ASOURCE CODE? A. Source code: DEFINITION: Is any collection of statements or declarations written in

some human-readable computer programming language. Source code is the mechanism most often used by programmers to specify the actions to be performed by a computer. Source code refers to the programming language one uses to write a program. There are hundreds, if not thousands, of forms of source code. Some computer languages include C++, Java, and Unix. Often people refer to source code of websites, which means programming conducted in HTML and possibly Java.

WHAT IS COMPILER? B. C++ /Java Compiler: DEFINITION: A compiler turns the program that you write in high level

language into an executable low level language ( binary format) that your computer can actually understand and run. A compiler is a special type of computer program that translates a human readable text file into a form that the computer can more easily understand. At its most basic level, a computer can only understand two things, a 1 and a 0. At this level, a human will operate very slowly and find the information contained in the long string of 1s and 0s incomprehensible. A compiler is a computer program that bridges this gap.

PAGE

6

Java Programme Structure? To understand structure and features of class I have used example of Hello Java program here. There is few lines in program and the major task of the program is to print “Hello Java” text.

 Compile Command: Javac  Run Command: Java

Programme output:

Hello Java

The above example has been used to print “Hello Java” on the screen.

PAGE

7

The First Simple program Explanation: public class Hello   

This creates a class called Hello. All class names required to start with a capital letter. The word public means that it is accessible by any other classes.

{…} The 2 curly brackets or phrases are used to group all the commands together so it is known that the commands belong to that class.

public static void main    

The word public means that it is accessible by any other classes. The word static means that it is unique. The word void means this main method has no return value. main is a method where the program starts.

You will notice that the main method code has been moved to some spaces left. This is called indentation which used to make a program easier to read and understand.

System.out.println(); This is a display command to display output.

PAGE

8

Java Virtual Machine (JVM) The Java Virtual Machine is called JVM, is an abstract computing machine or virtual machine interface that drives the java code. When we talk about the Java applications, then it works on those machines which is have JVM:     

JVM stands for Java Virtual Machine. JVM is the engine that drives the java code. Mostly in other Programming Languages, compiler produce code for a particular system but Java compiler produce Bytecode for a Java Virtual Machine. Bytecode is an intermediary language between Java source and the host system. It is the medium which compile java code to bytecode which get interpret on different machine and hence it makes it Platform/Operating system independent.

Note: JVM generates a .class (Bytecode) file, and that file can be run in any OS, but JVM should have in OS, because JVM is platform dependent.

PAGE

9

Platform Independent Java is called platform independent because of Java Virtual Machine. As different computers with different operating system have their own JVM, when we submit ‘.class‘ file to any operating system, JVM interpret the bytecode into machine level language.   

JVM is the main component of Java architecture and it is the part of the JRE (Java Runtime Environment). JVM is responsible to allocate the necessary memory needed by the java program. JVM is responsible to de allocate a memory space.

Just-in-time Compiler (JIT) JIT is the part of the Java Virtual Machine (JVM) that is used to speed up the execution time. JIT interpret parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for full interpretation.

PAGE

10

DATA TYPES IN JAVA DATA TYPE DEFINITION: A data type in programming language is a classification identifying one of various types of data such as floating-point number, fixed point number, text …..Etc. stating the possible values for that type, the operations that can be done on that type, and the way the values of that type are stored. Data Types available in java are:

1) Primary Data Type (Java supports 8 primitive data types): byte, short, int, long, float, double, char and boolean. There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a keyword. Let us now look into detail about the eight primitive data types.

2) Non-Primitive Data Types: string, array etc. List of the primary data type available in java? 1) 2) 3) 4)

integer short long float

5) 6) 7) 8)

double char string boolean

Example Programme that displays all data types: class DT{ public static void main(String args[]) { byte A= 5; short B = 20; int C = 30; long D = 60; float E = 20; double F = 20.123; boolean G = true; char H ='W'; System.out.println("Value Of byte Variable is " + A); System.out.println("Value Of short Variable is " + B); System.out.println("Value Of int Variable is " + C); System.out.println("Value Of long Variable is " + D); System.out.println("Value Of float Variable is " + E); PAGE

11

System.out.println("Value Of double Variable is " + F); System.out.println("Value Of boolean Variable is " + G); System.out.println("Value Of char Variable is " + H); } }

byte:  Byte data type is an 8-bit signed two's complement integer.  Minimum value is -128 (-2^7)  Maximum value is 127 (inclusive)(2^7 -1)  Default value is 0  Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.  Example: byte a = 100 , byte b = -50

short:  Short data type is a 16-bit signed two's complement integer.  Minimum value is -32,768 (-2^15)  Maximum value is 32,767 (inclusive) (2^15 -1)  Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int  Default value is 0.  Example: short s = 10000, short r = -20000

PAGE

12

int:  Int data type is a 32-bit signed two's complement integer.  Minimum value is - 2,147,483,648.(-2^31)  Maximum value is 2,147,483,647(inclusive).(2^31 -1)  Int is generally used as the default data type for integral values unless there is a concern about memory.  The default value is 0.  Example: int a = 100000, int b = -200000

long:  Long data type is a 64-bit signed two's complement integer.  Minimum value is -9,223,372,036,854,775,808.(-2^63)  Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)  This type is used when a wider range than int is needed.  Default value is 0L.  Example: long a = 100000L, long b = -200000L

float:  Float data type is a single-precision 32-bit IEEE 754 floating point.  Float is mainly used to save memory in large arrays of floating point numbers.  Default value is 0.0f.  Float data type is never used for precise values such as currency.  Example: float f1 = 234.5f

double:  double data type is a double-precision 64-bit IEEE 754 floating point.  This data type is generally used as the default data type for decimal values, generally the default choice.  Double data type should never be used for precise values such as currency.  Default value is 0.0d.  Example: double d1 = 123.4

PAGE

13

boolean:  boolean data type represents one bit of information.  There are only two possible values: true and false.  This data type is used for simple flags that track true/false conditions.  Default value is false.  Example: boolean one = true

char:  char data type is a single 16-bit Unicode character.  Char data type is used to store any character.  Example: char letterA ='A'

PAGE

14

Rules of declaring variables in Java  Variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and two special characters such as underscore and dollar Sign.  The first character must be a letter.  Blank spaces cannot be used in variable names.  Java keywords can not be used as variable names.  Variable names are case-sensitive.

Variable Definition in Java?

What is variable? Definition: it’s the quantity which may change during the execution of a programme & IT’S NOT CONSTANT. The variable can be integer, float, character, string…..etc. Variables are the identifier of the memory location, which used to save data temporary for later use. Every variable has a name, called the variable name, and a type called data type. A variable's data type indicates what sort of value the variable represents, such as whether it is an integer, a floating-point number, or a character.

PAGE

15

Types of Variable in Java There are three types of variables in Java:  Local variables  Instance variables  Class/Static variables

 Local variables: A variable that is declared within the method that is called local variables.

 Instance variables: A non static variable that is declared within the class but not in the method is called instance variable.

 Class/Static variables: A variable that is declared with static keyword in a class but not in the method is called static or class variable.

Example: class A { int amount=100; static int pin=2315;

//instance variable //static variable

void method() { int age=35;

//local variable

} }

PAGE

16

WHAT IS IDENTIFIRE IN JAVA? Definition:

Identifier is a name given to a variable, constant…..etc.

►WHAT IS DECLEARATION IN JAVA? Declaration means assigning A NAME or GIVING A NAME TO a CONSTANT & a VARIABLE or VALUE. That value can be a number, character, string (text or collection of characters),….etc. Definition:

WHAT IS CONSTANTS IN JAVA? Definition: The opposite of a variable is a constant. Constants are values that never change remains always constant fixed. Because of their inflexibility, constants are used less often than variables in programming. Definition 2: it’s the quantity which cannot change during the execution of a programme.

WHAT ARE COMMANDS IN JAVA? KEYWORDS or COMMANDS: Definition: Keywords are reserved words or PROGRAMMING COMMANDS. It has predefined meaning & it cannot be used as user defined name; that means it cannot be assigned by the user.

PAGE

17

Operators: All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. Operator Precedence Operators

Precedence

postfix

expr++ expr--

unary

++expr --expr +expr -expr ~ !

multiplicative

* / %

additive

+ -

shift

> >>>

relational

< > = instanceof

equality

== !=

bitwise AND

&

bitwise exclusive OR

^

bitwise inclusive OR

|

logical AND

&&

logical OR

||

ternary

? :

assignment

= += -= *= /= %= &= ^= |= = >>>=

The Simple Assignment Operator One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:

int cadence = 0; int speed = 0;

PAGE

18

The Arithmetic Operators The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only

symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result. Operator

Description

+

Additive operator (also used for String concatenation)

-

Subtraction operator

*

Multiplication operator

/

Division operator

%

Remainder operator

The Unary Operators The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

Operator

Description

+

Unary plus operator; indicates positive value (numbers are positive without this, however)

-

Unary minus operator; negates an expression

++

Increment operator; increments a value by 1

--

Decrement operator; decrements a value by 1

!

Logical complement operator; inverts the value of a boolean

The Equality and Relational Operators The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. == != > >= <
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF