0% found this document useful (0 votes)
6 views30 pages

Introduction To OOP Handout 1

The document provides an introduction to Object-Oriented Programming (OOP) and Java programming, detailing the types of programming languages, features of OOP, and the history and characteristics of Java. It explains the concepts of classes, objects, inheritance, polymorphism, and encapsulation, as well as Java's syntax, variable types, and modifiers. The document emphasizes Java's simplicity, platform independence, and robustness, making it a popular choice for software development.

Uploaded by

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

Introduction To OOP Handout 1

The document provides an introduction to Object-Oriented Programming (OOP) and Java programming, detailing the types of programming languages, features of OOP, and the history and characteristics of Java. It explains the concepts of classes, objects, inheritance, polymorphism, and encapsulation, as well as Java's syntax, variable types, and modifiers. The document emphasizes Java's simplicity, platform independence, and robustness, making it a popular choice for software development.

Uploaded by

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

1.

Introduction to Object-Oriented Programming


A program is a set of instructions written in a language (such as BASIC) understandable by the computer to
perform a particular function on the computer. A well written program could be parceled .well to form an
application package customized for solving specific type of problem on the computer system.
A computer programmer is computer scientist (a professional) skilled in using constructs of programming
languages to develop executable and acceptable computer programs. A software developer is a programmer.
Programmers often work hand in hand with system analysts on large projects.
Programming languages are artificial notational languages created or developed to be used in preparing coded
instructions on the computer for later execution by the computer. They are usually composed of series of usage
rules (syntax) that determine the meaning (semantics) of expressions written in the language. Each
programming language comes handy with its own translator i.e interpreter or compiler as the case may be.
Programming
Programming is the art of developing computer programs with the aid of selected programming language by a
computer programmer. It is a special skill whose quality is tested by the quality of the resulting program or
software. In programming, programming stages must be properly followed, i.e from problem definition to
maintenance and review
Types of computer languages:
There are basically three types of computer programming languages, they are
1) Low level programming languages
2) High level programming languages
3) Middle level programming languages
1.1. Low level programming languages
These are machine dependent programming languages such as Binary (Machine code) and
Assembly language.
Since computer only understand the Binary language that means instructions in the form of
0’s and 1’s (Signals - that can be either High or Low), so these programming languages are
the best way to give signals (Binary Instructions) to the computer directly
Machine Code (Binary Language) does not need any interpreter or compiler to convert
language in any form because computer understands these signals directly.
Low Level programming language programs are faster than High Level programming
language programs as they have less keywords, symbols and no need (less need) to
convert into Machine Code

1.2. High level programming languages

These are the machine independent programming languages, which are easy to write,
read, edit and understand.

The languages like Java, .Net, Pascal, COBOL, C++, C, C# and other (which are very
popular now to develop user end applications). These languages come under the high
level programming language category.

High level programming languages have some special keywords, functions and class
libraries by using them we can easily build a program for the computer.

Computer does not understand program written in such languages directly, as I have
written above that computer understands only Machine code. So, here programming
translators are required to convert a high level program to its equivalent Machine cod

Here are the features of High Level programming languages

 The programs are written in High Level programming languages and are
independent that means a program written on a system can be run on another
system.
 Easy to understand - Since these programming languages have keywords,
functions, class libraries (which are similar to English words) we can easily
understand the meaning of particular term related to that programming
language.
 Easy to code, read and edit - The programs written in High Level
programming languages are easy to code, read and edit. Even we can edit
programs written by other programmers easily by having little knowledge of
that programming language.
 Since, High Level language programs are slower than Low level language
programs; still these programming languages are popular to develop User End
Applications.

1.3. Middle Level programming language

Since, there is no such category of computer programming languages, but the programming
languages that have features of low level and high level programming languages come
under this category.
Hence, we can say that the programming languages which have features of Low Level
as well as High Level programming languages known as "Middle Level"
programming language.
C programming languages is the best example of Low Level Programming languages as it
has features of low level and high level programming languages both.

