Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Updated Notes Unit I

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

UNIT I

INTRODUCTION TO OOP AND JAVA


Overview of OOP – Object oriented programming paradigms – Features of Object
Oriented Programming – Java Buzzwords – Overview of Java – Data Types, Variables
and Arrays – Operators – Control Statements – Programming Structures in Java –
Defining classes in Java – Constructors -Methods -Access specifiers - Static members-
Java Doc comments

Object Oriented Programming Paradigms


 The object oriented programming approach is developed in order to remove some of
the flaws of procedural programming.
 OOP has a complete focus on data and not on the procedures. In OOP, the data can be
protected from accidental modification.
 In OOP the most important entity called object is created.
 Each object consists of data attributes and the methods. The methods or functions
operate on data attributes.
Difference Between Procedural Programming and Object Oriented Programming (Nov-
Dec 2022)
Procedure-Oriented Programming Object-Oriented Programming
 Divided  In POP, program is divided into small  In OOP, program is divided into
into parts called functions. parts called objects.
 Importance  In POP, Importance is not given to data  In OOP, Importance is given to the
but to functions as well as sequence of data rather than procedures or
actions to be done. functions because it works as a
real world.
 Approach  POP follows Top Down approach.  OOP follows Bottom Up approach.
 Access  POP does not have any access specifier.  OOP has access specifiers named
Specifiers Public, Private, Protected, etc.
 Data  In POP, Data can move freely from  In OOP, objects can move and
Moving function to function in the system. communicate with each other
through member functions.
 Expansion  To add new data and function in POP is  OOP provides an easy way to add
not so easy. new data and function.
 Data Access  In POP, Most function uses Global data  In OOP, data cannot move easily
for sharing that can be accessed freely from function to function, it can be
from function to function in the system. kept public or private so we can
control the access of data.
 Data Hiding  POP does not have any proper way for  OOP provides Data Hiding so
hiding data so it is less secure. provides more security.
 Overloadin  In POP, Overloading is not possible.  In OOP, overloading is possible in
g the form of Function Overloading
and Operator Overloading.
 Examples  Example of POP are: C, VB,  Example of OOP are: C++, JAVA,
FORTRAN, Pascal. VB.NET, C#.NET.

Features of Object Oriented Programming (Nov – Dec


2022)
Fundamental principles of OOPS
OOPS Concepts

 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

Difference between class and Objects


Object Class
 Object is an instance of a class.  Class is a blueprint or template
from which objects are created
 Object is a real world entity such  Class is a group of similar objects.
aspen, laptop, mobile, bed,
keyboard, mouse, chair etc
 Object is a physical entity.  Class is a logical entity
 Object is created through new  Class is declared using class
keyword mainly e.g. keyword
Student s1=new Student(); e.g.class Student{}
 Object is created many times as  Class is declared once.
per requirement.
 Object allocates memory when it is  Class doesn't allocated memory
created. when it is created.
 Encapsulation
o Definition: The wrapping up of data and methods into a single unit is known
as encapsulation.
o The data inside that class is accessible by the function in the same class. It is
normally not accessible from the outside of the component.
o This protection mechanism is called data hiding or information hiding.

 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;

char name [10];

public;

void input ();

void display();

In main function we can access the functionalities using object. For instance
Student obj;

obj.input();

obj.display ();

Thus only abstract representation can be presented, using class.

 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.,

Features of Java/ Java Buzzwords/Characteristics of


Java
 Platform Independent
 Object Oriented Concepts
 Simple
 Secure
 Robust
 Portable
 Multithreading
 Distributed Applications
 Architectural Neutral
Platform Independent:
 On compilation Java program is compiled into bytecode.
 Byte code is an intermediate code generated from the source code by java compiler
and it is platform independent.
 This bytecode is platform independent and can be run on any machine, plus this
bytecode format also provide security.
 Any machine with Java Runtime Environment can run Java Programs.
 Java is guaranteed to be write-once, run-anywhere language.

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

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division
Increment operator increases integer
++
value by one

