computer chapter: 4 introduction to programming with c++ &...
TRANSCRIPT
-
Computer
Chapter: 4
Introduction to Programming with C++ & Java
[Till Pg. No. 75]
Learning Objectives
Introduction to object-oriented programming
Starting C++ with turbo C++ [Omit]
Starting Java with BlueJ
Components of a Program (Java)
Data types
Declaration & initialization of variables
Operators
Introduction to Object-Oriented Programming
All operations performed by a computer are controlled by computer programs. A
computer program is a program code which involves the use of a computer
programming language to write a series of instructions or algorithms.
The modular and structured approach to programming was followed before the
development of object-oriented programming. However, a need for new
methodology grew with the increasing size and complexity of programs. This gave
rise to the object- oriented programming (OOP) methodology which had the best
features of structured programming with several new concepts.
-
In an object-oriented programming language like C++ and Java, the data and the
functions are defined that act upon the data. The major features of object-oriented
programming are:
Object Class
Data Hiding Data Abstraction
Encapsulation Polymorphism
Inheritance
OBJECT
An object is the basic element of object - oriented programming. Let us look at
some of the real - world entities or objects around us - the trees, people, animals,
birds, even your computer, a mug or a spoon - all are examples of objects. Each
object has its own set of characteristics and behaviors.
For example, let us consider a plant. Its characteristics would be the name, color of
its leaves, its type, flowering or non - flowering and so on. And, its behaviour
would be - producing flowers, producing fruits, shedding leaves and so on.
Similarly, the characteristics of a computer will be - its type, size, speed, amount
of RAM and so on. And its behavior will include - processing data, playing music,
showing images, playing movies and so on. Hence, we can say that an object
encapsulates characteristics and behaviour.
Here, the plant belongs to living things category. As plants and animals are objects
belong to the type of living things. So, living things is called a class here.
An object in object - oriented programming, comprises of data and code that
operate on that data. In other words, an object can be defined as a group of data
members or attributes as characteristics and related methods, routines or
member functions as its behavior. One particular object is called an instance.
CLASS
-
A group of objects that share similar characteristics (attributes) and behaviour
(methods) form a class. As explained in the above example, the plant is an object
and it belongs to the living things class. Let us take another example, consider an
animal. One way to visualize an animal is through its specie, its color, its weight,
its height and so forth. Another way is to think about what it does: it moves, it
eats, and it produces sound and so on. Therefore, the class of an animal
encapsulates its various attributes and its functions together into a single collection
called an object. A program can contain any number of classes.
DATA HIDING
The object can maintain private data and methods that can be changed at any time
without affecting the other objects that depend on it. This is called data hiding or
information hiding. The public data and methods are accessible to all the classes
in the program. And the private data and methods are accessible only within the
class in which they are declared and remain hidden from all the other classes in the
program.
DATA ABSTRACTION
Data abstraction can be defined as a process through which the programmer hides
all but the relevant data about an object. This reduces complexity and increases
productivity. We can also say that abstraction also defines an interface for our
applications.
ENCAPSULATION
Encapsulation, closely related to data hiding, allows binding of code and the data
together into a class) and restricts any outside entity from misusing them. A class
in the object - oriented programming is an example of encapsulation.
POLYMORPHISM
Poly means many, whereas, morph means forms. Polymorphism in a
-
programming language is the ability to make use of objects time and again without
knowing their exact type at the compile time. You know that a class is a collection
of data members and the member functions that operate on these data members.
Since polymorphism refers to the same name given to many forms, these forms
may be classes or functions.
A very simple real life example of polymorphism would be that of a person who
could speak various languages, such as Hindi, English and Malayalam. Here, the
act of speaking is the method. However, considering this particular person
(object), this method (speaking) would have various forms - speaking Hindi,
speaking English or speaking Malayalam.
INHERITANCE
Inheritance is a feature of a programming language in which one object can attain
classes. Like, multiple classes can be created in other programs. This might result
in similar classes being defined across different programs, to handle similar
requirements. Therefore, to extend new classes from existing ones, the
programming language has the feature of inheritance, in which one class can be
derived from another existing class, leading to the reuse of existing code. This
feature again reduces complexity and increases productivity.
Starting JAVA with BlueJ
BlueJ is a Java integrated development environment (IDE), specifically designed
for teaching at an introductory level. It was designed and implemented by the
BlueJ team at Monash University at Melbourne in Australia, and the University of
Southern Denmark at Odense. It can be freely downloaded from
http://www.bluej.org/.
http://www.bluej.org/
-
To start BlueJ, follow the steps given below.
Step 1: Click on the Start button All Programs BlueJ BlueJ.
Or
Double-click the shortcut icon of BlueJ located on the desktop. The
BlueJ window will appear on the screen (Fig. 1).
Fig. 1: BlueJ Window
You need to create a Project in order to write a Java program in BlueJ.
Step 2: Click on the Project New Project…(Fig. 2). A New Project dialog
box will appear where you can set the path and the name for your
project (Fig. 3).
-
Fig. 2 New project option of the Project menu
Fig. 3 New Project dialog box
Step 3: Click on the Create/ Choose button (Fig. 3). This will create your folder
at the location mentioned and open the project window.
Step 4: The project window has one file by default. This is a readme file where
you can record your notes. Just double-click on the icon to open the
file (Fig. 4).
-
Fig. 4 Project window with readme file
Fig. 5 Readme editor window
Step 5: An editor window will appear where you can type text. Click on the
Close button to close the file once you are done (Fig. 5).
Step 6: Now, to create a class in your project, click on the New Class... button
(Fig. 6).
-
Fig. 6 Selecting New Class
Or
Select Edit New Class… option.
A Create New Class dialog box will appear where you can type the
name for your class (Fig. 7).
Step 7: Click on the OK button (Fig. 7). This will bring a new icon in the
project window. This icon will denote the new class created. This
class file will contain the default code. Also, the stripes on the file
icon tell that the file has not been compiled even once (Fig.8 ).
-
Fig. 7 Create New Class dialog box
Fig. 8 New icon created for Class FirstJavaProgram
Step 8: Double-click on the file icon to open the file. It will open in the editor
window. Here, you can make the desired changes or you can delete the
default code and write your own code afresh (Fig. 9).
-
Fig. 9 Program template in BlueJ
Step 9: Type the sample program code (Fig. 10).
public class FirstJavaProgram
{
public static void main()
{
System.out.println(“I like JAVA programming”);
}
}
Fig. 10 Sample program in the Editor window of Class FirstJavaProgram
-
Fig. 11 Saving the Class
Step 10: Click on the Class Save option to save the code (Fig. 11).
Structure of JAVA Program
Let us examine the sample program (Fig. ) for creating a Class in JAVA to
understand the basic structure of a JAVA program.
public class FirstJavaProgram
It declares a class called FirstJavaProgram
public static void main()
It declares a method called main(). Most of the actual code in Java is
found within methods. This method or function is the parent function of
all the functions in Java. It is executed when the Class FirstJavaProgram
is executed using the Java command.
System.out.println(“I like JAVA programming”);
It prints “Ilike JAVA programming” to the output screen. println means
string or text provided in the brackets and then add a line break, like the
enter key.
The remaining lines having opening and closing curly brackets or braces
close the method and the class.
-
Compiling a JAVA Program
After you write the source code in BlueJ, next step is to compile the code
and check for errors, if any. To compile a program source file, follow the
steps given below.
Step 1: Click the Compile button (Fig. 12).
Or
Right-click on the class file FirstJavaProgram icon and click on the
Compile option from the context menu.
After compilation, the stripes will disappear from the icon (Fig. 13).
Fig. 12 Program after compilation
-
Fig. 13 Compile class file
Running a JAVA Program
After you have compiled your code successfully without any errors, you can
execute it.
To observe the output of the code, follow the steps given below.
Step 1: Right click on the class file FirstJavaProgram icon and select the void
main() option (Fig. 14).
Step 2: A method call will be made to the main function and the output will
appear in the Terminal Window (Fig. 15).
Fig. 14 Right-click the Class icon Fig. 15 Program output
-
Tokens
A token is the smallest individual unit of a program. C++ and Java support the
following types of tokens.
Keywords
Identifiers
Constants
Punctuators
Comments
Operators
Keywords
Keywords are the reserved words that form the vocabulary of any programming
language. Hence, they are also known as reserved words. They have special
meanings and usage. C++ and Java keywords are case-sensitive and should be
typed in lowercase only. Some examples of keywords are int, do, return, if and
continue.
The keywords have special meanings to the language compiler. These reserved
words are meant for special purposes only and should not be used as identifiers.
Identifiers
An identifier is a sequence of characters (letters, numbers and underscore) that we
create to denote a name to any class, object or function.
Rules to create identifiers
Identifiers are case sensitive
An identifier cannot be a keyword or true or false, or null.
-
An identifier can consist of letters, digits 0-9, the underscore, or the dollar
sign.
An identifier must start with a letter, an underscore, or a dollar sign.
Identifier cannot start with a digit but digits can be used after the first
character.
We cannot use symbols or spaces in the names of the identifiers.
Naming Conventions
Identifiers should be meaningful. For example, if an identifier is going to
store the value of a student’s fee, it should be ideally named as “studentfee”
than simply “f” though is correct.
If more than one word is used in the name of a variable, first word should be
all small case and the first letter of the consequent words should be capital
like studentName, dateOfBirth and so on.
The names of the public methods and instance variables should begin with
lower case letter.
Private and local variables should use lower case letters, for example,
areacircle, tot_marks and so on.
Class names should be named using all uppercase letters and an underscore,
for example, MAX_VAL, TOTAL and so on.
Data Types
Data in any programming language is handled in a systematic manner. For this
purpose, it is divided into various types. C ++ and Java too defines its data into
various types. Some of the data types supported by C ++ and Java are- void, char,
int, float and double. Data types are initialized to some default values when they
-
are declared. The table 1 given below lists some of the common data types
available in C ++ and Java.
Table1: Some common data types available in C++ and Java
Data type Description Storage
void Void or Null 0 byte
char A single character 1 byte
int Integer 4 bytes
float Single precision floating point (that is, can
display 7 digits after the decimal point)
4 bytes
double Double precision floating point (that is, can
display 15 digits after the decimal point)
8 bytes
VARIABLES AND CONSTANTS
Variables are the names that represent or store constant values. For example, age =
16. Here, 16 is the constant value which is stored in the variable named age.
As the name suggests, a variable may change its value from time to time.
Therefore, we can define a variable as a memory location (s) that is named and
which is used to store a constant. Hence, these memory locations store a value of
certain type. The variable may store its value in one or more cells depending upon
the type of the value.
When a variable is defined in a program, the compiler determines its data type
(integer, float, character and so on) and sets aside the appropriate amount of
memory for the value of the variable to be stored. Suppose, a variable named
my_var is of float type (which is four bytes long) and as each cell is one byte
-
large, the compiler for this variable will set aside four bytes of memory.
It is now clear that variables have a name (identifier), a type (data type), and a
value. Before we try to use a variable, we have to declare and initialize it. When
we declare a member of a class as static, it means no matter how many objects of
the class are created, there is only one copy of the static member.
Declaring Variables
Variables have a significant role in programming as their declaration allows
programmers to write flexible programs. Instead of entering data directly into a
program, a programmer can use variables to represent the data. During the
program execution, the variables are replaced with real data. This makes it
possible for the same program to process different sets of data. A variable in C ++
and Java is declared by specifying its data type.
The syntax to declare a variable in C ++ and Java is as follows:
data_type variable_name;
Example :
int age;
float marks;
Note that several variables of the same data type can be declared in the same line
separating the variable identifiers with commas.
Example :
int x, y, z;
The above statement has exactly the same meaning as:
-
int x;
int y;
int z;
Initialisation of Variables
After a variable is declared, it could be assigned some value. This is accomplished
using the assignment operator (=).
The syntax is as follows:
data_type variable_name;
variable_name = value;
When a variable is declared and assigned a value in single statement, it is
initialised.
data_type variable_name = value;
For example,
Data Type Variable Name Assignment Operator Value
Multiple variables can be declared and initialized in a single statement, as shown
below.
For example, int weight = 32, height = 160;
It is not mandatory to initialize all the variables when they are declared.
int age = 13
-
For example, int weight, height = 160;
Operators
Operators help in forming a defined link between the variables and constants. The
variables and constants are called operands. The number of operands required by
the operator can classify operators. For example, unary operators have only one
operand (for example, -1, +40) and binary operators have two operands required
operator and operands together form an expression.
There are many types of operators defined in C ++ and Java. Some of them are as
follows:
Arithmetic Operators (+, -, *, /, % )
Relational Operators (=, ==, ! =)
Logical Operators (||, &&, !)
Assignment Operator (=)
Let us learn about them in detail.
Arithmetic Operators (+, -, *, /, %)
Arithmetic operators are used in mathematical expressions. The table 2 given
below lists all the arithmetic operators.
Table 2: Arithmetic Operators
Operator Name Example with X=20
& Y=10
Description
+ Addition or
Unary plus
X+ Y will return 30 Adds value on either side of the
operator
- Subtraction or Unary minus
X-Y will return 10 Subtracts right hand operand from the left hand operand
* Multiplication X*Y will return 200 Multiplies values on either side
-
of the operator
/ Division X/Y will return 2 Divides left hand operand by
right hand operand and returns
quotient
% Modulus X%Y will return 0 Divides left hand operand by right hand operand and returns
remainder
Relational Operators (=, ==, !=)
Relational operators are used to compare two expressions. The result can be either
true or false. The table 3 below lists all the relational operators available in C++
and Java.
Operator Name Example with X=20
& Y=10
Description
< Less than X= Greater or equal
than
X>=Y will return TRUE Compares both the operands
and returns true if the left
operand is greater than or equal
to the right operand, otherwise returns false
-
== Equal to X==Y will return
FALSE
Compares both the operands
and returns true if both the
operands are equal, otherwise returns false
!= Not equal to X!=Y will return TRUE Compares both the operands and returns true if both the
operands are not equal,
otherwise returns false
Logical Operators (||, &&, !)
The function of logical operators is to join more than one condition or expression
and return either true or false as result. The table 4 given below lists all the logical
operators available in C++ and Java.
Operator Name Example with
X=20, Y=10 & Z=
30
Description
|| OR X>Z || X>Y will return
TRUE
Combines expressions and returns true if
one or all the expressions are true, otherwise returns false
&& AND X>Z && X>Y will return FALSE
Combines expressions and returns true if all the expressions are true, otherwise returns
false
! NOT !(X>Z && X>Y) will
return TRUE
It has only one operand located at its right.
It returns the opposite result of evaluating
its operand. It means that this operator inverts the value of its operand, producing
false if its operand is true and true if its
operand is false
-
Assignment Operator (=)
The assignment operator (=) is used to assign a value to a variable. This variable
may be of any type.
For example,
A = 110;
The above expression assigns integer value 110 to variable ‘A’.
The expression on the left of the assignment (=) operator is known as lvalue (left
value) and the one on the right is called rvalue (right value). lvalue must always be
a variable whereas rvalue is either a constant, a variable, the result of an operation
or any combination of them.
Note that the assignment operation always takes place from right to left and not
vice versa.
For example, in statement a=b; the value of variable b (rvalue) is assigned to
variable a (lvalue).
Standard Input/Output Streams in Java
Java programs also perform input-output operations through streams. InputStream
is used for input operation and OutputStream is used for output operations. Both
the streams are defined in java.io.package.
In order to make all the classes of a package available to a program available to a
program, the syntax is:
Import .*;
For example: import java.io;
-
The java.io package contains almost every class might ever need to perform an
input-output operation in Java programs.
System.out.println() displays messages and/or values of the variables and/or result
of an expression to the command window.
In this statement:
System is a class defined within the java.lang package.
out is a public static member of the System class.
println() is a method that accepts an expression as an argument and displays
it in String form to the standard output window.
You can also use System.out.print() in place of System.out.println(). The
difference between the two is as follows:
System.out.println() adds a new line to the end of the output. It places the cursor
on a new line.
Example:
System.out.println(“1”);
System.out.println(“2”);
System.out.println(“3”);
Output:
1
2
3
Example:
System.out.print(“1”);
System.out.print(“2”);
-
System.out.print(“3”);
Output:
123
Omitted Pages:-
57, 58, 59, 60, 61[Fig. 10 & Fig. 11],
68 [instance variables, class variables, local variable],
72 [From Standard Input/output Streams in C++], 73, 74 [Eg:9 & 10]
-
Textbook Exercise
Ex: A. Tick the correct option.
1. An identifier can denote ________.
a. Variable name
b. Class name
c. Function name
d. All of these
2. Which of the following statements is correct?
a. Identifiers can be made up of letters, digits and the underscore (_)
character.
b. Identifiers can use symbols such as ? or %.
c. Spaces are permitted inside identifiers.
d. Identifiers are not case sensitive.
3. Which operator is used to assign a value to a variable?
a. Arithmetic
b. Assignment
c. Relational
d. None of these
4. Which operator combines test conditions?
a. Compound operator
b. Equals operator
c. Complex operator
d. Logical operator
5. Omit
-
Ex: B. Fill in the blanks
1. The smallest individual unit in a program is known as ________.
2. Omit
3. A class is a group of objects that share similar ________ (attributes) and
behavior (methods).
4. Omit
5. Omit
Ex: C. Write True or False
1. Relational operators are used to combine two or more conditional
statements.
2. Keywords are not case sensitive and they can be typed in any case.
3. The java.io.package contains almost every class that you might need to
perform an input-output operation in Java programs.
4. In Java, System.out.println doesn’t adds a new line to the end of the output.
5. The assignment operation always takes place from left to right.
Ex: D. Match the columns.
Column A Column B
1 !(30 == 30) a True
4 int b False
5 30 != 50 c Data type
Ex: E Answer the following questions.
1. Name the main features of object-oriented programming.
2. Omit
3. Omit
-
4. Omit
5. How are variables declared and initialized in Java? Give syntax and
example of it.
Textbook Exercise Solution
Ex: A. Tick the correct option.
1. d: All of these
2. a: Identifiers can be made up of letters, digits, and the underscore (_)
character.
3. b: assignment
4. d: Logical operator
5. Omit
Ex: B. Fill in the blanks
1. Token
2. Omit
3. Characteristics
4. Omit
5. Omit
Ex: C. Write True or False
1. False
Correct Statement:
Logical operators are used to combine two or more conditional statements.
-
2. False
Correct Statement:
Keywords are case sensitive and they can be typed in any case.
3. True
4. False
Correct Statement:
In Java, System.out.println adds a new line to the end of the output.
5. False
Correct Statement:
The assignment operation always takes place from right to left.
Ex: D. Match the columns.
1- b
2-omit
3-omit
4-c
5-a
Ex: E Answer the following questions [Given during class]
Learn the following boxes from the textbook:-
Tech Terms [No. 8 Omit]
Recall Time [No. 4 omit]
Smart Byte [Pg. no. 67]
Table 1 [Pg. No. 67]
-
Table 2 [Pg. No. 70]
Table 3 [Pg. No. 70 & 71]
Table 4 [Pg. No. 71]
[Note: Values of Example in table 2, 3 & 4 can change]