Unit I-Cs3391
Unit I-Cs3391
UNIT I
INTRODUCTION TO OOP AND JAVA
1.1 Overview of OOP – Object oriented programming paradigms – 1.2 Features of Object Oriented
Programming – Java Buzzwords – Overview of Java – 1.3 Data Types 1.4 Variables and 1.5 Arrays
– 1.6 Operators – Control Statements – Programming Structures in Java – Defining classes in Java –
Constructors Methods -Access specifiers Static members-Java Doc comments
OVERVIEW OF OOP
Object-oriented programming (OOP) is a programming paradigm based on the concept of
“objects”.
It contain data(attributes) and code(methods).
Object-Oriented Programming languages:
1. Ada 95
2. Fortran 2003
3. PHP since v4, greatly enhanced in v5
4. BETA
5. Graph talk
6. Python
7. C++
OOPs Concepts:
1. Class
2. Objects
3. Data Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing
Benefits of OOP:
Greater programmer productivity,
Better quality of software
Lesser maintenance cost.
Easily upgraded
Very easy to partition the work based on objects.
To map the objects in problem domain
Data hiding helps to build secure programs
Eliminate redundant code
Disadvantages of OOP:
Larger Program size
Requires more time to execute
OOP is not a universal language.
Programmers need good programming skill
Everything is treated as object in OOP
Applications of OOPS:
User interface design such as windows, menu.
Real Time Systems
Simulation and Modeling
Object oriented databases
AI and Expert System
Neural Networks and parallel programming
Decision support and office automation systems etc.
1.1 OBJECT ORIENTED PROGRAMMING PARADIGMS
In Java, OOPS stands for Object-Oriented Programming System.
This paradigm is based on the concept of objects, which can contain data in the form of fields
(also known as attributes or properties) and code in the form of procedures (methods).
OOP concepts:
1. Object:
An object represents a real-world entity (e.g., a chair, pen, or car).
It has both state (attributes like color, size, etc.) and behavior (methods or functions it can
perform).
Objects communicate by sending messages to each other.
2. Class:
A class is a blueprint or template for creating objects.
It defines the attributes (data members) and methods (functions) that objects of that class
will have.
Classes allow code reusability and organization.
3. Inheritance:
Inheritance allows creation of new classes(Child/Derived class) from existing class
(parent/base class).
It promotes code reuse and establishes a hierarchy of classes.
Example: a `Car` class can inherit from a more general `Vehicle` class.
4. Polymorphism:
Polymorphism means "many forms".
It allows one task to be performed in different ways.
In Java, polymorphism is achieved through
i. Compile Time Polymorphism/Method overloading –
Multiple methods with the same name but different parameters within class.
5. Abstraction:
Abstraction hides the internal details of an object and exposes only the essential features.
It focuses on what an object does rather than how it does it.
Abstract classes and interfaces to achieve abstraction.
Example: Phone Call, We don’t know internal processing
6. Encapsulation:
Encapsulation binds data (attributes) and methods (functions) together into a single unit
(an object or a class).
Encapsulation means “Combining”.
Example:In School,student cannot exist without class
Advantage:
Increased flexibility
Reusability
Testing code is easy
It protects data by restricting direct access.
Procedural Oriented Programming Vs Object-Oriented Programming:
Uses the concept of procedure abstraction. Uses the concept of data abstraction.
Examples: C, FORTRAN, Pascal, Basic, Examples: C++, Java, Python, C#, etc.
etc.
1. Object Oriented
• Java is true object-oriented language.
• All program code and data reside within objects and classes.
• Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
2.Simple
• Java was designed to be easy for a professional programmer to learn and use effectively.
3.Secured
• Java provides a “firewall” between a networked application and your computer.
• we can develop virus-free systems.
• Java is secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
4. Platform Independent
• Java is a Write Once and Run Anywhere (WORA) language.
• Java provides a software-based platform that runs on top of other hardware-based platforms.
• It has two components:
1. Runtime Environment
5. Robust
• It provides many features that make the program execute reliably in a variety of
environments.
6. Portable
• Java Provides a way to download programs dynamically to all the various types of
platforms connected to the Internet.
7. Architecture Neutral
• No implementation dependent features.
• Example: Size of primitive types is fixed.
8. Dynamic
• Java is capable of linking in new class libraries, methods, and objects.
9. Compiled and Interpreted
• Usually, a computer language is either compiled or Interpreted. Java combines both this
approach and makes it a two-stage system.
• Compiled: Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java Byte code.
• Interpreted: Bytecode is then interpreted, which generates machine code that can be
directly executed by the machine that provides a Java Virtual machine.
10.High Performance
• Java is faster than other traditional interpreted programming languages because Java byte
code is "close" to native code.
11. Multithreaded
• Multithreaded Programs handled multiple tasks simultaneously, which was helpful in
creating interactive, networked programs.
12. Distributed
• Users to create distributed applications in Java.
• To access files by calling the methods from any machine on the internet.
OVERVIEW OF JAVA
• Java is an object-oriented, class-based programming language.
• Whenever we compile a Java code, we get the byte code (.class file), and that can be
executed (without compiling it again) on different platforms.
• It is mainly used to develop web, desktop, and mobile devices.
• The Java language is known for its robustness, security, and simplicity features.
History
• James Gosling initiated Java language project in June 1991 for use in one of his many set-
top box projects.
• Initially called as 'Oak' and later being renamed as Java.
• Sun released the first public implementation as Java 1.0 in 1995.It promised Write Once,
Run Anywhere (WORA), providing no-cost run-times on popular platforms.
• On 2006, Sun released much of Java as free and open source software under General
Public License (GPL).
• On 2007, Sun finished the process, making all of Java's core code free and open-source.
The Terminologies in Java
JVM (Java Virtual Machine):
• JVM provides the runtime environment in which the execution of the Java bytecode takes
place.
Byte Code(.class file):
• Java compiler compiles the Java code to generate the .class file or the byte code.
• Use the javac command to invoke(call) the Java compiler.
Java Development Kit (JDK):
• JDK encompasses everything, including JRE(Java Runtime Environment), compiler, java
docs, debuggers, etc.
• JDK must be installed on the computer for the creation, compilation, and execution of a Java
program.
Java Runtime Environment (JRE):
• JRE is part of the JDK. If a system has only JRE installed, then the user can only run the
program.
Garbage Collector:
• JVM has a program known as Garbage Collector.
• Garbage Collectors recollect or delete unreferenced objects.
• Garbage Collector makes the life of a developer/ programmer easy.
Classpath:
• classpath is the path where the Java compiler and the Java runtime search the .class file to
load.
• Many inbuilt libraries are provided by the JDK. However, if someone wants to use the external
libraries, it should be added to the classpath.
SandBox Execution:
• Java programs are executed in different environment, which gives liberty to users to execute
their own applications without impacting the underlying system using the bytecode verifier.
The Bytecode verifier also gives extra security as it checks the code for the violation of access.
Advantages of Java
Platform independent
Object-Oriented
Security
Large community
Enterprise-level applications
Disadvantages of Java
Performance
Memory management
1.3 DATA TYPES
• Java is a statically-typed programming language. It means, all variables must be declared
before its use.
• Data types specify the different sizes and values that can be stored in the variable.
• Java has two categories in which data types are segregated
1. Primitive Data Type:
Boolean, char, int, short, byte, long, float, and double.
2. Non-Primitive Data Type or Object Data type:
String, Array, etc.
Primitive data are only single values and have no special capabilities. There are 8 primitive data
types.
float floatVar;
Size :4 bytes (32 bits).
7. Double Data Type
• The double data type is a double-precision 64-bit.
Syntax:
double doubleVar;
Size: 8 bytes or 64 bits.
8. Char Data Type
• The char data type is a single 16-bit Unicode character.
Syntax:
char charVar;
Size:2 bytes (16 bits).
Example:Primitive Data type Output
class GFG { char: G
public static void main(String args[]) integer: 89
{ byte: 4
char a = 'G'; short: 56
int i = 89; float: 4.7333436
byte b = 4; double: 4.355453532
short s = 56; long: 12121
double d = 4.355453532; Boolean:
float f = 4.7333434f;
long l = 12121;
boolean bool = true;
//Print Values
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
System.out.println("Boolean: " + bool);
}
}
II)Non-Primitive Data Type or Reference or Object Data Types
• It will contain a address of variable values because it won’t store the variable value directly
in memory.
SRRCET/CSE/III SEM/CS3391_OOPS 9 PREPARED BY DIVYA.A.S
CS3391-OBJECT ORIENTED PROGRAMMING
1. Strings
• Strings are defined as an array of characters.
• String is designed to hold a sequence of characters in a single variable whereas,
• Character array is a collection of separate char-type entities.
• Java strings are not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:String Data Type Output:
class Main { Java
public static void main(String[] args) { Python
String first = "Java";
String second = "Python";
System.out.println(first);
System.out.println(second);
}
}
2. Arrays
• An Array is a group of variables that are referred to by a common name.
• In Java, all arrays are dynamically allocated.
• Since arrays are objects in Java, we can find length using member length.
• A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered and each has an index beginning with 0.
1.4 VARIABLES
• Variables are the data containers that save the data values during Java program execution.
• Every Variable is assigned a data type that designates the type and quantity of value it can
hold.
• A variable is a memory location name for the data.
• In Java, all variables must be declared before use.
Rules to Declare a Variable
• A variable name can consist of Capital letters A-Z, lowercase letters a-z,digits 0-9, and
special characters such as _ underscore and $ dollar sign.
• The first character must not be a digit.
• Blank spaces cannot be used in variable names.
• Java keywords cannot be used as variable names.
• Variable names are case-sensitive.
Variable Declaration
Syntax:
data_type data_name;
Ex:
int a;
Variable Initialization
SRRCET/CSE/III SEM/CS3391_OOPS 10 PREPARED BY DIVYA.A.S
CS3391-OBJECT ORIENTED PROGRAMMING
Syntax:
data_type data_name=value;
Ex: int a=80;
Variable Type
1. Local Variables
• A variable defined within a block or method or constructor is called a local variable.
• The scope of these variables exists only within the block.
• We can access these variables only within that block.
• Initialization of the local variable is mandatory.
2. Instance Variables
• Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block.
• These variables are created when an object of the class is created and destroyed when the
object is destroyed.
• Initialization of an instance variable is not mandatory.
• Instance variables can be accessed only by creating objects.
3. Static Variables
• Static variables are also known as class variables.
• These variables are declared similarly to instance variables.
• Static variables are declared using the static keyword within a class outside of any method,
constructor, or block.
• Initialization of a static variable is not mandatory.
• Its Default value for String is null, for float is 0.0f, for int is 0.
• Access a static variable without the class name.
• But for accessing the static variable of a different class, we must mention the class name as
2 different classes might have a static variable with the same name.
Example Program: Variable Types Output:
class variables{ 35
int amount = 100; //instance variable 2315
static int pin = 2315; //static variable
public static void main(String[] args)
{
int age = 35; //local variable
System.out.println(age);
System.out.println(pin);
}
}
Syntax:
target_variable=(target_data_type)source_variable;
Example:
double d=90;
int i;
i=(int)d;
This process is known as Type Casting.
Example Program: Type Conversion Output:
class typecast { int=10
public static void main(String[] args) { double=10.0
double d; byte=10
int i=10;
byte b;
d=i; //Widening Type Conversion
System.out.println("int=" +i);
System.out.println("double=" +d);
b=(byte)i;//Narrow Type Conversion
System.out.println("byte=" +b);
}
}
1.5 ARRAYS
• An array is a collection of similar type of elements which has contiguous memory location.
• Array in Java is index-based.
• Array index starts from 0 to arraySize-1;
a[1]=20; 50
a[2]=70;
a[3]=40;
a[4]=50;
System.out.println(“Array Length:”+a.length);
//traversing array
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
2.Multidimensional Arrays
• A multidimensional array is an array of arrays. That is, each element of a multidimensional
array is an array itself.
• For example,
double[][] matrix = {{1.2, 4.3, 4.0}, {4.1, -1.1}};
1.6 OPERATORS
• Operators in Java are the symbols used for performing specific operations in Java.For
example: +, -, *, / etc.
1.Arithmetic Operators
• Arithmetic operators are used to perform common mathematical operations.
2.Unary Operators
Unary operators require only one operand to perform operations like incrementing/decrementing a
value by one, negating an expression, or inverting the value of a boolean.
•
Example Program: Shorthand Output:
Operator(shorthand.java)
import java.io.*; f += 3: 10
class shorthand f -= 2: 8
{ f *= 4: 32
public static void main(String[] args) f /= 3: 10
{ f %= 2: 0
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
}
}
4. Relational Operators
Relational operators compare two operands and return a boolean value. They are used in control flow
statements to make decisions.
5.Logical Operators:
Logical operators are used to perform logical “AND”, “OR” and “NOT” operations, i.e. the function
similar to AND gate and OR gate in digital electronics
Ex:
student s=new student();
student s2=s;
Both objects s and s2 takes same memory location.
Example Program 1: (Main.java)
class Box
{ Output:
double width,height,depth; Vol:3000.0
}