Overview of OO principles
Object-Oriented Programming (OOP) is the term used to describe a programming
approach based on objects and classes. The object-oriented paradigm allows us to organise
software as a collection of objects that consist of both data and behaviour. This is in contrast
to conventional functional programming practice that only loosely connects data and
behaviour.
Since the 1980s the word 'object' has appeared in relation to programming languages, with
almost all languages developed since 1990 having object-oriented features. Some languages
have even had object-oriented features retro-fitted. It is widely accepted that object-oriented
programming is the most important and powerful way of creating software.

An object-oriented programming language generally supports five main features:


 Classes
 Objects
 Classification
 Polymorphism
 Inheritance

Overview of Java Programming and types of Java Program


1.History of Java Programming
The history of Java is very interesting. Java was originally designed for
interactive television, but it was too advanced technology for the digital cable
television industry at the time. The history of java starts from Green Team. Java
team members (also known as Green Team), initiated this project to develop a
language for digital devices such as set-top boxes, televisions etc. But, it was suited
for internet programming. Later, Java technology was incorporated by Netscape
Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
2) Originally designed for small, embedded systems in electronic appliances like
set-top boxes
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.

5) Why Oak? Oak is a symbol of strength and choosen as


a national tree of many countries like U.S.A., France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies.
Why Java named as "Java"
7) Why had they choosen java name for java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary", "Silk",
"jolt", "DNA" etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun
to say.
According to James Gosling "Java was one of the top choices along with Silk".
Since java was so unique, most of the team members preferred java. 8) Java is an
island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).
Features of Java
 Simple: Java is very easy to learn and its syntax is simple, clean and easy
to understand. According to Sun, Java language is simple because: syntax
is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit
pointers, operator overloading etc. No need to remove unreferenced
objects because there is Automatic Garbage Collection in java.
 Object Oriented: Java is Object-oriented programming language.
Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporates
both data and behaviour. Object-oriented programming(OOPs) is a
methodology that simplifies software development and maintenance by
providing some rules.
 Object :Object is an instance of a class:bjects 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.
An object has three characteristics:
1. state: represents data (value) of an object.
2. behavior: represents the behavior (functionality) of an
object such as deposit, withdraw etc.
 Class: A class can be defined as a template/blueprint that
describes the behavior/state that the object of its type supports.
 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.
 Instance Variables − Each object has its unique set of instance
variables. An object's state is created by the values assigned to
these instance variables.
 Inheritance:(( When one object acquires all the properties and
behaviours of parent object i.e. known as inheritance. code
reusability. It is used to achieve runtime polymorphism
 Polymorphism: When one task is performed by different ways
i.e. known as polymorphism
 Abstraction: Hiding internal details and showing functionality
is known as abstraction. For example: phone call, we don't know
the internal processing.
 Encapsulation: Binding (or wrapping) code and data together
into a single unit is known as encapsulation. For example:
capsule, it is wrapped with different medicines.
 Platform Indepenedent :Java is platform independent because it is
different from other languages like C, C++ etc. which are compiled into
platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a
program runs.
 Robust: Robust simply means strong. Java is robust because
It uses strong memory management.
There are lack of pointers that avoids security problem.
There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All
these points makes java robust
 Portable: Java is portable because it facilitates you to carry the java
bytecode to any platform
2. Basics in Java Programming
First Java Program
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}}
Basic Syntax
 Case Sensitivity − Java is case sensitive, which means identifier Hello and hello
would have different meaning in Java.
 Class Names − For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first letter
should be in Upper Case
Example: class MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner word's first
letter should be in Upper Case.
Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the class
name.
 When saving the file, you should save it using the class name (Remember Java is
case sensitive) and append '.java' to the end of the name (if the file name and the
class name do not match, your program will not compile).
 Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'
 public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.
All Java components require names. Names used for classes, variables, and
methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows

 All identifiers should begin with a letter (A to Z or a to z), currency
character ($) or an underscore (_).
 After the first character, identifiers can have any combination of
characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.
Java Variable Types
Following are the types of variables in Java –
 Local Variables: Variables defined inside methods, constructors or
blocks are called local variables. The variable will be declared and
initialized within the method and the variable will be destroyed when the
method has completed
Example: public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge()
}}

 Class Variables (Static Variables): class variables are variables declared


