0% found this document useful (0 votes)
6 views

Actual Chap2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Actual Chap2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

4/16/2024

University of Buea
Faculty of Engineering and Technology
Department of Computer Engineering Course outline

CEF 346 Chapter 2: Overview of Java Language


• Introduction
OBJECT ORIENTED PROGRAMMING • Java Basics (data types, keywords, comments, expressions, operators etc.)
• Conditional Statements, Loops and Arrays
Java, C++ • Classes and Objects in Java (new, constructor, attributes, methods,
Chapter 2 creating classes and objects, access modifiers)
By Dr. Eng. Ines DJOUELA • Packages and interfaces
M. Nelson TIYDZE • The Java API Documentation

[email protected]
2

Basic of Java programming


Basic of Java programming
a simple java program
• A Java program
– Consists of classes (existing ones and/or new ones)
– Has one class with a main method (to start the program)
• Syntax of a class
– Comments and embedded documentation
– Import from libraries (by default: java.lang.*)
– Class declaration: collection of variables and methods
• Compiling and running
– javac Hello.java
– java Hello 3 4

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 1
4/16/2024

Java Basic
Basic of Java programming
Java comments
• The java comments are statements that are not executed by
the compiler and interpreter.
• The comments can be used to provide information or
explanation about the variable, method, class or any
statement. It can also be used to hide program code for
specific time.
• Three types of comments:
 Single line comment
 Multi Line comment
 Documentation comment

5 6

Java Basic Java Basic


Java comments 1. Variables: definitions
• A variable is a name of memory location.
• Single line comment: used to comment a single line of code • The scope of a variable defines the section of the code in which the
Syntax: //This is single line comment variable is visible.
• Multi Line comment: used to comment multiple lines of code • The lifetime of a variable refers to how long the variable exists before it
is destroyed.
Syntax: /* This is • Destroying variables refers to deallocating the memory that was
multi line comment
*/ allotted to the variables when declaring it.
• Documentation comment: used to create documentation API. • As a general rule, variables that are defined within a block are not
accessible outside that block. Thus, variables that are declared in the
Syntax: /** This is body of a method are different from those that are declared in the class
documentation comment itself.
*/
• There are three types of variables in Java: instances variables, Local
variables ((i) argument and (ii)local variables), and static variables
7 8

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 2
4/16/2024

Java Basic Java Basic


Instance variables Argument variables
• They are those that are defined within a class itself and not in any
method or constructor of the class. • These are the variables that are defined in the header of the
• They are known as instance variables because every instance of the constructor or a method.
class (object) contains a copy of these variables. • The scope of these variables is the method or constructor in which
• The scope of instance variables is determined by the access specifier they are defined.
that is applied to these variables. • The lifetime is limited to the time for which the method keeps
• The lifetime of these variables is the same as the lifetime of the executing.
object to which it belongs. • Once the method finishes execution, these variables are
• Object once created do not exist for ever. They are destroyed by the destroyed.
garbage collector of Java when there are no more reference to that
object. 9 10

Java Basic Java Basic


Local variables Static variables
• A local variable is the one that is declared within a method or a
constructor (not in the header). • If you declare any variable as static, it is known static variable.
• The scope and lifetime are limited to the method itself. • The static variable can be used to refer the common property of all
objects (that is not unique for each object)
• One important distinction between these three types of variables
is that access specifiers can be applied to instance variables only e.g.: company name of employees, college name of students etc.
and not to argument or local variables. • The static variable gets memory only once in class area at the time
• In addition to the local variables defined in a method, we also have of class loading.
variables that are defined in blocks (e.g.: if …else block). The • Advantage of static variable: It makes your program memory
scope and is the same as that of the block itself. efficient (i.e. it saves memory).

11 12

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 3
4/16/2024

Java Basic Java Basic


Variables: Recap Constants in java
• Instance variables: They are variables that are • A constant is a variable which cannot have its value changed after
declared inside the class, but outside the
method. It is not declared as “static”. declaration. It uses the “final” keyword.
• Local variables: They are variables which are Syntax:
declared inside the method but not in the  Modifier final dataType variableName = value; //global constant
 Modifier static final dataType variableName = value; //constant