Decrement operator decreases integer


--
value by one

Example program for Arithmetic Operators Output


import java.util.Scanner; Enter two values
class Arithmetic_operators1{ 10
public static void main(String args[]) 2
{ Addition: 12
Scanner in1=new Scanner(System.in); Subtraction: 8
System.out.println("Enter two values"); Multiplication: 20
int a=in1.nextInt(); Division: 5
int b=in1.nextInt(); Remainder: 1
int c; Increment Operator: 11
c=a+b; decrement Operator: 10
System.out.println("Addition: "+c);
c=a-b;
System.out.println("Subtraction: "+c);
c=a*b;
System.out.println("Multiplication: "+c);
c=a/b;
System.out.println("Division: "+c);
b=3;
c=a%b;
System.out.println("Remainder: "+c);
a=++a;
System.out.println("Increment Operator: "+a);
a=--a;
System.out.println("decrement Operator: "+a);

}
}
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

== Check if two operand are equal

!= Check if two operand are not equal.


> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Example program for Relational Operators Output


import java.util.Scanner; Enter two values
class Arithmetic_operators1{ 40
public static void main(String args[]) 30
{ a == b = false
Scanner in1=new Scanner(System.in); a != b = true
System.out.println("Enter two values"); a > b = true
int a=in1.nextInt(); a < b = false
int b=in1.nextInt(); b >= a = false
System.out.println("a == b = " + (a == b) ); b <= a = true
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) );
}
}

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

Example program for logical Operators Output


class Main { true
public static void main(String[] args) { false
true
// && operator true
System.out.println((5 > 3) && (8 > 5)); // true false
System.out.println((5 > 3) && (8 < 5)); // false true
false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! 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;

Program for Assignment Operators Output


public class Assignment{ 10
public static void main(String[] args) { 30
int a = 10; 20
int b=20; 200
int c; 20
System.out.println(c = a); // Output =10 0
System.out.println(b += a);// Output=30
System.out.println(b -= a);// Output=20
System.out.println(b *= a);// Output=200
System.out.println(b /= a);// Output=20
System.out.println(b %= a);// Output=0

}
}

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 AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift


Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b

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.

1. public class OperatorExample{ 10


12
2. public static void main(String args[]){ 12
3. int x=10; 10
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Java Ternary Operator/ Conditional Operator


 The ternary operator (conditional operator) is shorthand for the if-then-else statement.
For example,
 variable = Expression ? expression1 : expression2
Here's how it works.

 If the Expression is true, expression1 is assigned to the variable.


 If the Expression is false, expression2 is assigned to the variable.
Example for Ternary Operator Output
class Java { Leap year
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}

Java instanceof Operator


 The instanceof operator checks whether an object is an instanceof a particular class.
Example for Ternary Operator Output
class Main { Is str an object of String?
public static void main(String[] args) { true

String str = "Akshaya";


boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}

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();

System.out.println("The array contains: ");


//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
Initializing an Array at the time Declaration Output
public class InitializeDemo 3
{ 6
public static void main(String[] args) 9
{ 12
//Declaring array 15
int[] intArray = {3,6,9,12,15};

//Printing the values


for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}

Two – dimensional Array (2D-Array)


 Two – dimensional array is the simplest form of a multidimensional array.
 Two Dimensional Array can be represented as the collection of rows and columns.
 Declaration – Syntax:
o data_type[][] array_name = new data_type[x][y];
 Initialization – Syntax:
o array_name[row_index][column_index] = value;
o For example: arr[0][0] = 1;
 Direct Method of Declaration: Syntax:
o data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};

Java program that takes a two-dimensional array as input. Output


import java.util.Scanner;
public class ArrayInputExample2
{
public static void main(String args[])
{
int m, n, i, j;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of rows: ");
//taking row as input
m = sc.nextInt();
System.out.print("Enter the number of columns: ");
//taking column as input
n = sc.nextInt();
// Declaring the two-dimensional matrix
int array[][] = new int[m][n];
// Read the matrix values
System.out.println("Enter the elements of the array: ");
//loop for row
for (i = 0; i < m; i++)
//inner for loop for column
for (j = 0; j < n; j++)
array[i][j] = sc.nextInt();
//accessing array elements
System.out.println("Elements of the array are: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
//prints the array elements
System.out.print(array[i][j] + " ");
//throws the cursor to the next line
System.out.println();
}
}
}
Program for direct method of declaration Output

import java.io.*; arr[0][0] = 1


class GFG { arr[0][1] = 2
arr[1][0] = 3
public static void main(String[] args) arr[1][1] = 4
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println("arr[" + i + "][" + j + "] = "+ arr[i][j]);
}
}
Accessing elements of Two Dimensional Array Output

import java.io.*; arr[0][0] = 1

class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };

System.out.println("arr[0][0] = " + arr[0][0]);


}
}

Constructors (Nov/Dec 2022)


