Вы находитесь на странице: 1из 52

CMP-2123-Object Oriented

Programming
Lecture 2
By
Mohammad Noman
Today’s Topics
• Data Types
• JavaTokens
• Variables

2
Data Types
•Data type specifies the size and type of values that can be
stored in an identifier. The Java language is rich in its data
types. Different data types allow you to select the type
appropriate to the needs of the application.
•Data types in Java are classified into two types:
•Primitive—which include Integer, Character, Boolean, and
Floating Point.
•Non-primitive—which include Classes, Interfaces, and
Arrays.

3
Primitive Data Types
• Integer
•Integer types can hold whole numbers such as 123 and
−96. The size of the values that can be stored depends
on the integer type that we choose.

4
•The range of values is calculated as −(2n−1) to (2n−1)−1; where
n is the number of bits required. For example, the byte data
type requires 1 byte = 8 bits. Therefore, the range of values
that can be stored in the byte data type is −(28−1) to (28−1)−1
= −27 to (27) -1
= −128 to 127
• Floating Point
•Floating point data types are used to represent numbers
with a fractional part. Single precision floating point
numbers occupy 4 bytes and Double precision floating
point numbers occupy 8 bytes. There are two subtypes:

5
• Character
•It stores character constants in the memory. It assumes a size
of 2 bytes, but basically it can hold only a single character
because char stores unicode character sets. It has a minimum
value of ‘u0000’ (or 0) and a maximum value of ‘uffff’ (or
65,535, inclusive).
• Boolean
•Boolean data types are used to store values with two states:
true or false.
6
Java Tokens
•A token is the smallest element in a program that is
meaningful to the compiler. These tokens define the
structure of the language. The Java token set can be divided
into five categories: Identifiers, Keywords, Literals,
Operators, and Separators.
• Identifiers
•Identifiers are names provided by you. These can be
assigned to variables, methods, functions, classes etc. to
uniquely identify them to the compiler.

7
• Keywords
•Keywords are reserved words that have a specific meaning
for the compiler. They cannot be used as identifiers. Java
has a rich set of keywords. Some examples are: boolean,
char, if, protected, new, this, try, catch, null, threadsafe etc.

• Literals
•Literals are variables whose values remain constant
throughout the program. They are also called Constants.
Literals can be of four types. They are:

8
• StringLiterals
• String Literals are always enclosed in double quotes and are
implemented using the java.lang.String class. Enclosing a
character string within double quotes will automatically create
a new String object. For example,
• String s = “This is astring”;
• String objects are immutable, which means that once created, their
values cannot be changed.
• CharacterLiterals
• These are enclosed in single quotes and contain only onecharacter.

• Boolean Literals
• They can only have the values true or false. These values do
not correspond to 1 or 0 as in Cor C++.

9
• Numeric Literals
• Numeric Literals can contain integer or floating point values.

• Operators
• An operator is a symbol that operates on one or more operandsto
produce a result.

• Separators
• Separators are symbols that indicate the division and arrangement of
groups of code. The structure and function of code is generally
defined by the separators. The separators used in Java are as follows:

10
• parentheses ( )
• Used to define precedence in expressions, to encloseparameters
in method definitions, and enclosing casttypes.

• braces { }
• Used to define a block of code and to hold the values of arrays.

• semicolon ;
• Used to separate statements.

11
• comma ,
• Used to separate identifiers in a variable declaration and in the
for statement.

• period .
• Used to separate package names from classes and subclasses
and to separate a variable or a method from a reference
variable.

12
Variables
1. Instance Variables (Non-Static Fields)

•Objects store their individual states in “non-static


fields”, that is, fields declared without the static
keyword
•Non-static fields are also known as instance variables
because their values are unique to each instance of a class.
For example, the currentSpeed of one bicycle is
independent from the currentSpeed of another.

14
2. Class Variables (Static Fields)
•A class variable is any field declared with the static modifier;
this tells the compiler that there is exactly one copy of this
variable in existence, regardless of how many times the class
has been instantiated. A field defining the number of gears
for a particular kind of bicycle could be marked as static
since, conceptually, the same number of gears will apply to
all instances. The code
• static int nymGears = 6
would create such a static field.