within a class, outside any method, constructor or a block.with the static
keyword. Static variables are rarely used other than being declared as
constants.
Static variables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants. Static variables are created when the program starts and
destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables
are declared public since they must be available for users of the class.
public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
Java static variable

 The static variable can be used to refer the common property of all objects (that is not unique for each
object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.
 It makes your program memory efficient (i.e it saves memory)

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}

 Instance Variables (Non-static Variables): A variable which is created


inside the class but outside the method, is known as instance variable.
Instance variable doesn't get memory at compile time. It gets memory at
run time when object(instance) is created. That is why, it is known as
instance variable.
Instance variables are created when an object is created with the use of
the keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that
must be present throughout the class.
Access modifiers can be given for instance variables.

Example.
public class Employee {

// this instance variable is visible for any child class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by
using modifiers. There are two categories of modifiers –
 Access Modifiers − default, public , protected, privat
private hides from other classes within the package. public exposes to
classes outside the package. protected is a version of public restricted only
to subclasses.
| Class | Package | Subclass | Subclass | World
| | |(same pkg)|(diff pkg)|
————————————+———————+—————————+——————————+——————————+————————
public | + | + | + | + | +
————————————+———————+—————————+——————————+——————————+————————
protected | + | + | + | + |
————————————+———————+—————————+——————————+——————————+————————
no modifier | + | + | + | |
————————————+———————+—————————+——————————+——————————+————————
private | + | | | |

+ : accessible
blank : not accessible

1) private access modifier

In this example, we have created two classes A and Simple. A class contains
private data member and private method. We are accessing these private members
from outside the class, so there is compile time error

1. class A{
2. private int data=40;
3. private void msg()
4. {System.out.println("Hello java");}
5. }
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
2.default access modifier: In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.

1. /save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

3.protected access modifier

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the
class.

1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }

A java package is a group of similar types of classes, interfaces and sub-packages.


Package in java can be categorized in two form, built-in package and user-defined package. In simple
words, it is a way of categorizing the classes and interfaces. When developing applications in Java,
hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as
makes life much easier

We will learn more about access modifiers and package in detail in Lab class or in Try it online in class
in //www.javatpoints.com or www.tutorialspoint.com the above code is the example of Java package while
using A protected A/Modifier.

2.1.Number types, strings, constants


There are two data types available in Java −

 Primitive Data Types


 Reference/Object Data Types

Primitive Data Types

There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and
named by a keyword. Let us now look into the eight primitive data types in detail.

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 integer.
 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
integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

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)
 Integer 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
 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
 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

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


 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'

Reference Datatypes

 Reference variables are created using defined constructors of the classes. They are used to access objects.
These variables are declared to be of a specific type that cannot be changed. For example, Employee,
Puppy, etc.
 Class objects and various type of array variables come under reference datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any compatible type.
 Example: Animal animal = new Animal("giraffe");

Operators and operator precedence

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following
groups −

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The
following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −


Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

Subtracts right-hand operand from left-hand


- (Subtraction) A - B will give -10
operand.

Multiplies values on either side of the


* (Multiplication) A * B will give 200
operator.

Divides left-hand operand by right-hand


/ (Division) B / A will give 2
operand.

Divides left-hand operand by right-hand


% (Modulus) B % A will give 0
operand and returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

Checks if the values of two operands are equal or not,


== (equal to) (A == B) is not true.
if yes then condition becomes true.

Checks if the values of two operands are equal or not,


!= (not equal to) (A != B) is true.
if values are not equal then condition becomes true.

Checks if the value of left operand is greater than the


> (greater than) value of right operand, if yes then condition becomes (A > B) is not true.
true.

Checks if the value of left operand is less than the


< (less than) value of right operand, if yes then condition becomes (A < B) is true.
true.

Checks if the value of left operand is greater than or


>= (greater than or equal
equal to the value of right operand, if yes then (A >= B) is not true.
to)
condition becomes true.

Checks if the value of left operand is less than or equal


<= (less than or equal to) to the value of right operand, if yes then condition (A <= B) is true
becomes true.

Example
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

The Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Operator Description Example

Called Logical AND operator. If both the operands are non-