 Definition: The constructor is a specialized method for initializing objects.
 Name of the constructor is same as that of its class name. In other words, the name of
the constructor and class name is same.

 Whenever an object of its associated class is created, the constructor is invoked


automatically.
 The constructor is called constructor because it creates values for data fields of
class.
Program for Default and parameterised constructor Output
public class Rectangle 1 { F:\test>javac Rectangle1.java
int height; F:\test>java Constr_Demo
Data fields
int width; Simple constructor: values
are initialised...
Rectangle1()
Now, The function is called...
{
The area is 200
System.out.println(" Simple constructor: values are initialised...");
Parameterised constructor:
height=10; values are initialised...

width=20; Now, The function is called...

} The area is 220

Rectangle1 (int h,int w) F:\test>

System.out.println(" Parameterised constructor: values are initialised...");

height=h;

width=w;

void area()

System.out.println("Now, The function is called...");

int result height*width;

System.out.println("The area is "+result);

class Constr_Demo {

public static void main(String args[])

Rectangle1 obj = new Rectangle 1();

obj.area();//call the to method


Rectangle1 obj1 = new Rectangle 1(11,20);

obj1.area();//call the to method

}
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.

Defining classes in Java


Defining a class
 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:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
o A variable which is created inside the class but outside the method is known as an
instance variable.
o Instance variable doesn't get memory at compile time.
o It gets memory at runtime when an object or instance is created.
o That is why it is known as an instance variable.
Object and Class Example: main within the class
Here, we are creating a main() method inside the class.
Java Program to illustrate how to define a class and Output
fields
1. class Student{ 0
int id; null
1. String name;
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Object and Class Example: main outside the class
o In real time development, we create classes and use it from another class.
o It is a better approach than previous one.
o Let's see a simple example, where we are having main () method in another class.

Java Program to demonstrate having the main method Output


in another class
class Student{ 0
int id; null
String name;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object
There are 3 ways to initialize object in Java.
o By reference variable
o By method
o By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
Object and Class Example: Initialization through Output
reference
class Student{ 101
int id; Akshaya
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Akshaya";
System.out.println(s1.id+" "+s1.name);
}
}

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.
Object and Class Example: Initialization through method Output
class Student{ 111 Karan
int rollno; 222 Aryan
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
As you can see in the above figure, object gets the memory in heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both
are reference variables that refer to the objects allocated in memory.
Object and Class Example: Initialization through a constructor
Object and Class Example: Initialization through a constructor Output
class Employee{ 101 ajeet 45000.0
int id; 102 irfan 25000.0
String name; 103 nakul 55000.0
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}

Object & Class Example: Rectangle Output


class Rectangle{ 55
int length; 45
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea()
{System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),
r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

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 class class1 public class class3

{ {
public int a; void My_method()

int b; class1 obj=new class1();

private int c; obj.a;//allowed

public void fun1() { obj.b;// error:cannot access

} obj.c;//error:cannot access

void fun2() { obj.fun1();//allowed

} obj.fun2()//error:cannot access

private void fun3() { obj.fun3()//error:cannot access

} }

} }

public class class2

void My_method() {

class 1 obj=new class1();

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

static int a = 10; a= 10

static void fun(int b)

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

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

class AnotherClass

public static void main(String[] args)

System.out.println("a= "+Static Prog.a);

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.

Java Data types (Nov/Dec 2021)

 Java is a statically typed and also a strongly typed language.


 In Java, each type of data (such as integer, character, hexadecimal, etc. ) is predefined
as part of the programming language and all constants or variables defined within a
given program must be described with one of the data types

Data types represent the different values to be stored in the variable. In java, there are two
categories of data types:

 Primitive data types


 Non-primitive data types
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.
1. Integers
 This group includes byte, short, int, and long.
 All of these are signed, positive and negative values.
Name Width in bits Range
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
2. Float-point numbers:
 They are also known as real numbers.
 This group includes float and double, which represents single- and double-
precision numbers, respectively.
Name Width in bits Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e–045 to 3.4e+038
3. Characters - This group includes char, which represents symbols in a character set like
letters and numbers. Char is 16-bit type. The range of a char is 0 to 65,536.
4. Boolean: This group includes boolean. It can have only one of two possible values, true
or false.

This program introduces use of various Output


data type in the program
class DatatypeDemo The value of a=: 10
{ The value of b=: 1280
public static void main(String args[]) The value of c=: 1280000
{ The value of d=: 1280000000
byte a=10; The value of e=: 99.9998
short b=10*128; The value of f=: a
int c=10000* 128; The value of f after increment=: b
long d=10000*1000*128; The value of g=: true
double e=99.9998; The value of h=: false
char f='a';
boolean g=true;
boolean h=false;
dynamic initialization
System.out.println("The value of a=: "+a);
System.out.println("The value of b=: "+b);
System.out.println("The value of c=: "+c);
System.out.println("The value of d=: "+d);
System.out.println("The value of e=: "+e);
System.out.println("The value of f=: "+f);
f++;
System.out.println("The value of f after
increment=: "+f);
System.out.println("The value of g=: "+g);
System.out.println("The value of h=: "+h);
}
}

Control Statements (Nov/Dec


2020)
 Control statements in Java is one of the fundamentals required for Java Programming.
 It allows the smooth flow of a program.
 Control Statements are divided into three categories, namely
o Selection statements/ Decision making statements
o Iteration Statements/ Looping Statements
Selection Statements
 Simple if statement
 if else statement
 nested if statement
 if-else-if ladder
 Switch statement

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>
}

//Java Program for implementation of if-else statement Output


import java.util.Scanner; Enter a number: -9
public class Main The entered number
{ -9 is negative.
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 a number: ");
int num=sc.nextInt();
if(num>0)
{
System.out.println("The entered number "+num+" is positive.");
}
else
{
System.out.println("The entered number "+num+" is negative.");
}
}
}
Nested if statement
 The nested if statement represents the if block within another if block.
 Syntax:
if(condition1)
{
if(condition2)
{
//Executes this block if condition is True
}
else
{
//Executes this block if condition is false
}
}
else
{
//Executes this block if condition is false
}

Example Program for Nested if else Statement Output


public class code { Equal
public static void main(String[] args) {
int a = 2;
int b = 2;
int c = 2;
if (a == b) {
if (a == c) {
// all are equal
System.out.println("Equal");
} else {
// a!=c
System.out.println("Not equal");
}
} else {
// a!=b
System.out.println("Not equal");
}
}
}
Java if-else-if ladder Statement
 The if-else-if ladder statement executes one condition from multiple statements.
 Syntax
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Example for IfElseIfExample Output


public class IfElseIfExample { C grade
public static void main(String[] args) {
int marks=65;

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!");
}
}
}

Java Switch Statement


 The Java switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement.
 Points to remember
o There can be one or N number of case values for a switch expression.
o The case value must be of switch expression type only. The case value must
be literal or constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-
time error.
o Each case statement can have a break statement which is optional.
 Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

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");
}
}
}

