OOPJ Unit 1 Material
OOPJ Unit 1 Material
Introduction
Java is a widely used programming language and is designed for the distributed environment of internet. It
is a general-purpose programming language that is concurrent, class-based, and object-oriented. It is free to
access and we can run it on all the platforms. Java follows the principle of WORA (Write Once, Run
Anywhere), and is platform-independent. It is also simple and easy to learn.
Some languages like C, Fortran and Pascal are not object-oriented programming languages and are called
as procedural programming languages. They were having some disadvantages.
1) They were less secure.
2) There are no access modifiers in procedural programming.
3) Procedural programming does not have the concept of inheritance.
4) It gives importance to functions over data.
5) There is not any proper way for data hiding.
6) Code reusability is difficult in procedural programming.
7) There is no concept of virtual class.
8) Polymorphism, Abstraction and Encapsulation were not present in procedural languages.
The above details are not needed. These details are hidden by the car dealer. Like this, you can think of
other examples in the real world. Abstraction is everywhere.
Encapsulation
Encapsulation is the fundamental principle to achieve abstraction in object -oriented programming.
Abstraction is conceptual and encapsulation is a way to implement abstraction. Wherever you can find
abstraction you can say that encapsulation is there but encapsulation may not always provide abstraction.
Encapsulation is defined as wrapping up or combining the data and code into a single unit. In the
definition data refers to variables and code refers to methods (functions). Every object contains private data
(variables) and public methods which allows other code to access the private data. Private methods are
optional. We can view an object in OOP as shown below:
As a real-world example for encapsulation let’s consider a television. We access the television by using a
remote which provides an interface to communicate with the television. Television manufacturer is hiding
its components (data) under the shell and is providing public interface (remote control) to access its
components.
In our real-world example, television components are analogous to private member variables and public
methods are analogous to buttons on remote control of the television.
Unit-I
Data hiding or information hiding is the side effect of encapsulation. Whenever we use encapsulation, we
are implicitly hiding the data of an object which is known as data hiding. Encapsulation helps
programmers to write code which is extensible.
Inheritance
Another way to implement abstraction is by using inheritance. In inheritance, entities are arranged as
hierarchies. You might come across situations where even though objects have similar properties are quite
different. In such cases, it is better to move all the common properties and behavior into one common
entity and the specific properties and behavior into special or specific entity. Inheritance is defined as one
object derives or inherits the properties and behavior of another object. Common properties and behavior
are moved into a common class also known as super class or base class or parent class. Specific properties
and behavior are moved into specialized classes also known as sub class or derived class or child class.
As a real-world example, consider a child inheriting the properties (land and other assets) from their
parents. As another example, let’s consider that we are developing a program to work with geometrical
objects like circle, rectangle etc. In the application I can create these objects and perform operations like
move, re size etc. These operations are common for all the objects. So, we can use inheritance in this
context. It provides code reusability. The resultant hierarchy will be as shown below:
Polymorphism
Polymorphism means many forms. More generally it is defined as one interface multiple implementations.
It means that based on the situation or different factors, the same thing exhibits multiple behaviors or the
same thing can be used to carry out different tasks. Here thing is used as a general element.
Unit-I
As a real-world example for polymorphism, let’s consider
the animal Chameleon. This animal changes its color to
reflect the surroundings to hide from its prey. It is really
cool! Based on the color of the surroundings the same thing
(Chameleon) can change its color from one to another. In
every well written java program, we can find
encapsulation, inheritance and polymorphism.
___________________________________________________________________________________________
____________________________________________________________________________________________
History of Java
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.
Unit-I
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995.
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) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) Java is an island in Indonesia where the first coffee was produced (called Java coffee).
8) Initially developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
9) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have
been many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc. Each new
version adds new features in Java.
____________________________________________________________________________________________
Applications of OOP:
Java is widespread; the following are some of the areas in which we find java usable:
Desktop applications
Web applications
Mobile applications (Android)
Cloud computing
Unit-I
Enterprise applications
Scientific applications
Operating Systems
Embedded systems
Real-time software
Cryptography
Smart cards
Computer games
Web servers and application servers
____________________________________________________________________________________________
History of Java
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 with the
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. However, it was best suited for internet
programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of Java, in
1995. James Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
Following are given significant points that describe 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) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Java was named as "Oak"?
5) Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) 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 than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of
espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
9) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional
features added to the language. Now Java is being used in Windows applications, Web applications,
enterprise applications, mobile applications, cards, etc. Each new version adds new features in Java.
Java JDK, JRE and JVM
What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java program.
When you run the Java program, Java compiler first compiles your Java code to bytecode. Then, the JVM
translates bytecode into native machine code (set of instructions that a computer's CPU executes directly).
Unit-I
Java is a platform-independent language. It's because when you write Java code, it's ultimately written for
JVM but not your physical machine (computer). Since JVM executes the Java bytecode which is platform-
independent, Java is platform-independent.
What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual
Machine (JVM), and other components that are required to run Java applications.
What is JDK?
JDK (Java Development Kit) is a software development kit required to develop applications in Java. When
you download JDK, JRE is also downloaded with it.
In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc, Java Debugger,
etc).
1) ClassLoader: The class loader is a subsystem used for loading class files. It performs three major
functions viz. Loading, Linking, and Initialization.
2) Method Area: JVM Method Area stores class structures like metadata, the constant runtime pool, and
the code for methods.
3) Heap: All the Objects, their related instance variables, and arrays are stored in the heap. This memory is
common and shared across multiple threads.
4) JVM language Stacks: Java language Stacks store local variables, and it’s partial results.
5) PC Registers: PC register store the address of the Java virtual machine instruction which is currently
executing.
6) Native Method Stacks: Native method stacks hold the instruction of native code depends on the native
library.
7) Execution Engine: It is a type of software used to test hardware, software, or complete systems.
8) Native Method interface: The Native Method Interface is a programming framework. It allows Java code
which is running in a JVM to call by libraries and native applications.
9) Native Method Libraries: Native Libraries is a collection of the Native Libraries (C, C++) which are
needed by the Execution Engine.
_____________________________________________________________________________________________
Unit-I
How to execute a java program on a computer?
After we install Java on the computer, Let’s learn how to execute a java program on a computer.
First step is to type the Java source code into a text editor and save it with .java extension.
class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Above Java program prints Hello World on to the console (command prompt in Windows). After typing
the above program save the file as Hello.java. Note that file name Hello is same as the class name.
Let’s assume that the file is saved in the path C:/java. So, full path to the source file is
C:/java/Hello.java.
Next step is to compile the source code file. Open the command prompt (black window) and navigate to
the location C:/java. Type the following command to compile the java file:
javac Hello.java
If there are no errors in the Java program, the program compiles successfully and you will see the prompt
again as shown below:
After compiling the program, you can see the generated file Hello.class which contains the bytecode in the
location C:/java.
Next step is to execute the program. To execute the program, type the following command in the command
prompt:
java Hello
Take care that .class is not added after the class name Hello. You can see the output Hello World as shown
below:
Unit-I
Types of comments
In Java, there are three types of comments. They are:
o Single line comments
o Multi-line comments
o javadoc comments
A single line comment as the name implies is a comment containing a single line of text. A single line
comment starts with //. All the characters after the // to the end of the line is treated as a comment.
Syntax for single line comment is as shown below:
// This is a single line comment
To write a comment containing more than one line, we can use a multi-line comment. A multi-line
comment starts with /* and ends with */.
Syntax for writing a multi-line comment is as shown below:
/* This is a
multi-line
comment */
We can use a multi-line comment for writing a single line comment as shown below:
/* This is a single line comment. */
Both single line comments and multi-line comments can be written anywhere in the program.
The third type of comments called javadoc comments can be used to generate HTML documentation which
can be viewed using a browser. This can help the client programmers to understand the classes that you
create. A javadoc comment starts with /** and ends with */. Syntax for writing a javadoc comment is as
shown below:
Unit-I
/**
* This is a
* javadoc comment
*/
Note that * is not necessary before each line of text. It is widely accepted usage of javadoc comments by
Java developers. Generally javadoc comments are written at the top of the program.
_______________________________________________________________________________________________
Java Variables
A variable is a location in memory (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier).
It is common in programs to store data and process the data to get the required outcome.
Creating or declaring variables in Java:
A variable can be created or declared in Java by using the below syntax:
datatype variable_name;
A variable_name can be any valid identifier in Java. Before using any variable in a Java program, you have
to declare it first as per the syntax given above. The datatype specifies the type of value you are going to
store in the variable.
Example for declaring a variable in Java is shown below:
int x;
In the above example, int is a Java’s primitive data type and x is the name of the variable.
Types of variables:
Based on the location where the variable is declared and how it is declared, variables in Java are divided
into three types. They are:
o Instance variables
o Class variables
o Local variables
Instance Variables: A variable which is declared inside a class and outside all the methods, constructors
and blocks is known as an instance variable.
Class Variables: A variable which is declared inside a class and outside all the methods, constructors,
blocks and is marked as static is known as a class variable. More on static keyword in another article.
Local Variables: Any variable which is declared inside a class and inside a block, method or a constructor
is known as a local variable.
Following Java example program demonstrates all the three kinds of variables:
class Sample
{
int x, y;
static int result;
void add(int a, int b)
{
x = a;
y = b;
int sum = x+y;
System.out.println("Sum = "+sum);
}
public static void main(String[] args)
{
Sample obj = new Sample();
obj.add(10,20);
}
}
In the above program x and y are instance variables, result is a class variable; a, b, sum and args are local
variables.
One important point to remember is, every object maintains its own copy of each instance variable and a
shared copy of each class variable.
_______________________________________________________________________________________________
Data Types
A data type specifies the type of value a variable can store or the type of an expression. Java is a strongly
typed language means that you should specify the type of a variable before using it in a Java program.
Unit-I
a. Primitive Data Types- Java primitive data types are the ones which are predefined by the programming
language which in this case is Java. Without primitive data types it would be impossible to frame
programs. Primitive data types are also the building blocks of Non-primitive data types. Examples are-
int,float etc.
b. Non-Primitive Data Types- These data types are special types of data which are user defined, Some
examples are- classes, interfaces etc.
Primitive Data Types
There are eight primitive types in Java namely: byte, short, long, int, float, double, char and boolean.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
_______________________________________________________________________________________
Command Line Arguments
Unit-I
Sometimes we might want to pass extra information while running a Java program. This extra
information passed along with the program name are known as command line arguments.
These command line arguments are separated by white spaces.
Command line arguments can be accessed using the string array specified in the main function’s
signature.
For example, if the array name is args, then the first command line argument can be accessed as
args[0] and the second command line argument can be accessed as args[1] and so on.
Let’s see the following Java program which access two command line arguments, multiplies them
and displays the result to the user:
class CommandArgs
{
public static void main(String[] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int mult = x * y;
System.out.println("Multiplication of the command line arguments is: " + mult);
}
}
Output:
javac CommandArgs.java
java CommandArgs 2 4
Multiplication of the command line arguments is:8
What do you mean by operators? What are different kinds of operators in java?
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
In other words, an operator allows the programmer or the computer to perform an operation on the
operands. An operand can be a literal, variable or an expression.
C=a+b
Operand
Operand
Operator Operand Operator
Arithmetic Operator:
They are used to perform basic mathematical operations like addition, subtraction, multiplication and
division.
Some of the arithmetic operators are + , - , * , / , % , ++ , --
Points to note:
Unit-I
1) % is for reminder division and returns the reminder part.
2) ++x is pre-increment and x++ is post increment
3) Similarly. –-x is pre-decrement and x-- is post decrement.
1) Post-Increment (y++): we use y++ in our statement if we want to use the current value, and then we
want to increment the value of y by 1.
2) Pre-Increment(++x): We use ++x in our statement if we want to increment the value of x by 1 and then
use it in our statement.
Similarly for decrement operator too.
Assignment Operators
Assignment operators are used to assign values to variables. In the example below, we use the assignment
operator (=) to assign the value 10 to a variable called x:
public class AO {
public static void main(String[] args) {
int x = 10; Unit-I
System.out.println(x);
}
}
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
!= Not equal x != y
&& Logical and Returns true if both statements are x < 5 && x< 10
true
! Logical not Reverse the result, returns false if !(x < 5 && x < 10)
the result is true
Note that the logical && operator doesn't check the second condition if the first condition is false.
Sample program demonstrating logical operators:
true
false
& (bitwise and) Binary AND Operator copies a bit to the result if it exists in both operands.
^ (bitwise XOR) Binary XOR Operator copies the bit if it is set in one operand but not both.
~ (bitwise
Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
compliment)
Binary Left Shift Operator. The left operands value is moved left by the number of
<< (left shift)
bits specified by the right operand.
Binary Right Shift Operator. The left operands value is moved right by the
>> (right shift)
number of bits specified by the right operand.
class Main {
public static void main(String[] args) {
}
}
Output:
7
5
2
-8
10
2
Operators can also be divided based on the number of operands on which they operate.
1) Unary operators:
The Java unary operators require only one operand.
Unit-I
2) Binary operators
The java binary operator requires 2 operands
3) Ternary operators
Java ternary operator is the only conditional operator that takes three operands. It’s a one-line replacement
for if-then-else statement and used a lot in Java programming.
What is Primitive Type Conversion and Casting? (or) What is the difference between implicit and
explicit type conversion? (or) what is the difference between widening and Narrowing type casting?
Converting a value from one data type to another data type is known as type conversion.
There are 2 types of type conversion/casting:
1) Implicit type conversion/Automatic conversion/coercion/Widening Casting
2) Explicit type conversion/ Manual conversion/casting/narrowing casting.
Implicit type conversion/Automatic conversion /casting down / Widening Casting:
Converting a lower data type into a higher one is called widening type casting. It is also known as implicit
conversion or casting down. It is done automatically. It is safe because there is no chance to lose data.
byte -> short -> char -> int -> long -> float -> double
Lower Higher
datatype datatype
for example, a variable of int datatype is automatically converted into float.
public class Main
{
public static void main(String[] args)
{
int myint=3;
float myfloat=myint;
System.out.println(myint);
System.out.println(myfloat);
}
}
Unit-I
double -> float -> long -> int -> char -> short -> byte
Higher Lower
Datatype datatype
100 + 5 – 30
Now, we can apply the associativity rules and evaluate the expression. The final answer for the above expression is
75.
_______________________________________________________________________________________________
Simple if Statement
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
}
}
In the above code, the if part will not be executed. Instead, else part is executed.
if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements where the program may enter in the block of code where the
condition is true.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example in which we have used the if-else-if statement in the java code.
Unit-I
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
}
Consider the following example in which we have used the Nested if-else statement in the java code.
Unit-I
public class Main
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
if (i< 15)
System.out.println("i is smaller than 15");
if (i< 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
switch(operation)
{
case 1:
System.out.println("addition is "+ (a+b));
break;
case 2:
System.out.println("Substraction is " + (a-b));
break;
case 3:
System.out.println("Multiplication is "+ (a*b));
break;
case 4:
System.out.println("Division is "+ (a/b));
break;
case 5:
System.out.println("Reminder division "+ (a%b));
break;
default:
System.out.println (" Give correct choice");
}
}
}
Unit-I
As long as the condition is true, the statements execute again and again. If the statement to be executed in
any loop is only one, you can omit the braces. As the while loop checks the condition at the start of the
loop, statements may not execute even once if the condition fails. If you want to execute the body of a loop
atleast once, use do-while loop.
Unit-I
Note: Variable used in the condition should be increased, otherwise the loop will never end!
for loop
In a for statement, initialization of the loop control variable, condition and modifying the value of the loop
control variable are combined into a single line. When we know exactly how many times you want to loop
through a block of code, the for loop is used instead of a while loop:
Syntax:
for(initialization; condition; iteration)
{
Statements;
}
Unit-I
In the above syntax, the initialization is an assignment expression which initializes the loop control variable
and/or other variables. The initialization expression evaluates only once. The condition is a boolean
expression. If the condition evaluates to true, the body of the loop is executed. Else, the control quits the
loop.
Every time after the body executes, the iteration expression is evaluated. Generally, this is an increment or
decrement expression which modifies the value of the control variable.
Example of for loop
for-each Statement
The for-each statement is also known as enhanced for statement. It is a simplification over the for statement
and is generally used when you want to perform a common operation sequentially over an array. The
syntax of for-each statement is as shown below:
Syntax:
for(type var : array name)
{
Statements;
}
The data type of var must be same as the data type of the array. The above syntax is can be read as, for each
value in array, execute the statements. Starting from the first value in the array, each value is copied into
var and the statements are executed. The loop executes until the values in the array completes.
Example of for-each loop
public class Main{
public static void main(String[] args){
String[] branches={"CSE","ECE","MECH","EEE"};
for(String i: branches)
{
System.out.println(i);
}
}
}
Unit-I
}
}
}
}
}
}
Output:
Now the value of i is 0
Now the value of i is 1
Now the value of i is 2
Now the value of i is 3
Now the value of i is 4
Now the value of i is 6
Now the value of i is 7
Now the value of i is 8
Now the value of i is 9