&& (logical and) (A && B) is false
zero, then the condition becomes true.

Called Logical OR Operator. If any of the two operands are


|| (logical or) (A || B) is true
non-zero, then the condition becomes true.

Called Logical NOT Operator. Use to reverses the logical


! (logical not) state of its operand. If a condition is true then Logical NOT !(A && B) is true
operator will make false.

public class Test {

public static void main(String args[]) {


boolean a = true;
boolean b = false;

System.out.println("a && b = " + (a&&b));


System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output
a && b = false
a || b = true
!(a && b) = true
The Assignment Operators
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 0;

c = a + b;
System.out.println("c = a + b = " + c );

c += a ;
System.out.println("c += a = " + c );

c -= a ;
System.out.println("c -= a = " + c );

c *= a ;
System.out.println("c *= a = " + c );

a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );

a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );

c <<= 2 ;
System.out.println("c <<= 2 = " + c );

c >>= 2 ;
System.out.println("c >>= 2 = " + c );

c >>= 2 ;
System.out.println("c >>= 2 = " + c );

c &= a ;
System.out.println("c &= a = " + c );

c ^= a ;
System.out.println("c ^= a = " + c );

c |= a ;
System.out.println("c |= a = " + c );
}
}
Simple assignment operator. Assigns values from right side operands to left C = A + B will assign value of
=
side operand. A + B into C
Add AND assignment operator. It adds right operand to the left operand and C += A is equivalent to C = C
+=
assign the result to left operand. +A
Subtract AND assignment operator. It subtracts right operand from the left C -= A is equivalent to C = C –
-=
operand and assign the result to left operand. A
Multiply AND assignment operator. It multiplies right operand with the left C *= A is equivalent to C = C
*=
operand and assign the result to left operand. *A
/= Divide AND assignment operator. It divides left operand with the right C /= A is equivalent to C = C /
operand and assign the result to left operand. A
Modulus AND assignment operator. It takes modulus using two operands and C %= A is equivalent to C = C
%=
assign the result to left operand. %A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Operators precedence..??

Increment and Decrement Operators


increment and decrement operators are widely used in controlling loops. These operators provide a more convent
and compact way of increasing or decreasing the value of a variable by one. For instance the statement x=x+1; can
be simplified to x++; or ++x;

int x = 34;
int y = ++x;

The value of x is first incremented to 34 and is then assigned to y. Therefore x is now 35 and y is also 35.

int x = 34;
int y = x++;

x is first assigned to y and then incremented by one. Therefore, x becomes 35 while y is assigned with the value 34.
int s = 34;
s++; // s is now 35
int s= 34;
++s; // s is now 35

Casting
We have already come across casting quite a number of types. In order to help you, we will now recollect all that we
have learnt about casting till now and then learn something in addition to what you have already learnt.

Casting refers to the conversion of one data type to another. When we cast a particular variable, the data type of the
variable itself is not altered. For example, in the following code, when we cast, num1 to a double; the variable num1
does not change its data type from int to double. Instead, a new copy of num1 is made and its data type is changed to
double.

int num1=3, num2=4;


double result = (double) num1 / num2;
Casting is of two types- up casting and down casting. When we cast a variable to a higher data type it is known as up
casting. A higher data type simply indicates that the memory allocation for that data type is higher. For example, int
is a higher data type than short as the memory allocated for int is 32 bits which is higher than the memory allocated
for a short which is 16 bits. On the other hand, when we cast a variable to a lower data type, it is known as down
casting. When we up cast a variable, no information is lost but while down casting a variable, information loss might
occur. Consider the following example:

short a = 347;
int b= 347347;
short c = (short)a;
int d = (short) b;
System.out.println(c);
System.out.println(d);
Flow controll
1. Decision and Repetition Statements (6 hours)

Flow of Execution of the for Loop

As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this
the control flow, or the flow of execution of the program.

First step: In for loop, initialization happens first and only one time, which means that the initialization part of for
loop only executes once.

Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside
for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the
control gets transferred to the next statement in the program after for loop.

Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates
the loop counter.

Fourth step: After third step, the control jumps to second step and condition is re-evaluated.

Example of Simple For loop


class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}