Iteration statements (Nov / Dec 2021)


 Iteration statements execute a block of code for several numbers of times until
the condition is true.
while statement
 The while statement is one of the looping constructs control statement that
executes a block of code while a condition is true.
 The loop will stop the execution if the testing expression evaluates to false.
 The loop condition must be a boolean expression.
 Syntax:

while(condition)
{
//code for execution
}
Example Program for while loop Output

public class WhileDemo1


{
public static void main(String[]
args)
{
inti=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}

Program for Infinite while loop


public class WhileDemo2
{
public static void main(String[] args)
{
while(true)
{
System.out.println("infinitive while loop");
}
}
}

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);
}
}

Infinite do while Output


public class DoWhileDemo2
{
public static void main(String[] args)
{
do
{
System.out.println("infinitive do while
loop");
}while(true);
}
}

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:

public class ForEachDemo1


{
public static void main(String[] args)
{
inta[]={20,21,22,23,24};
for(int i:a)
{
System.out.println(i);
}
}
}
Output

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);
}
}
}

Nested for loop Output

public class ForDemo2


{
public static void main(String[] args)
{
for(inti=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}

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++;
}

public static void main(String[] args) throws IOException {


DataFlair java = new DataFlair();
DataFlair python = new DataFlair();
java.addStudent();
python.addStudent();
System.out.println("Total Students " + studentCount);
}
}
Output:
Total Students 17