15
3. Local Variables
• A method stores its temporary state in local variables. The syntax for
declaring a local variable is similar to declaring a field
• (for example, int count = 0; )
• There is no special keyword designating a variable as local; that
determination comes entirely from the location in which the variable
is declared—between the opening and closing braces of a method. As
such, local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class.

4. Parameters
• They are the variables that are passed to the methods of a class.

16
Variable Declaration
• Identifiers are the names of variables. They must be composed of
only letters, numbers, the underscore, and the dollar sign ($). They
cannot contain white spaces. Identifiers may only begin with a
letter, the underscore, or the dollar sign. A variable cannot begin
with a number. All variable names are case sensitive.

Syntax for variable declaration

• datatype1 variable1, datatype2 variable2, … datatypen variablen;


• For example:
• int a, char ch;

17
Initialization

• Variables can be assigned values in the following way:


variableName =value;
• For example
ch =‘a’;
a =0;

18
Operators
• Operator in java is a symbol that is used to perform operations. There
are many types of operators in java such as unary operator, arithmetic
operator, relational operator, shift operator, bitwise operator, ternary
operator and assignment operator.

2
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 = += -= *= /= %= &= ^= |= <<= >>= >>>=
3
Java If-elseStatement
• The Java if statement is used to test the condition. It checksboolean
condition: true or false. There are various types of if statement in
java.
• if statement
• if-else statement
• nested if statement
• if-else-if ladder

21
Java IFStatement
• The Java if statement tests the condition. It executes the if blockif
condition is true.
• Syntax:

22
23
24
Java IF-elseStatement
• The Java if-else statement also tests the condition. It executes the if
block if condition is trueotherwise else block is executed.
• Syntax:

25
26
27
Java IF-else-if ladderStatement
• The if-else-if ladder statement executes one condition from multiple
statements.
• Syntax:

28
29
30
31
Java SwitchStatement
• The Java switch statement executes
one statement from multiple
conditions. It is like if-else-if ladder
statement.
• Syntax:

32
33
34
Java Switch Statement isfall-through
• The java switch statement is fall-through. It means it executes all
statement after first match if break statement is not used with switch
cases.

35
36
JAVAMethods
• A Java method is a collection of statements that are grouped together
to perform an operation. When you callthe
System.out.println() method, for example, the systemactually
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 programdesign.

37
Creating Method

38
• The syntax shown includes −
• modifier − It defines the access type of the method and it is optional
to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature
consists of the method name and the parameterlist.
• Parameter List − The list of parameters, it is the type, order, and
number of parameters of a method. These are optional, methodmay
contain zero parameters.
• method body − The method body defines what the method doeswith
the statements.

39
• Here,
• public static − modifier
• int − return type
• methodName − name of the method
• a, b − formal parameters
• int a, int b − list of parameters
• Method definition consists of a method header and a method body.

40
41
• Here is the source code of the above definedmethod
called minFunction(). This method takes two parameters n1 and n2 and
returns the minimum between the two −

42
Method Calling
• For using a method, it should be called. There are two ways in which a
method is called i.e., method returns a value or returning nothing (no
return value).
• The process of method calling is simple. When a program invokes a
method, the program control gets transferred to thecalled method.
This called method then returns control to the caller in two
conditions, when −
• the return statement isexecuted.
• it reaches the method ending closingbrace.

43
• The methods returning void is considered as call to a statement. Lets
consider an example −

• The method returning value can be understood by the following


example −

• Following is the example to demonstrate how todefine a method and


how to call it −
27
44
• This will producethe
following result −

45
The void Keyword
• The void keyword allows us to create methods which do not return a
value. Here, in the following example we're considering a void
method methodRankPoints. This method is a void method, which
does not return any value. Call to a void method must be astatement
i.e. methodRankPoints(255.7);. It is a Java statement which ends with
a semicolon as shown in the following example.

46
• This will
produce the
following
result −

47
Passing Parameters by Value
• While working under calling process, arguments is to be passed.
These should be in the same order as their respective parameters in
the method specification. Parameters can be passed by value or by
reference.
• Passing Parameters by Value means calling a method with a
parameter. Through this, the argument value is passed to the
parameter.

48
• The following program shows an example of passing parameter by
value. The values of the arguments remains the same even after the
method invocation.

49
i
n

50
• This will produce the following result −

51
Thank You

Вам также может понравиться