The output of this program is:


The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
Infinite for loop

The importance of Boolean expression and increment/decrement operation co-ordination:

class ForLoopExample2 {
public static void main(String args[]){
for(int i=1; i>=1; i++){
System.out.println("The value of i is: "+i);
}
}
}

This is an infinite loop as the condition would never return false. The initialization step is setting up the value of
variable i to 1, since we are incrementing the value of i, it would always be greater than 1 (the Boolean expression:
i>1) so it would never return false. This would eventually lead to the infinite loop condition. Thus it is important to
see the co-ordination between Boolean expression and increment/decrement operation to determine whether the loop
would terminate at some point of time or not.

Here is another example of infinite for loop:

// infinite loop
for ( ; ; ) {
// statement(s)
}
For loop example to iterate an array:

Here we are iterating and displaying array elements using the for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}

Output:

2
11
45
9
Syntax of while loop
while(condition)
{
statement(s);
}
How while Loop works?

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute. When
condition returns false, the control comes out of loop and jumps to the next statement after while loop.

Note: The important point to note when using while loop is that we need to use increment or decrement statement
inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false.
This way we can end the execution of while loop otherwise the loop would execute indefinitely.

Simple while loop example


class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}

Output:

10
9
8
7
6
5
4
3
2
Infinite while loop
class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}

This loop would never end, its an infinite while loop. This is because condition is i>1 which would always be true as
we are incrementing the value of i inside while loop.

Here is another example of infinite while loop:

while (true){
statement(s);
}
Example: Iterating an array using while loop

Here we are iterating and displaying array elements using while loop.

class WhileLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
int i=0;
while(i<4){
System.out.println(arr[i]);
i++;
}
}
}

Output:

2
11
45
9
Syntax of do-while loop:
do
{
statement(s);
} while(condition);
How do-while loop works?

First, the statements inside loop execute and then the condition gets evaluated, if the condition returns true then the
control gets transferred to the “do” else it jumps to the next statement after do-while.

do-while loop example


class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}

Output:

10
9
8
7
6
5
4
3
2
Example: Iterating array using do-while loop

Here we have an integer array and we are iterating the array and displaying each element using do-while loop.

class DoWhileLoopExample2 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0
int i=0;
do{
System.out.println(arr[i]);
i++;
}while(i<4);
}
}

Output:
2
11
45
9

Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps to
the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current
iteration. This is particularly useful when you want to continue the loop but do not want the rest of the
statements(after continue statement) in loop body to execute for that particular iteration.

Syntax:
continue word followed by semi colon.

continue;
Example: continue statement inside for loop
public class ContinueExample {

public static void main(String args[]){


for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}

System.out.print(j+" ");
}
}
}

Output:

012356

As you may have noticed, the value 4 is missing in the output, why? because when the value of variable j is 4, the
program encountered a continue statement, which makes it to jump at the beginning of for loop for next iteration,
skipping the statements for current iteration (that’s the reason println didn’t execute when the value of j was 4).
Flow Diagram of Continue Statement

Example: Use of continue in While loop

Same thing you can see here. We are iterating this loop from 10 to 0 for counter value and when the counter value is
7 the loop skipped the print statement and started next iteration of the while loop.

public class ContinueExample2 {

public static void main(String args[]){


int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
System.out.print(counter+" ");
counter--;
}
}
}

Output:

10 9 8 6 5 4 3 2 1 0

he break statement is usually used in following two scenarios:

a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered inside a loop,
the control directly comes out of loop and the loop gets terminated for rest of the iterations. It is used along with if
statement, whenever used inside loop so that the loop gets terminated for a particular condition.

The important point to note here is that when a break statement is used inside a nested loop, then only the inner loop
gets terminated.
b) It is also used in switch case control. Generally all cases in switch case are followed by a break statement so that
whenever the program control jumps to a case, it doesn’t execute subsequent cases (see the example below). As
soon as a break is encountered in switch-case block, the control comes out of the switch-case body.

Syntax of break statement:


“break” word followed by semi colon

break;
Example – Use of break in a while loop

In the example below, we have a while loop running from o to 100 but since we have a break statement that only
occurs when the loop value reaches 2, the loop gets terminated and the control gets passed to the next statement in
program after the loop body.