Methods

 A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation.

 It is used to achieve the reusability of code.

 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

Single-word method name: sum(), area()


Multi-word method name: areaOfCircle(), stringComparision()

Types of Method

There are two types of methods in Java:

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.

length(), equals(), compareTo(), sqrt(), etc.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
User-defined 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

• Parameter can be passed to the function by two ways-

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.

• Following Java program shows the use of parameter passing by value-

Java Program

//Program implementing the parameter passing by value

public class ParameterByVal

void Fun(int a,int b)

{
a=a+5;

b=b+5;

public static void main(String args[])

ParameterByVal obj1=new ParameterByVal();

int a,b;

a=10;b=20;

System.out.println("The values of a and b before function call");

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

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

obj1.Fun(a,b);

System.out.println("The values of a and b after function call");

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

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

Output

The values of a and b before function call

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:

//This is single line comment


2) Java Multi Line Comment

 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
*
*/

Tag Syntax Description

{@docRo {@docRoot} to depict relative path to root directory of generated


ot} document from any page.

@author @author name - text To add the author of the class.

@code {@code text} To show the text in code font without interpreting it
as html markup or nested javadoc tag.

@version @version version-text To specify "Version" subheading and version-text


when -version option is used.

@since @since release To add "Since" heading with since text to generated
documentation.

@param @param parameter- To add a parameter with given name and


name description description to 'Parameters' section.

@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);

System.out.println("Addition of numbers: " + result);


}
}

Structure of Java Program


Documentation Section

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.

 It must be defined before any class and interface declaration.

 We use the keyword package to declare the package name.


Import statement section
 All the required java API can be imported by the import statement.
 There are some core packages present in the java.
 These packages include the classes and method required for java programming.
 These packages can be imported in the program in order to use the classes and
methods of the program.
Class definition section:
 The class definition section contains the definition of the class. This class normally
contains the data and the methods manipulating the data.
Main method class
 This is called the main method class because it contains the main () function.
 This class can access the methods defined in other classes.
Keywords
Keywords are the reserved words which are enlisted as below-

Difference between constructors and methods


Constructor Methods
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly
The java compiler provides a default Method is not provided by compiler in any
constructor if you don't have any case.
constructor.
Constructor name must be same as the class Method name may or may not be same as
name. class name.

You might also like