header. within a c
• Argument variables: They are local variables
which are declared inside the header of the e.g.: public final int age = 15;
method or constructor. Public static float weight = 23.54;
• Static variables: A variable that is declared as
static is called static variable. It cannot be local.
13 14

Operators Expressions statement


• Operator in java is a symbol that is • Expression is an essential building block of any Java program.
used to perform operations. Generally, it is used to generate a new value. Sometimes, we can also
E.g.: +, -, *, / etc. assign a value to a variable.
• There are many types of operators • In Java, expression is the combination of values, variables, operators,
in java which are given below:
Unary operator,
and method calls.
Arithmetic operator,
Shift operator,
Relational operator,
Bitwise operator,
Logical operator,
Ternary operator and
Assignment operator.
15 16

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 4
4/16/2024

Java Basic Java Basic


2. Data type Data Fields Types
• The default value of a data field is null for a reference type, 0 for
a numeric type, false for a boolean type, and '\u0000' for a char
type.
• Data fields types or data types
• However, Java assigns no default value to a local variable inside
represent the different values to be
a method.
stored in the variable.
• In java, there are two types of data • The data fields can be of reference types. For example, the
types: following Student class contains a data field name of the String
 Primitive datatypes type. public class Student {

Non-primitive datatypes. String name; // name has default value null


int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has
default value false
char gender; // c has default value '\u0000'
17 18
}

Data field type Data field type


Primitive types Primitive types
• char: used to declare a variable • float: used to declare a
that can hold unsigned 16-bit variable that can hold a
Unicode characters 32-bit floating-point
• int: used to declare a variable that number.
can hold a 32-bit signed integer.
• byte: used to declare a
• long: used to declare a variable variable that can hold 8-bit
that can hold a 64-bit integer. data values.
• short: used to declare a variable
that can hold a 16-bit integer
• double: used to declare a variable
that can hold 64-bit floating-point
number.
19 20

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 5
4/16/2024

Data field type Data field type