public class BreakExample1 {


public static void main(String args[]){
int num =0;
while(num<=100)
{
System.out.println("Value of variable is: "+num);
if (num==2)
{
break;
}
num++;
}
System.out.println("Out of while-loop");
}
}

Output:

Value of variable is: 0


Value of variable is: 1
Value of variable is: 2
Out of while-loop
Example – Use of break in a for loop

The same thing you can see here. As soon as the var value hits 99, the for loop gets terminated.

public class BreakExample2 {

public static void main(String args[]){


int var;
for (var =100; var>=10; var --)
{
System.out.println("var: "+var);
if (var==99)
{
break;
}
}
System.out.println("Out of for-loop");
}
}

Output:

var: 100
var: 99
Out of for-loop
Example – Use of break statement in switch-case
public class BreakExample3 {

public static void main(String args[]){


int num=2;

switch (num)
{
case 1:
System.out.println("Case 1 ");
break;
case 2:
System.out.println("Case 2 ");
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}
}
}

Output:

Case 2

1. Objects and Classes


Object variables

Class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created. It is a logical entity. It can't be physical.

A class in Java can contain:

 fields
 methods
 constructors
 blocks
 nested class and interface

Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }

Object and Class Example: main within class

In this example, we have created a Student class that have two data members id and name. We are creating the
object of the Student class by new keyword and printing the objects value.

Here, we are creating main() method inside the class.


File: Student.java
class Student{
int id;//field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

1) Object and Class Example: Initialization through reference

3 Ways to initialize object

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference

Initializing object simply means storing data into object. Let's see a simple example where we are going to initialize
object through reference variable.

File: TestStudent2.java

1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12. }

Output:

101 Sonoo
We can also create multiple objects and store information in it through reference variable.

File: TestStudent3.java

1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);
17. System.out.println(s2.id+" "+s2.name);
18. }
19. }

Output:

101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.

File: TestStudent4.java

1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19. }

Output:

111 Karan
222 Aryan

3) Object and Class Example: Initialization through constructor

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23. }
24. }

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java
1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. }
10. class TestRectangle1{
11. public static void main(String args[]){
12. Rectangle r1=new Rectangle();
13. Rectangle r2=new Rectangle();
14. r1.insert(11,5);
15. r2.insert(3,15);
16. r1.calculateArea();
17. r2.calculateArea();
18. }
19. }
20. Output:
21. 55
22. 45

Construction

In Java, constructor is a block of codes similar to method. It is called when an instance of object is created and
memory is allocated for the object.

It is a special type of method which is used to initialize the object.

When a constructor is called

Everytime an object is created using new() keyword, atleast one constructor is called. It is called a default
constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors in java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object
creation.

1. class Bike1{
2. Bike1()
3. {
4. System.out.println("Bike is created");
5. }
6. public static void main(String args[]){
7. Bike1 b=new Bike1();
8. }
9. } Output:Bike is created

What is the purpose of default constructor?

To provide the default values to the object like 0, null etc. depending on the type

class Student3{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display(); s2.display();
}
OUtput
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor


1. class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. } Output:111 Karan

222 Aryan

18. public class Puppy {


19. int puppyAge;
20.
21. public Puppy(String name) {
22. // This constructor has one parameter, name.
23. System.out.println("Name chosen is :" + name );
24. }
25.
26. public void setAge( int age ) {
27. puppyAge = age;
28. }
29.
30. public int getAge( ) {
31. System.out.println("Puppy's age is :" + puppyAge );
32. return puppyAge;
33. }
34.
35. public static void main(String []args) {
36. /* Object creation */
37. Puppy myPuppy = new Puppy( "tommy" );
38.
39. /* Call class method to set puppy's age */
40. myPuppy.setAge( 2 );
41.
42. /* Call another class method to get puppy's age */
43. myPuppy.getAge( );
44.
45. /* You can access instance variable as follows as well */
46. System.out.println("Variable Value :" + myPuppy.puppyAge );
47. }}

Output

Name chosen is :tommy


Puppy's age is :2
Variable Value :2
48.

You might also like