Updated Notes Unit I
Updated Notes Unit I
Updated Notes Unit I
Object
o Objects are basic run-time entities in object oriented programming.
o Object represent a person, place or any item that a program handles.
o A single class can create any number of objects.
o Object occupies memory
o Every object has data structures called attributes (data) and behaviour called
operations (methods/fucntions).
o Declaring objects -
The syntax for declaring object is - Class Name Object_Name;
Fruit f1;
For the class Fruit the object f1 can be created.
Classes
o A class is a user defined prototype for object creation.
o Class does not occupy memory.
o In Java, class keyword is used to declare the class.
o A class can be defined as an entity in which data and functions are put
together.
o The concept of class is similar to the concept of structure in C.
Syntax :
class name_of_class
{
private:
variables declarations;
function declarations;
public:
variable declarations;
function declarations;
}; do not forget semicolon
Abstraction
o Definition: Abstraction means representing only essential features by
hiding all the implementation details.
o In object oriented programming languages like C++, or Java class is an entity
used for data abstraction purpose.
Example
class Student
int roll;
public;
void display();
In main function we can access the functionalities using object. For instance
Student obj;
obj.input();
obj.display ();
Inheritance:
o Definition: Inheritance is a property by which the new classes are created
using the old classes. In other words the new classes can be developed using
some of the properties of old classes.
o Inheritance support hierarchical structure.
o The old classes are referred as base classes and the new classes are referred as
derived classes. That means the derived classes inherit the properties (data and
functions) of base class.
Example: Here the Shape is a base class from which the Circle, Line and
Rectangle are the derived classes. These classes inherit the functionality
draw() and resize(). Similarly the Rectangle is a base class for the derived
class Square. Along with the derived properties the derived class can have its
own properties. For example the class Circle may have the function like
backgrcolor() for defining the back ground color.
Polymorphism
o Definition: Polymorphism in java is a concept by which we can perform a
single action by different ways.
o Polymorphism is derived from 2 (two) greek words: poly and morphs.
o The word “poly” means many and “morphs” means forms. So, polymorphism
means many forms.
o Real Time Example:
In a class there will be more students with a same name. We can
differentiate the students with their initial, register number etc.,
Object Oriented
In java, everything is an object which has some data and behaviour. Java can be
easily extended as it is based on Object Model. Following are some basic concept of
OOP's.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Secure
The instructions of bytecode is executed by the Java Virtual Machine (JVM). That
means JVM converts the bytecode to machine readable form.
JVM understand only the bytecode and therefore any infectious code cannot be
executed by JVM. No virus can infect bytecode. Hence it is difficult to trap the
internet and network based applications by the hackers.
Robust
Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java.
Portable
Java program written in one environment can be executed in another environment.
Multithreading
Concurrent execution of several parts of same program at the same time.
The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area.
Distributed Applications
This feature is very much useful in networking environment.
In Java, two different objects on different computers can communicate with each
other.
This can be achieved by Remote Method Invocation (RMI).
Architectural Neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
Operators
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operators
Unary Operators
Ternary Operator
Instanceof operator
Arithmetic operators
Java arithmetic operators are used to perform addition, subtraction, multiplication,
and division. They act as basic mathematical operations.
Operator Description
% remainder of division
Increment operator increases integer
++
value by one
}
}
Relation operators
Relational operators are used to test comparison between operands or values. It can be
use to test whether two values are equal or not equal or less than or greater than etc.
Operator Description
Logical Operators
Logical operators are used to check whether an expression is true or false.
Operator Meaning
&& (Logical AND) true only if both expression1 and
expression2 are true
|| (Logical OR) true if either expression1 or expression2 is
true
! (Logical NOT) true if expression is false and vice versa
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Assignment Operators
Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 5 is assigned to the variable age.
Operator Example Equivalent to
= a=b; a=b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
}
}
Bitwise operators
Bitwise operators are used to perform operations bit by bit.
Java defines several bitwise operators that can be applied to the integer types long, int,
short, char and byte.
The following table shows all bitwise operators supported by Java.
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be
shifted and the right operand specifies the number of positions that the bits in the value are to
be shifted. Both operands have the same precedence.
Program for Bitwise Operators Output
public class Main{ 0
public static void main(String[] args) { 7
int a=4, b=3; 7
System.out.println(a&b); 16
System.out.println(a|b); 1
System.out.println(a^b); -5
System.out.println(a<<2);
System.out.println(a>>2);
System.out.println(~a);
}
}
Unary Operator
Incrementing/decrementing a value by one
Java also provides increment and decrement operators: ++ and -- respectively. ++ increases
the value of the operand by 1, while -- decrease it by 1.
Arrays
An array is a collection of similar data types.
Array is a container object that hold values of homogeneous type. It is also known as
static data structure because size of an array must be specified at the time of its
declaration.
Array starts from zero index and goes to n-1 where n is length of the array.
Each element in the array can be accessed by using the index number.
In java array is an Object.
There are two types of arrays –
o One dimensional arrays
o Two dimensional arrays
One Dimensional Array
o Represented using single index
o The syntax of declaring array is –
data_type array_name[ ];
o and to allocate the memory –
array_name=new data_type[size];
o We can combine both declaration and initialization in a single statement.
Datatype[] arrayName = new datatype[size]
Initializing All Array Elements to Zero Output
public class InitializeDemo 0
{ 0
public static void main(String[] args) 0
{ 0
//Declaring array 0
int[] intArray;
//Initializing to Zero
intArray = new int[5];
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
For string array the default value is null Output
public class InitializeDemo null
{ null
public static void main(String[] args) null
{ null
//Declaring array null
String[] strArray;
//Initializing to Zero
strArray = new String[5];
//Printing the values
for(int i = 0; i < strArray.length; i++)
System.out.println(strArray[i]);
}
}
Program to take user input to initialize an array by using Output
the Scanner class
import java.util.Scanner; Enter the values:
5
public class InitializeDemo 10
{ 15
public static void main(String[] args) 20
{ 25
//Declaring array The array contains:
int[] intArray; 5
//Defining the array length 10
intArray = new int[5]; 15
20
Scanner s = new Scanner(System.in); 25
System.out.println("Enter the values: ");
//Initializing
for(int i = 0; i < intArray.length; i++)
intArray[i] = s.nextInt();
s.close();
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
height=h;
width=w;
void area()
class Constr_Demo {
}
Properties of constructor
Name of constructor must be the same as the name of the class for which it is being
used.
The constructor must be declared in the public mode.
The constructor gets invoked automatically when an object gets created.
The constructor should not have any return type. Even a void data type should not be
written for the constructor.
The constructor cannot be used as a member of union or structure.
The constructors can have default arguments.
The constructor cannot be inherited.
Constructor can make use of new or delete operators for allocating or releasing
memory respectively.
Constructor cannot be virtual.
Multiple constructors can be used by the same class.
When we declare the constructor explicitly then we must declare the object of that
class.
Access Specifiers
Access modifiers control access to data fields, methods, and classes. There are three
modifiers used in Java –
public
private
default modifier
public allows classes, methods and data fields accessible from any class
private allows classes, methods and data fields accessible only from within the own
class.
If public or private is not used then by default the classes, methods, data fields are
assessable by any class in the same package. This is called package-private or
package-access. A package is essentially grouping of classes.
Example program to demonstrate the usage of access specifiers.
package Test; package another Test
{ {
public int a; void My_method()
} obj.c;//error:cannot access
} obj.fun2()//error:cannot access
} }
} }
void My_method() {
obj.a;//allowed
obj.b;//allowed
obj.c;//error:cannot access
obj.fun1();//allowed
obj.fun2();//allowed
obj.fun3();//error:cannot access
}
Protected mode is another access specifier which is used in inheritance.
The protected mode allows accessing the members to all the classes and subclasses in
the same package as well as to the subclasses in other package.
But the non subclasses in other package cannot access the protected members.
The effect of access specifiers for class, subclass or package is enlisted below-
Static Members
The static members can be static data member or static method.
The static members are those members which can be accessed without using object.
Program to introduce the use of the static method Output
and static variables
class StaticProg a= 10
{ b= 20
System.out.println("b= "+b);
System.out.println("a = "+a);
class AnotherClass
StaticProg.fun(20);
}
}
Program Explanation
In above program, we have declared one static variable a and a static member
function fun(). These static members are declared in one class StaticProg. Then we have
written one more class in which the main method is defined. This class is named as
AnotherClass. From this class the static members of class StaticProg are accessed without
using any object.
Syntax:
ClassName.staticMember
Points to Remember
In Java the main is always static method.
The static methods must can access only static data.
The static method can call only the static method and cannot call a non-
static method.
The static method cannot refer to this pointer.
The static method cannot refer to super method.
Data types represent the different values to be stored in the variable. In java, there are two
categories of data types:
Simple if Statement
An if statement consists of a Boolean expression followed by one or more statements
Block of statement is executed when the condition is true otherwise no statement will
be executed.
Syntax:
if(<conditional expression>)
{
< Statement Action>
}
//Java Program for implementation of if statement Output
import java.util.Scanner; Enter the age: 21
public class Main The person is eligible to vote
{
public static void main(String []args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc=new Scanner(System.in);
System.out.println("Enter the age: ");
int age=sc.nextInt();
if(age>=18)
{
System.out.println("The person is eligible to vote");
}
}
}
if-else statement
The if-else statement is used for testing condition. If the condition is true, if block
executes otherwise else block executes.
The else block execute only when condition is false.
Syntax:
if(<conditional expression>)
{
< Statement Action1>
}
else
{
< Statement Action2>
}
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
default:
code to be executed if all cases are not matched;
}
Program for Switch Statement Output
public class SwitchExample { 20
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or
30");
}
}
}
while(condition)
{
//code for execution
}
Example Program for while loop Output
do-while loop
In Java, the do-while loop is used to execute statements again and again.
This loop executes at least once because the loop is executed before the condition is
checked.
It means loop condition evaluates after executing of loop body.
The main difference between while and do-while loop is, in do while loop condition
evaluates after executing the loop.
Syntax:
do
{
//code for execution
}
while(condition);
Example for do while loop Output
public class DoWhileDemo1
{
public static void main(String[] args)
{
inti=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
for-each Loop
In Java, for each loop is used for traversing array or collection elements. In this loop,
there is no need for increment or decrement operator.
Syntax:
for(Type var:array)
{
//code for execution
}
Example:
For Loop
The for loop is used for executing a part of the program repeatedly.
When the number of execution is fixed then it is suggested to use for loop.
Syntax:
for(initialization;condition;increment/decrement)
{
//statement
}
For loop Parameters:
To create a for loop, we need to set the following parameters.
1) Initialization
It is the initial part, where we set initial value for the loop. It is executed only once at the
starting of loop. It is optional, if we don’t want to set initial value.
2) Condition
It is used to test a condition each time while executing. The execution continues until the
condition is false. It is optional and if we don’t specify, loop will be inifinite.
3) Statement
It is loop body and executed every time until the condition is false.
4) Increment/Decrement
It is used for set increment or decrement value for the loop.
Flowchart
Example Output
public class ForDemo1
{
public static void main(String[] args)
{
int n, i;
n=2;
for(i=1;i<=10;i++)
{
System.out.println(n+"*"+i+"="+n*i);
}
}
}
Break Statement
In Java, break is a statement that is used to break current execution flow of the
program.
We can use break statement inside loop, switch case etc.
If break is used inside loop then it will terminate the loop.
If break is used inside the innermost loop then break will terminate the innermost loop
only and execution will start from the outer loop.
If break is used in switch case then it will terminate the execution after the matched
case. Use of break, we have covered in our switch case topic.
Example for break statement Output
public class BreakExample { 1
public static void main(String[] args) { 2
//using for loop 3
for(int i=1;i<=10;i++){ 4
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Continue statement
In Java, the continue statement is used to skip the current iteration of the loop. It jumps to
the next iteration of the loop immediately. We can use continue statement with for loop,
while loop and do-while loop as well.
Example for continue statement Output
1
public class ContinueDemo1 2
{ 3
public static void main(String[] args) 4
{ 5
for(inti=1;i<=10;i++) 6
{ 7
if(i==5) 8
{ 9
continue; 10
}
System.out.println(i);
}
}
}
Variables
A variable is an identifier that denotes the storage location.
Variable is a fundamental unit of storage in Java.
The variables are used in combination with identifiers, data types, operators and some
value for initialization. The variables must be declared before its use.
The syntax of variable declaration will be -
data_type name_of_variable [=initialization][,=initialization][,…];
Following are some rules for variable declaration -
The variable name should not with digits.
No special character is allowed in identifier except underscore.
There should not be any blank space with the identifier name.
The identifier name should not be a keyword.
The identifier name should be meaningful.
Local Variable in Java
A local variable is a variable which has value within a particular method or a function.
Outside the scope of the function the program has no idea about the variable.
class DataFlair {
int a = 9,
b = 10;
void LearnJava {
int local_j = 45; // A local variable
String s = ”DataFlair Training”; //A local variable
}
}
Java Instance Variable
Instance variables are those which are declared inside the body of a class but not within any
methods.
import java.io. * ;
class Person {
int height,
weight; // Instance Variables
Person(int h, int w) {
this.height = h;
this.weight = w;
}
void run() {
System.out.println(“Huff Puff”);
}
void print() {
System.out.println(“Now my weight is” + this.weight);
}
public static void main(String[] args) throws IOException {
Person A = new Person(170, 65);
A.run();
A.print();
}
}
Output
Huff Puff
Now my weight is 65.
Static Variables in Java
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
import java.io. * ;
class DataFlair {
static int studentCount;
DataFlair() {
studentCount = 15;
}
void addStudent() {
studentCount++;
}
Methods
We write a method once and use it many times. We do not require to write code again
and again.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. Java
provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our
application
Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
Default: It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. Suppose, if
we are creating a method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method.
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Parameter Passing
1. Call by value
2. Call by reference
• In the call by value method the value of the actual argument is assigned to the formal
parameter. If any change is made in the formal parameter in the subroutine definition then
that change does not reflect the actual parameters.
Java Program
{
a=a+5;
b=b+5;
int a,b;
a=10;b=20;
System.out.println("a= "+a);
System.out.println("b= "+b);
obj1.Fun(a,b);
System.out.println("a= "+a);
System.out.println("b= "+b);
Output
a= 10
b= 20
The values of a and b after function call
a= 10
b= 20
Java Comments
The java comments are statements that are not executed by the compiler and
interpreter
The comments can be used to provide information or explanation about the variable,
method, class or any statement.
It can also be used to hide program code for specific time.
Types of Java Comments
There are 3 types of comments
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
1) Java Single Line Comment
The single-line comment is used to comment only one line of the code. It is the
widely used and easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not
executed by Java.
Syntax:
The multi-line comment is used to comment multiple lines of code. It can be used to
explain a complex code snippet or to comment multiple lines of code at a time (as it
will be difficult to use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
3) Java Documentation Comment
Documentation comments are usually used to write large programs for a project or
software application as it helps to create documentation API. These APIs are
needed for reference, i.e., which classes, methods, arguments, etc., are used in the
code.
To create documentation API, we need to use the javadoc tool. The documentation
comments are placed between /** and */.
Syntax
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
@code {@code text} To show the text in code font without interpreting it
as html markup or nested javadoc tag.
@since @since release To add "Since" heading with since text to generated
documentation.
@return @return description Required for every method that returns something
(except void)
Example:
import java.io.*;
/**
* <h2> Calculation of numbers </h2>
* This program implements an application
* to perform operation such as addition of numbers
* and print the result
* <p>
* <b>Note:</b> Comments make the code readable and
* easy to understand.
*
* @author Anurati
* @version 16.0
* @since 2021-07-06
*/
public class Calculate{
/**
* This method calculates the summation of two integers.
* @param input1 This is the first parameter to sum() method
* @param input2 This is the second parameter to the sum() method.
* @return int This returns the addition of input1 and input2
*/
public int sum(int input1, int input2){
return input1 + input2;
}
/**
* This is the main method uses of sum() method.
* @param args Unused
* @see IOException
*/
public static void main(String[] args) {
Calculate obj = new Calculate();
int result = obj.sum(40, 20);
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program.
To write the statements in the documentation section, we use comments. The comments may
be single-line, multi-line, and documentation comments.
Package Declaration
The package declaration is optional. It is placed just after the documentation section.
In this section, we declare the package name in which the class is placed.