Primitive types Non-Primitive types: String
• String is basically an object that represents sequence of char
values.
• An array of characters works same as java string.
For example: 1. char[] ch={'j','a','v','a','t','p','o','i','n','t’};
2. String s = new String(ch); is same as:
3. String s = "javatpoint";

• Java String class provides a lot of methods to perform operations


on string such as compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.
• The java.lang.String class implements Serializable, Comparable
and CharSequence interfaces.
21 22

Data field type Data field type


Non-Primitive types: Array Non-Primitive types: Array

• An array is used to store a collection of data, but it is often more useful


to think of an array as a collection of variables of the same data type.
• An array is an object in Java, which means it can be assigned to a
variable, passed as a parameter to a method, and returned as a value
from a method
• To use an array in a program, you must declare a variable to reference
the array, and you must specify the type of array the variable can
reference.
Syntax:

23 24

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 6
4/16/2024

Data field type Data field type


Non-Primitive types: Array Non-Primitive types: Array
• Creating Arrays: You can create an array • Alternatively you can create arrays as
by using the new operator. follows:
Syntax:

• The array elements are accessed through


• Declaring an array variable, creating an the index. Array indices are 0-based; that
array, and assigning the reference of the is, they start from 0 to arrayRefVar.length-
1.
array to the variable can be combined in
• E.g.: The following statement declares an
one statement, as follows: array variable, myList, creates an array of 10
Syntax: elements of double type and assigns its
reference to myList.
25 26

Java Basic
Declaration and creation of objects- reminder 2. Constructor
• A constructor in java is a special type of method that is used to
initialize the object.
• Java constructor is invoked at the time of object creation using
the keyword “New”. It constructs the values i.e. provides data
for the object, that is why it is known as constructor.
• There are basically two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. Constructor must have no explicit return type- not even
void
27 28

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 7
4/16/2024

Java Basic Java Basic


2. Types of Constructors 2. Types of Constructors

• There are two types of constructors:


1.Default constructor (“no-arg”): It is a 2. Parameterized constructor
constructor that have no parameter. • It is a constructor that has one or
many parameters as arguments.
Even if you haven't specified any • It can take as many arguments as
constructor in the code, the Java possible.
compiler calls a default constructor. e.g. The class student has a
Syntax: <class_name>(){} constructor with two parameters

29 30

Java Basic Tutorial: Updating our class “Dog”


Constructors overloading
• Rewrite the class dog adding two main
constructors:
• Constructor overloading is a - One with all the parameters (data fields),
technique in Java in which a class
can have any number of - The second one with only color and height
constructors that differ in as parameters.
parameter lists. • Create two dogs: “Bobby” that has all the
• The compiler differentiates these parameters of the picture, and “Doddo”
constructors by considering the that provides only his color (set to brown)
number of parameters in the list and his eye color (set to gray).
and their type. • Create the method display that will display
each dog.
31 32

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 8
4/16/2024

Access modifiers (1/5) Access modifiers (2/5)

• The access modifiers in java specifies 1. A private member within a class/method


accessibility (scope) of a data member, denotes that only members of the same
method, constructor or class. class/method have accessibility. The private
• There are four (04) types of java access member is inaccessible from outside the
modifiers: class/method.
Private • Public getter (Accessor) and setter
Public (Mutator) methods are used to read and
Protected and modify private properties.
Default

33 34

Access modifiers (3/5) Access modifiers (3/5)


Rules for private access modifier Rules for private access modifier
• Making data fields private protect data.
• Making data fields private helps to make code • A getter method is also referred to as
easy to maintain since the client programs an accessor and a setter to a mutator.
cannot modify them.
• To prevent direct modifications of data fields, • E.g.: This is an example of setter and
declaring the data fields private is known as getter for the private variable name
data field encapsulation.
• To make a private data field accessible,
provide a getter method to return its value.
• To enable a private data field to be updated,
provide a setter method to set a new value.
• A getter method is also referred to as an
accessor and a setter to a mutator.
35 36

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 9
4/16/2024

Access modifiers (4/5) Access modifiers (5/5)

2. Public members are accessible from 4. A Default member: If you don't use any modifier, the member
outside the class. (class, method, etc.) is treated as default by default.
PS: Using the modifiers public and private on local • The default modifier is accessible only within package.
variables would cause a compile error.

3. A protected access specifier is a stage


between private and public access. If
member functions defined in a class are
protected, they cannot be accessed from
outside the class but can be accessed from
the derived class.
37 38

keywords in Java “This” keyword in Java

• There can be a lot of usage of Java “this” keyword. In Java, “this”


There are many keywords used in java. is a reference variable that refers to the current object.
• This • Here is given the six usage of java “this” keyword.
• Super
• Final 1. this can be used to refer current class instance variable.
• Abstract 2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from
39
the method. 40

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 10
4/16/2024

Classes, methods, and access modifiers


“Super” keyword in Java
Tutorial
1. Create a Java class named Person with private data members for name,
age, and gender, along with methods for setting and getting these The super keyword in java is a reference variable which is used to
attributes. refer immediate parent class object.
2. Create a Java class named Car with private data members for make, Whenever you create the instance of subclass, an instance of parent
model, year, and mileage, along with methods for updating mileage
and displaying car details. class is created implicitly which is referred by super reference variable.
3. Create a Java class named Circle with private data member for radius,
along with methods for calculating area and circumference.
Usage of java super Keyword
4. Create a Java class named Rectangle with private data members for
length and width, along with methods for calculating area and 1. super can be used to refer immediate parent class instance
perimeter. variable.
5. Create a Java class named BankAccount with private data members for
account number, balance, and account holder name, along with 2. super can be used to invoke immediate parent class method.
methods for deposit, withdrawal, and balance inquiry. 3. super() can be used to invoke immediate parent class constructor.
41 42

“Super” keyword in Java


“Final” keyword in Java
Example

• The final keyword in java is used to restrict


the user. The java final keyword can be used
in many context.
• Final can be: variable, method, and class.
• If you make any method as final, you cannot
override it.
• If you make any class as final, you cannot
extend it.
• Is final method inherited? Yes it can be
herited but cannot be override
43 44

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 11
4/16/2024

“Final” keyword in Java “Abstract” keyword in Java


• A class that is declared with “abstract” keyword is known as abstract
• A final variable that is not initialized at the class in java.
time of declaration is known as blank final • It can have abstract and non-abstract methods (method with body).
variable. It needs to be extended and its method implemented.
• If you want to create a variable that is • It cannot be instantiated.
initialized at the time of creating object and • An abstract class can provide the implementation of the interface.
once initialized may not be changed, it is useful
Example of abstract class
e.g. PAN CARD number of an employee.
1. abstract class A{}

Example of abstract method


• A final variable can be initialized only in
constructor. 2. abstract void printStatus();//no body and abstract

45 46

Interface in Java(1/3) Interface in Java(2/3)


• An interface in java is a blueprint of a class. It has static constants
and abstract methods. Internal addition by compiler
• The interface in java is a mechanism to achieve abstraction. There
can be only abstract methods in the java interface not method body.
It is used to achieve abstraction and multiple inheritance in Java.
• Java Interface also represents IS-A relationship. It cannot be
instantiated just like abstract class.
• There are mainly three reasons to use interface. They are given Relationship between classes and interfaces
below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling. 47 48

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 12
4/16/2024

Interface in Java
Abstract class vs Interface
Example
//Interface declaration: by first user
Interface Drawable{ void draw();
} //Using interface: by third user

//Implementation: by second user Class TestInterface1{

Class Rectangle implements Drawable{ public static void main(String


args[]){
public void draw(){
Drawable d=new Circle();//In
System.out.println("drawing real scenario, object is provided by
rectangle");} method e.g. getDrawable()
} d.draw();
Class Circle implements Drawable{ }
public void draw(){ }
System.out.println("drawing
circle");}
}
49 50

Java package Java package


• A java package is a group of similar types of classes, interfaces and • Advantage of Java Package
sub-packages.
1) Java package is used to categorize the classes and interfaces so
• Package in java can be categorized in two forms: built-in package and that they can be easily maintained.
user-defined package.
2) Java package provides access protection.
• There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc. 3) Java package removes naming collision.
• Package in java can be categorized in two forms: built-in package and
user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.

51 52

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 13
4/16/2024

Java package Java package


The package java.util.scanner The package java.util.scanner

e.g. The nextLine() method is used to read Strings entered by the user.
• The Scanner class is used to get
user input, and it is found in the
java.util package.
• To use the Scanner class, create
an object of the class and use any
of the available methods found in
the Scanner class documentation.

53 54

Java package
Control statements
Tutorial

e.g. The nextLine() method is used to read Strings entered by the user.
• Selection or decision-
making statement
• Iteration or repetition or
looping statement
• Jump statement

55 56

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 14
4/16/2024

Decision-making statements Decision-making statements


1. if-statement
• They decide which statement to
execute and when. • In Java, the "if" statement is used to
evaluate a condition.
• Decision-making statements evaluate
the Boolean expression and control the • The control of the program is diverted
program flow depending upon the depending upon the specific condition.
result of the condition provided. • The condition of the If statement gives
• There are two types of decision-making a Boolean value, either true or false.
statements in Java, i.e., If statement and • In Java, there are four types of if-
switch statement. statements (see picture).

57 58

If-statements If-statements
simple if-statement The if-else statement
• The most basic statement among all control flow statements in
Java.
• The “if-else” statement is an extension Syntax:
• It evaluates a Boolean expression and enables the program to to the if-statement, which uses
enter a block of code if the expression evaluates to true. another block of code, i.e., else block.
Syntax: • The else block is executed if the
condition of the if-block is evaluated
as false.

59 60

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 15
4/16/2024

If-statements If-statements
The if-else-if statement The nested-if statement

• The if-else-if statement contains the if- Syntax: Syntax:


statement followed by multiple else-if
statements. • In nested if-statements, the if
• In other words, we can say that it is the statement can contain a if or if-else
chain of if-else statements that create a statement inside another if or else-if
decision tree where the program may statement.
enter in the block of code where the
condition is true.
• We can also define an else statement at
the end of the chain.

61 62

Decision-making statements
Loop statements
2. switch-statement
Syntax:
• In Java, Switch statements are similar to • In programming, sometimes we need to
if-else-if statements. execute the block of code repeatedly
• The switch statement contains multiple while some condition evaluates to true.
blocks of code called “cases” and a • However, loop statements are used to
single case is executed based on the execute the set of instructions in a
variable which is being switched. repeated order.
• The switch statement is easier to use • The execution of the set of instructions
instead of if-else-if statements. It also depends upon a particular.
enhances the readability of the
program.
63 64

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 16
4/16/2024

Loop statements Arrays- reminder


1. For loop Processing arrays
Syntax: • When processing array elements, we often use either “for loop” or “for
each” loop because all of the elements in an array are of the same type
• In Java, for loop is similar to C and C++. and the size of the array is known.
• It enables us to initialize the loop
variable, check the condition, and public class TestArray {
public static void main(String[] args) {
total);
System.out.println("Total is " +

increment/decrement in a single line of double[] myList = {1.9, 2.9, 3.4, 3.5};


// Finding the largest element

code. Flowchart: // Print all the array elements


double max = myList[0];
for(int i = 1; i < myList.length; i++)
• We use the for loop only when we for (int i = 0; i <myList.length; i++){
System.out.println(myList[i] + " ");
{

exactly know the number of times, we


if (myList[i] >max) max =
} myList[i];

want to execute the block of code. // Summing all elements double total = 0; }

for(int i = 0; i <myList.length; i++) { System.out.println("Max is " + max);

total += myList[i]; } }
65 } 66

Loop statements Loop statements


1. For loop-Tutorial 2. For-each loop
Syntax:

1. Write a Java program to generate the multiplication table for • Java provides an enhanced for loop to
a given number. traverse the data structures like array or
collection.
2. Write a Java program to find the maximum element in an e.g.:
array. • In the for-each loop, we don't need to
update the loop variable.
3. Write a Java program to sort an array using the bubble sort
algorithm.
PS: Bubble sort is a basic algorithm for arranging a string of numbers or other elements in
the correct order.

67 68

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 17
4/16/2024

Loop statements Loop statements


3. While loop 3. do-While loop
• The while loop is also used to iterate over the Syntax: Syntax:
number of statements multiple times. • The do-while loop checks the condition
• If we don't know the number of iterations in at the end of the loop after executing
advance, it is recommended to use a while loop. the loop statements.
• Unlike for loop, the initialization and • When the number of iteration is not
increment/decrement doesn't take place inside Flowchart: known and we have to execute the loop Flowchart:
the loop statement in while loop. at least once, we can use do-while loop.
• It is also known as the entry-controlled loop since • It is also known as the exit-controlled
the condition is checked at the start of the loop. loop since the condition is not checked
• If the condition is true, then the loop body will be in advance.
executed. Otherwise, the statements after the
loop will be executed.
69 70

Jump statements
Jump statements
1. Break statement
e.g.:
• As the name suggests, the break statement
• They are used to transfer the control of is used to break the current flow of the
the program to the specific statements. program and transfer the control to the
next statement outside a loop or switch
• In other words, jump statements statement.
transfer the execution control to the
• However, it breaks only the inner loop in
other part of the program. the case of the nested loop.
• There are two types of jump statements • The break statement cannot be used
in Java, i.e., break and continue. independently in the Java program, i.e., it
can only be written inside the loop or
switch statement..
71 72

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 18
4/16/2024

Jump statements Control statements


2. Continue statement Tutorials
e.g.: 1. Create a Java class named BankAccount with private data
members for account number, balance, and account
holder name, along with methods for deposit, withdrawal,
• Unlike break statement, the continue and balance inquiry.
statement doesn't break the loop,
whereas, it skips the specific part of the
loop and jumps to the next iteration of
the loop immediately.

73 74

Thank you for your attention

I.R.D. Kamgang, Dr. Eng OOP Java and C++


Faculty of Engineering and Technology 19

You might also like