0% found this document useful (0 votes)
2 views

OOP JAVA Unit -1

This document provides an overview of Object-Oriented Programming (OOP) concepts using Java, including key principles such as classes, objects, inheritance, encapsulation, and polymorphism. It also covers the history of Java, its data types, and the differences between procedural and object-oriented programming paradigms. Additionally, the document discusses Java programming fundamentals, including comments, control flow statements, and method overloading.

Uploaded by

saifomer127
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

OOP JAVA Unit -1

This document provides an overview of Object-Oriented Programming (OOP) concepts using Java, including key principles such as classes, objects, inheritance, encapsulation, and polymorphism. It also covers the history of Java, its data types, and the differences between procedural and object-oriented programming paradigms. Additionally, the document discusses Java programming fundamentals, including comments, control flow statements, and method overloading.

Uploaded by

saifomer127
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

Object Oriented Programming Through Java

UNIT-I
• OOP concepts: Classes and objects, data abstraction, encapsulation, inheritance,
benefits of inheritance, polymorphism, procedural and object oriented
programming paradigm;
• Java programming: History of java, comments data types, variables, constants,
scope and life time of variables, operators, operator hierarchy, expressions, type
conversion and casting, enumerated types, control flow statements, jump
statements, simple java standalone programs, arrays, console input and output,
formatting output, constructors, methods, parameter passing, static fields and
methods, access control, this reference, overloading methods and constructors,
recursion, garbage collection, exploring string class.

1
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Introduction:
 Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:
 Object
 Class
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
• Apart from these concepts, there are some other terms
which are used in Object-Oriented design:
 Coupling
 Cohesion
 Association
 Aggregation
 Composition 2
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Object
 It is a basic unit of Object Oriented Programming and represents the real life entities. A
typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
 State : It is represented by attributes of an object. It also reflects the properties of an
object.
 Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
 Identity : It gives a unique name to an object and enables one object to interact with
other objects.
 Example of an object : dog

3
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Class
 A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class declarations
can include these components, in order:
1. Modifiers : A class can be public or has default access .
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by
the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.

4
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Data Abstraction
 Data Abstraction is the property by virtue of which only the essential details are displayed to
the user.The trivial or the non-essentials units are not displayed to the user. (or)
 Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
 Ex: A car is viewed as a car rather than its individual components.
 Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.
 The properties and behaviours of an object differentiate it from other objects of similar type
and also help in classifying/grouping the objects.
 Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of accelerator, brakes etc
in the car. This is what abstraction is.
 In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces. 5
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
Encapsulation
 Binding (or wrapping) code and data together into a single unit are known as
encapsulation. It is the mechanism that binds together code and the data it
manipulates.
 Other way to think about encapsulation is, it is a protective shield that
prevents the data from being accessed by the code outside this shield.
 Technically in encapsulation, the variables or data of a class is hidden
from any other class and can be accessed only through any member
function of own class in which they are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it
is also known as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class
as private and writing public methods in the class to set and get the values
of variables.
 For example, a capsule, it is wrapped with different medicines.
 A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here. 6
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Inheritance
 When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
 It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another
class.
 Important terminology:
 Super Class: The class whose features are inherited is known as superclass(or a base class or a parent
class).
 Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or
child class). The subclass can add its own fields and methods in addition to the superclass fields and
methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the existing class.
 The keyword used for inheritance is extends.
 Syntax: class derived-class extends base-class
{
//methods and fields
7
} Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Benefits of Inheritance
 One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units.
 Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a
method is superclass.
 Reusability -- facility to use public methods of base class without rewriting the same
 Extensibility -- extending the base class logic as per business logic of the derived class
 Data hiding -- base class can decide to keep some data private so that it cannot be altered by
the derived class.
 Overriding--With inheritance, we will be able to override the methods of the base class so
that meaningful implementation of the base class method can be designed in the derived
class.
8
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Polymorphism
 Polymorphism refers to the ability of OOPs programming
languages to differentiate between entities with the same
name efficiently. This is done by Java with the help of the
signature and declaration of these entities.
 If one task is performed in different ways, it is known as
polymorphism. For example: to convince the customer
differently, to draw something, for example, shape, triangle,
rectangle, etc.
 In Java, we use method overloading and method overriding
to achieve polymorphism.
 Another example can be to speak something; for example, a
cat speaks meow, dog barks woof, etc.

9
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Polymorphism
// Java program to demonstrate Polymorphism
// This class will contain 3 methods with same name
// Driver code
public class Sum { public static void main(String args[])
// Overloaded sum(). This sum takes two int parameters {
public int sum(int x, int y) Sum s = new Sum();
{ System.out.println(s.sum(10, 20));
return (x + y); System.out.println(s.sum(10, 20, 30));
} System.out.println(s.sum(10.5, 20.5));
// Overloaded sum(). This sum takes three int parameters }
public int sum(int x, int y, int z) }
{ File Name: Sum.java
return (x + y + z); For Compilation: javac Sum.java
} To Run the Program: java Sum
// Overloaded sum(). This sum takes two double parameters
Output:
public double sum(double x, double y) 30
{ 60
return (x + y); 31.0

}
10
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Procedural And Object Oriented Programming Paradigm

Procedural Oriented Programming Object Oriented Programming


In procedural programming, program is divided into In object oriented programming, program is divided
small parts called functions. into small parts called objects.
Object oriented programming follows bottom up
Procedural programming follows top down approach.
approach.
There is no access specifier in procedural Object oriented programming have access specifiers
programming. like private, public, protected etc.
Adding new data and function is not easy. Adding new data and function is easy.
Procedural programming does not have any proper Object oriented programming provides data hiding so it
way for hiding data so it is less secure. is more secure.
In procedural programming, overloading is not Overloading is possible in object oriented
possible. programming.
In procedural programming, function is more In object oriented programming, data is more
important than data. important than function.
Procedural programming is based on unreal world. Object oriented programming is based on real world.
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.
11
Dr. M V Narayana, Professor, GNITC
UNIT-I OOP concepts
 Procedural And Object Oriented Programming Paradigm

12
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 History of java
 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called
Green Team.
 2) Originally designed for small, embedded systems in electronic appliances
like set-top boxes.
 3) Firstly, it was called "Greentalk" by James Gosling, and file extension
was .gt
 4) After that, it was called Oak and was developed as a part of the Green
project.
 Why Java named "Oak"?
 5) Why Oak? Oak is a symbol of strength and chosen as a national tree of
many countries like U.S.A., France, Germany, Romania, etc.
 6) In 1995, Oak was renamed as "Java" because it was already a trademark
13
by Oak Technologies. Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 History of java
 Why Java Programming named "Java"?
 7) Why had they chosen java name for java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary", "Silk",
"jolt", "DNA", etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun
to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
 8) Java is an island of Indonesia where first coffee was produced (called java coffee).
 9) Notice that Java is just a name, not an acronym.
 10) Initially developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
 11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
 12) JDK 1.0 released in(January 23, 1996). 14
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 History of java
 Next Versions are:
 JDK 1.0 (January 23, 1996)
 JDK 1.1 (February 19, 1997)
 J2SE 1.2 (December 8, 1998)
 J2SE 1.3 (May 8, 2000)
 J2SE 1.4 (February 6, 2002)
 J2SE 5.0 (September 30, 2004)
 Java SE 6 (December 11, 2006)
 Java SE 7 (July 28, 2011)
 Java SE 8 (March 18, 2014)
 Java SE 9 (September 21, 2017)
 Java SE 10 (March 20, 2018)
 Java SE 11 (September 25, 2018)
15
 Java SE 12 (March 19, 2019) Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 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 in java.
 Single Line Comment
 Multi Line Comment
 Documentation Comment
 //This is single line comment
 /* This is multi line
comment */
 /**
This is documentation comment
*/ 16
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:
 Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
 Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

17
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Primitive data types:
 A primitive data type specifies the size and type of variable values, and it has no additional methods.
There are eight primitive data types in Java:

Data Type Size Description


byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values

18
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Primitive data types:
 Primitive datatypes are predefined by the language and named by a keyword.

byte
 Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an integer.
 Example: byte a = 100, byte b = -50

19
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Primitive data types:

short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

20
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Primitive data types:

int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is a concern
about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000

21
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Primitive data types:

long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L

22
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Primitive data types:

float
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f

double
 double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal values, generally the
default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
23
 Example: double d1 = 123.4 Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 Primitive data types:

boolean
 boolean data type represents one bit of information
 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false
 Example: boolean one = true

char
 char data type is a single 16-bit Unicode character
 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'
24
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
Small Example on Data Types:
public class Dtypes {
public static void main(String[] args) {
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number Filename: Dtypes.java
char myLetter = 'D'; // character For Compiling: javac Dtypes.java
To Run : java Dtypes
boolean myBool = true; // boolean
String myText = "Hello"; // String
Output
System.out.println(myNum);
5
System.out.println(myFloatNum); 5.99
System.out.println(myLetter); D
true
System.out.println(myBool); Hello
System.out.println(myText);
}
25
} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Data Types
 The main difference between primitive and non-primitive data types are:
 Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
 Non-primitive types can be used to call methods to perform certain operations, while primitive types
cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
 The size of a primitive type depends on the data type, while non-primitive types have all the same size.
 Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

26
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming

Java Buzzwords or Features of Java


 The Java programming language is a high-level language that can be characterized by all of the
following buzzwords:

Simple
 Java was designed to be easy for professional programmer to learn and use effectively.
 It’s simple and easy to learn if you already know the basic concepts of Object Oriented Programming.
 C++ programmer can move to JAVA with very little effort to learn.
 In Java, there is small number of clearly defined ways to accomplish a given task

Object oriented
 Java is true object oriented language.
 Almost “Everything is an Object” paradigm. All program code and data reside within objects and
classes.
 The object model in Java is simple and easy to extend.
 Java comes with an extensive set of classes, arranged in packages that can be used in our programs
through inheritance.
27
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Java Buzzwords or Features of Java
Distributed
 Java is designed for distributed environment of the Internet. Its used for creating applications on
networks.
 Java applications can access remote objects on Internet as easily as they can do in local system.
 Java enables multiple programmers at multiple remote locations to collaborate and work together on
a single project.

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 creation of a cross platform programs by compiling into an intermediate
representation called Java Bytecode.
 Interpreted : Bytecode is then interpreted, which generates machine code that can be directly
executed by the machine that provides a Java Virtual machine.

28
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Java Buzzwords or Features of Java
Robust
 It provides many features that make the program execute reliably in variety of environments.
 Java is a strictly typed language. It checks code both at compile time and runtime.
 Java takes care of all memory management problems with garbage-collection.
 Java, with the help of exception handling captures all types of serious errors and eliminates any risk of
crashing the system.

Secure
 Java provides a “firewall” between a networked application and your computer.
 When a Java Compatible Web browser is used, downloading can be done safely without fear of viral
infection or malicious intent.
 Java achieves this protection by confining a Java program to the java execution environment and not
allowing it to access other parts of the computer.

29
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Java Buzzwords or Features of Java
Architecture neutral
 Java language and Java Virtual Machine helped in achieving the goal of “write once; run anywhere,
any time, forever.”
 Changes and upgrades in operating systems, processors and system resources will not force any
changes in Java Programs.

Portable
 Java Provides a way to download programs dynamically to all the various types of platforms
connected to the Internet.
 It helps in generating Portable executable code.

High performance
 Java performance is high because of the use of bytecode.
 The bytecode was used, so that it was easily translated into native machine code.

30
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Java Buzzwords or Features of Java
Multithreaded
 Multithreaded Programs handled multiple tasks simultaneously, which was helpful in creating
interactive, networked programs.
 Java run-time system comes with tools that support multiprocess synchronization used to construct
smoothly interactive systems.

Dynamic
 Java is capable of linking in new class libraries, methods, and objects.
 It can also link native methods (the functions written in other languages such as C and C++).

31
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Variables
 A variable is a name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable effects
that memory location.
 In Java, all the variables must be declared before use.
 We can declare variables in java as follows:

 datatype: Type of data that can be stored in this variable.


 variable_name: Name given to the variable.
 value: It is the initial value stored in the variable.
32
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Variables
 Types of Variables:
 There are three types of variables in Java:
 Local Variables
 Instance Variables
 Static Variables
 Local Variables: A variable defined within a block or method or constructor is called local variable.
 These variable are created when the block in entered or the function is called and destroyed after exiting from
the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is declared. i.e. we can access
these variable only within that block.
 Initialization of Local Variable is Mandatory.

33
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Types of Variables:
Output:
 Local Variables:
public class StudentDetails Student age is : 5
{
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}
public static void main(String args[])
{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
34
} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Instance Variables
 Instance variables are non-static variables and are declared in a class outside any method,
constructor or block.
 As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
 Initialization of Instance Variable is not Mandatory. Its default value is 0
 Instance Variable can be accessed only by creating objects.

35
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Instance Variables // displaying marks for first object
import java.io.*; System.out.println("Marks for first object:");
class Marks { System.out.println(obj1.engMarks);
// These variables are instance variables. System.out.println(obj1.mathsMarks);
// These variables are in a class System.out.println(obj1.phyMarks);
// and are not inside any function // displaying marks for second object
int engMarks; System.out.println("Marks for second object:");
int mathsMarks; System.out.println(obj2.engMarks);
int phyMarks; System.out.println(obj2.mathsMarks);
} System.out.println(obj2.phyMarks);
class MarksDemo { } }
public static void main(String args[])
{
// first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;
// second object
Marks obj2 = new Marks();
obj2.engMarks = 80;
obj2.mathsMarks = 60; 36
obj2.phyMarks = 85; Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Variables
 Static variables are also known as Class variables.
 These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed automatically
when execution ends.
 Initialization of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like Instance variable (through an object), the compiler will
show the warning message and it won’t halt the program. The compiler will replace the
object name to class name automatically.
 If we access the static variable without the class name, Compiler will automatically append
the class name.
 To access static variables, we need not create an object of that class, we can simply access
the variable as class_name.variable_name; 37
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Variables
import java.io.*;
class Emp {
// static variable salary
public static double salary;
public static String name = "Harsh";
}
public class EmpDemo {
public static void main(String args[])
{
// accessing static variable without object
Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:"+ Emp.salary);
}
} 38
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Instance variable Vs Static variable
 Each object will have its own copy of instance variable whereas We can only have one copy of a static
variable per class irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other objects as each
object has its own copy of instance variable. In case of static, changes will be reflected in other objects
as static variables are common to all object of a class.
 We can access instance variables through object references and Static Variables can be accessed
directly using class name.
 Syntax for static and instance variables:
class Example
{
static int a; //static variable
int b; //instance variable
}

39
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constants
 A constant is an identifier that is similar to a variable except that it holds the same value
during its entire existence.
 As the name implies, it is constant, not variable.
 The compiler will issue an error if you try to change the value of a constant.
 In Java, we use the final modifier to declare a constant
final int MIN_HEIGHT = 69;
 Constants are useful for three important reasons
 First, they give meaning to otherwise unclear literal values
 For example, MAX_LOAD means more than the literal 250
 Second, they facilitate program maintenance
 If a constant is used in multiple places, its value need only be updated in one place
 Third, they formally establish that a value should not change, avoiding inadvertent errors by
other programmers
40
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Scope and Lifetime of Variables:
 Scope of a variable refers to in which areas or sections of a program can the variable be
accessed and lifetime of a variable refers to how long the variable stays alive in memory.
 General convention for a variable’s scope is, it is accessible only within the block in which it is
declared. A block begins with a left curly brace { and ends with a right curly brace }.
 As we know there are three types of variables:
 1) instance variables,
 2) class/static variables and
 3) local variables,

 we will look at the scope and lifetime of each of them now.


 General scope of an instance variable is throughout the class except in static methods.
Lifetime of an instance variable is until the object stays in memory.
 General scope of a static/class variable is throughout the class and the lifetime of a
static/class variable is until the end of the program or as long as the class is loaded in
memory.
 Scope of a local variable is within the block in which it is declared and the lifetime of a local
41
variable is until the control leaves the block in which it is declared. Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Scope and Lifetime of Variables:
 Nested Scope
 In Java, we can create nested blocks – a block inside another block
 All the local variables in the outer block are accessible within the inner block but vice versa is not true
i.e., local variables within the inner block are not accessible in the outer block. Consider the following
example:
class Sample
{
public static void main(String[] args)
{
int x;
//Begining of inner block
{
int y = 100;
x = 200;
System.out.println("x = "+x);
}
//End of inner block
System.out.println("x = "+x);
y = 200; //Error as y is not accessible in the outer block
} } 42
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:
Java provides a rich set of operators to manipulate variables. We can
divide all the Java operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators

43
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Arithmetic Operators (+,-,*,/,%)


public class Test { Output:
a + b = 30
public static void main(String args[]) { a - b = -10
int a = 10; int b = 20; int c = 25; int d = 25; a * b = 200
b / a = 2
System.out.println("a + b = " + (a + b) );
b % a = 0
System.out.println("a - b = " + (a - b) ); c % a = 5
System.out.println("a * b = " + (a * b) ); a++ = 10
b-- = 11
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) ); // Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) ); } }
44
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Relational Operators(==,!=,>,<,>=,<=)
Output:
public class RelOP
a == b = false
{
a != b = true
public static void main(String args[])
a > b = false
{ a < b = true
int a = 10; b >= a = true
int b = 20; b <= a = false
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
} } 45
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Bitwise Operators(&,|,^,~(Binary Ones Complement Operator),<<,>>,<<<(Shift right zero fill operator))


public class BitOp
{
c = a ^ b; /* 49 = 0011 0001 */

public static void main(String args[]) System.out.println("a ^ b = " + c ); Output:


a & b = 12
{ c = ~a; /*-61 = 1100 0011 */
a | b = 61
int a = 60; /* 60 = 0011 1100 */ System.out.println("~a = " + c );
a ^ b = 49
int b = 13; /* 13 = 0000 1101 */ c = a << 2; /* 240 = 1111 0000 */ ~a = -61
int c = 0; a << 2 = 240
System.out.println("a << 2 = " + c );
c = a & b; /* 12 = 0000 1100 */ a >> 2 = 15
c = a >> 2; /* 215 = 1111 */
System.out.println("a & b = " + c ); a >>> 2 = 15
}
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c ); }

46
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Logical Operators(&&,||,!)
public class LogicOPs { Output:
a && b = false
public static void main(String args[])
a || b = true
{
!(a && b) = true
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}

47
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Assignment Operators(=,+=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=)
= Simple assignment operator, Assigns values from right side operands to left side operand
 += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
 -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left
operand C -= A is equivalent to C = C - A
 *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left
operand C *= A is equivalent to C = C * A
 /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left
operand C /= A is equivalent to C = C / A
 %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
 <<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
 >>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
 &= Bitwise AND assignment operator C &= 2 is same as C = C & 2
 ^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
 |= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2 48
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Assignment Operators(=,+=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=)
public class AssignOp System.out.println("c &= 2 = " + c );
a = 10;
{ c ^= a ;
c = 15;
public static void main(String args[])
c /= a ; System.out.println("c ^= a = " + c );
{
System.out.println("c /= a = " + c ); c |= a ;
int a = 10;
a = 10; System.out.println("c |= a = " + c );
int b = 20;
c = 15;
int c = 0; }
c %= a ;
c = a + b; }
System.out.println("c %= a = " + c );
System.out.println("c = a + b = " + c );
c <<= 2 ;
c += a ;
System.out.println("c <<= 2 = " + c );
System.out.println("c += a = " + c );
c >>= 2 ;
c -= a ;
System.out.println("c >>= 2 = " + c );
System.out.println("c -= a = " + c );
c >>= 2 ;
c *= a ;
System.out.println("c >>= a = " + c );
System.out.println("c *= a = " + c ); 49
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Assignment Operators(=,+=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=)
Output:
c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= a = 1
c &= 2 = 0
c ^= a = 10
c |= a = 10
50
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Misc Operators
Conditional Operator ( ? : )
 Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be
assigned to the variable.
 The operator is written as: variable x = (expression) ? value if true : value if false
public class Test {
public static void main(String args[ ]) { Output:
int a , b; Value of b is : 30
Value of b is : 20
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
51
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:

Misc Operators
instanceOf Operator
 This operator is used only for object reference variables. The operator checks whether the
object is of a particular type(class type or interface type).
The instanceOf operator is wriiten as:
( Object reference variable ) instanceOf (class/interface type)
 If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true.
class Vehicle {
public class Car extends Vehicle {
Output:
public static void main(String args[]){
true
Vehicle a = new Car();
boolean result = a instanceOf Car;
System.out.println( result);
}
} 52
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:
 Operator hierarchy
 Operator precedence/hierarchy determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
 Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at
 the bottom. Within an expression, higher precedence operators will be evaluated first.

53
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:
 Operator hierarchy

54
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Operators, Operator hierarchy, expressions:
 Expressions:
 Expressions consist of variables, operators, literals and method calls that evaluates to a
single value.
 Expressions are the basic way to create values. Expressions are created by combining
literals (constants), variables, and method calls by using operators. Parentheses can be
used to control the order of evaluation.
 The order in which expressions are evaluated is basically left to right, with the exception of
the assignment operators. It may be changed by the use of parentheses. See the
expression summary for the precedence.

55
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Type conversion and type casting:
 In Java, there are two kinds of data types – primitives and references.

Primitives include int, float, long, double etc.


References can be of type classes, interfaces, arrays.
 A value can change its type either implicitly or explicitly.
 Implicit and Explicit changes:
 There are situations in which the system itself changes the type of an expression implicitly based on
some requirement.
 Example:
 int num1 = 4;
 double num2;
 double d = num1 / num2; //num1 is also converted to double
 This kind of conversion is called automatic type conversion.

56
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Type conversion and type casting:
 When you assign value of one data type to another, the two types might not be
compatible with each other. If the data types are compatible, then Java will perform the
conversion automatically known as Automatic Type Conversion and if not then they need
to be casted or converted explicitly. For example, assigning an int value to a long
variable.
 Two types of Conversions
Widening or Automatic Type Conversion
Narrowing or Explicit Conversion

57
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Type conversion and type casting:
Widening or Automatic Type Conversion
 Widening conversion takes place when two data types are automatically converted. This happens
when:
 The two data types are compatible.
 When we assign value of a smaller data type to a bigger data type.

class Test
{ public static void main(String[] args)
{ int i = 100;
Output:
//automatic type conversion
Int value 100
long l = i; Long value 100
//automatic type conversion
Float value 100.0
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
} 58
} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Type conversion and type casting:
Narrowing or Explicit Conversion
 If we want to assign a value of larger data type to a smaller data type we perform explicit type casting
or narrowing.
 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.
//Java program to illustrate explicit type conversion
class Test
{ public static void main(String[] args)
{ double d = 100.04;
//explicit type casting
Output:
long l = (long)d;
Double value 100.04
//explicit type casting Long value 100
int i = (int)l; Int value 100
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i); 59
}} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Enumerated Types:
 The Enum in Java is a data type which contains a fixed set of constants.
 It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and
SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST), season (SPRING, SUMMER, WINTER, and
AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc. According to the Java
naming conventions, we should have all constants in capital letters. So, we have enum constants in
capital letters.
 Java Enums can be thought of as classes which have a fixed set of constants (a variable that does not
change). The Java enum constants are static and final implicitly. It is available since JDK 1.5.
 Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is more
powerful. Here, we can define an enum either inside the class or outside the class.
 Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can implement
many interfaces. We can have fields, constructors, methods, and main methods in Java enum.

60
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Enumerated Types:
Defining Java Enum
The enum can be defined within or outside the class because it is similar to
a class. The semicolon (;) at the end of the enum constants are optional.
For example:
enum Season { WINTER, SPRING, SUMMER, FALL }
Or,
enum Season { WINTER, SPRING, SUMMER, FALL; }
Both the definitions of Java enum are the same.

61
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Enumerated Types: Defined inside class
1. class EnumExample3{
Defining Java Enum
2. enum Season { WINTER, SPRING, SUMMER, FALL; }
Defined outside class 3. //semicolon(;) is optional here
1. enum Season { WINTER, SPRING, SUMMER, FALL } 4. public static void main(String[] args)
2. class EnumExample2{ 5. {
3. public static void main(String[] args) {
6. Season s=Season.WINTER;
4. Season s=Season.WINTER;
5. System.out.println(s); 7. //enum type is required to access WINTER
6. }} 8. System.out.println(s);
Output
9. }}
WINTER

Output
WINTER

62
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Enumerated Types:
Defining Java Enum
main method inside Enum
If you put main() method inside the enum, you can run the enum directly.

1. enum Season {
2. WINTER, SPRING, SUMMER, FALL;
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.println(s);
6. }
Output
7. } WINTER

63
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Enumerated Types:
 Initializing specific values to the enum constants
 The enum constants have an initial value which starts from 0, 1, 2, 3, and so on.
But, we can initialize the specific value to the enum constants by defining fields
and constructors. As specified earlier, Enum can have fields, constructors, and
methods.
1. class EnumExample4{
2. enum Season{
3. WINTER(5), SPRING(10), SUMMER(15), FALL(20);
4. private int value;
Output
5. private Season(int value){ WINTER 5
SPRING 10
6. this.value=value; SUMMER 15
7. } } FALL 20

8. public static void main(String args[]){


9. for (Season s : Season.values())
10. System.out.println(s+" "+s.value);
64
11. }} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
 A conditional statement lets us choose which statement will be executed next

 Therefore they are sometimes called selection statements

 Conditional statements give us the power to make basic decisions

Statements
– Using if and if...else
– Nested if Statements

– Using switch Statements


– Conditional Operator
 Repetition Statements
– Looping: while, do-while, and for
– Nested loops

– Using break and continue


65
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements

if statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a Java evaluate to either true or false.
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.

66
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming

Class Age{ Enter your age: 12


public static void main (String[] args)
You entered: 12
{
final int MINOR = 21; Youth is a wonderful thing. Enjoy.
Scanner scan = new Scanner (System.in); Age is a state of mind.
System.out.print ("Enter your age: ");
int age = scan.nextInt();
System.out.println ("You entered: " + age);
if (age < MINOR) Enter your age: 100
System.out.println ("Youth is a wonderful thing. "+ "Enjoy."); You entered: 100
System.out.println ("Age is a state of mind."); Age is a state of mind.
}
}

67
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
if-else statement
• An else clause can be added to an if statement to
make an if-else statement
if ( condition )
statement1;
else
statement2;

• If the condition is true, statement1 is executed;


if the condition is false, statement2 is executed

• One or the other will be executed, but not both

68
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
if-else statement
Class Ifelseex{
Public static void main(String args[])
{
int num1, num2, num3, min = 0;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter three integers: ");
num1 = scan.nextInt();
num2 = scan.nextInt();
num3 = scan.nextInt();
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
System.out.println ("Minimum value: " + min);
69
}} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
switch statement
• The switch statement provides another way to decide which statement to
execute next
• The switch statement evaluates an expression, then attempts to match
the result to one of several possible cases
• Each case contains a value and a list of statements
• The flow of control transfers to statement associated with the first case
value that matches
• Syntax of a switch statement is:

70
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
switch statement
 A switch statement can have an optional default case

 The default case has no associated value and simply uses the reserved word default

 If the default case is present, control will transfer to it if no other case value matches

 If there is no default case, and no other value matches, control falls through to the statement after the
switch

 The expression of a switch statement must result in an integral type, meaning an int or a char

 It cannot be a boolean value, a floating point value (float or double), or another integer type

 The implicit boolean condition in a switch statement is equality

 You cannot perform relational checks with a switch statement

71
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
19.case 8:
switch statement 20.System.out.println ("above average. Nice
1. public class GradeReport job.");
2. { 21.break;
3. public static void main (String[] args) 22.case 7:
4. { 23.System.out.println ("average.");
5. int grade,category; 24.break;
6. Scanner scan = new Scanner (System.in); 25.case 6:
7. System.out.print("Enter a numeric 26.System.out.println ("below average.");
grade(0to100): "); 27.System.out.println ("See the
8. grade = scan.nextInt(); instructor.");
9. category = grade / 10; 28.break;
10.System.out.print("That grade is "); 29.default:
11.switch (category) 30.System.out.println ("not passing.");
12.{ 31.} }}
13.case 10:
14.System.out.println("a perfect score.Well done.");
15.break;
16.case 9:
17.System.out.println ("well above average.
Great.");
72
18.break; Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
Conditional Operator
if (x > 0) y = 1
else y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;

Syntax: (booleanExp) ? exp1 : exp2


Ternary operator
Binary operator
Unary operator
73
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
while Loop Flow Chart
 Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

false
Continuation
while (continuation-condition) condition?

{ true

// loop-body; Statement(s)

}
Next
Statement

74
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
do….while Loop Flow Chart
 Like a while statement, except that it tests the condition at the end of the loop body.
Statement(s)

do
{
true
// loop-body; Continue
condition?

} while (continuation-condition);
false

Next
Statement

75
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
for Loop Flow Chart
Execute a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
for (initial-action; loop-continuation-condition; action-after-each-iteration)
{ Initial-Action

//loop body;
} false
Action-After- Continuation
Each-Iteration condition?

true

Statement(s)
(loop-body)

Next 76
Statement Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
The break Keyword Continuation
false

 The break statement in Java programming language condition?


has the following two usages −
 When the break statement is encountered inside a true
loop, the loop is immediately terminated and the
program control resumes at the next statement
Statement(s)
following the loop.
 It can be used to terminate a case in the switch
statement break
 Syntax break;
Statement(s)

 Terminates the loop or switch statement and transfers


execution to the statement immediately following the
loop or switch. Next
Statement

77
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Control Flow & Jump Statements
The continue Keyword
false
Causes the loop to skip the remainder of its Continue
condition?
body and immediately retest its condition
prior to reiterating. true

Statement(s)

continue

Statement(s)

Next
Statement

78
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Arrays
 Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
 Declaration of Array
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
 Creating Arrays
 You can create an array by using the new operator with the following syntax
arrayRefVar = new dataType[arraySize];
 The above statement does two things −
 It creates an array using new dataType[arraySize].
 It assigns the reference of the newly created array to the variable arrayRefVar.
79
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Arrays
 Processing Arrays:
 When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
1. public class TestArray
2. {
3. public static void main(String[] args)
4. {
5. double[] myList = {1.9, 2.9, 3.4, 3.5}; Output
6. // Print all the array elements 1.9
7. for (int i = 0; i < myList.length; i++) 2.9
8. { System.out.println(myList[i] + " "); } 3.4
9. // Summing all elements 3.5
10. double total = 0; Total is 11.7
11. for (int i = 0; i < myList.length; i++) Max is 3.5
12. { total += myList[i]; }
13. System.out.println("Total is " + total);
14. // Finding the largest element
15. double max = myList[0];
16. for (int i = 1; i < myList.length; i++)
17. { if (myList[i] > max) max = myList[i]; }
80
18. System.out.println("Max is " + max); }} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Arrays
 Processing Arrays:
 foreach loop
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for
loop, which enables you to traverse the complete array sequentially
without using an index variable.
1. public class TestArray Output
2. { public static void main(String[] args) 1.9
2.9
3. { double[] myList = {1.9, 2.9, 3.4, 3.5};
3.4
4. // Print all the array elements 3.5
5. for (double element: myList)
6. {
7. System.out.println(element);
8. } }}

81
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Arrays
 Methods in Java Array(java.util.Arrays):
 static <T> List<T> asList(T… a): This method returns a fixed-size list backed by the specified
Arrays.
 static int binarySearch(elementToBeSearched): These methods searches for the specified
element in the array with the help of Binary Search algorithm.
 static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<T> c): This
method searches a range of the specified array for the specified object using the binary
search algorithm.
 compare(array 1, array 2): This method compares two arrays passed as parameters
lexicographically.
 compareUnsigned(array 1, array 2): This method compares two arrays lexicographically,
numerically treating elements as unsigned.
 copyOf(originalArray, newLength): This method copies the specified array, truncating or
padding with the default value (if necessary) so the copy has the specified length.
 copyOfRange(originalArray, fromIndex, endIndex): This method copies the specified range
of the specified array into a new Arrays. copyOfRange(originalArray, fromIndex, endIndex):
This method copies the specified range of the specified array into a new Arrays.
 static boolean deepEquals(Object[] a1, Object[] a2): This method returns true if the two
specified arrays are deeply equal to one another. 82
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Arrays
 Methods in Java Array(java.util.Arrays):
 static int deepHashCode(Object[] a): This method returns a hash code based on the “deep
contents” of the specified Arrays.
 static String deepToString(Object[] a): This method returns a string representation of the
“deep contents” of the specified Arrays.
 equals(array1, array2): This method checks if both the arrays are equal or not.
 fill(originalArray, fillValue): This method assigns this fillValue to each index of this Arrays.
 hashCode(originalArray): This method returns an integer hashCode of this array instance.
 mismatch(array1, array2): This method finds and returns the index of the first unmatched
element between the two specified arrays.
 setAll(originalArray, functionalGenerator): This method sets all the element of the specified
array using the generator function provided.
 sort(originalArray): This method sorts the complete array in ascending order.
 sort(originalArray, fromIndex, endIndex): This method sorts the specified range of array in
ascending order.

83
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Arrays
 The Arrays Class
Sr.No. Method & Description
public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search
1
algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is
contained in the list; otherwise, it returns ( – (insertion point + 1)).
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if
2 both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays
are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive
data types (Byte, short, Int, etc.)
public static void fill(int[] a, int val)
3 Assigns the specified int value to each element of the specified array of ints. The same method could be used
by all other primitive data types (Byte, short, Int, etc.)
public static void sort(Object[] a)
Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements.
4
The same method could be used by all other primitive data types ( Byte, short, Int, etc.)
84
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Console Input and Output
 java.io.Console class which provides convenient methods for reading input and writing output to the
standard input (keyboard) and output streams (display) in command-line (console) programs.
 Three different ways for reading input from the user in the command line environment (also known as
the “console”).
 Using BufferedReader class
 Using Scanner class
 Using Console class

85
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Console Input and Output
 Using BufferedReader class
 This is the Java traditional technique, introduced in JDK1.0. This strategy is utilized by wrapping the
System.in (standard information stream) in an InputStreamReader which is wrapped in a Java
BufferedReader, we can read result include from the user in the order line.
 Pros –
The input is buffered for efficient reading.
 Cons –
The wrapping code is difficult to recall.
Output
import java.io.BufferedReader; Enter String
import java.io.IOException; Hello
import java.io.InputStreamReader; Your Entered String is
public class ConIOBuffRead Hello
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter String");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println("Your Entered String is");
System.out.println(name); }
86
} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Console Input and Output
 Using Scanner class
 This is presumably the most favoured technique to take input. The primary reason for the Scanner
class is to parse primitive composes and strings utilizing general expressions, in any case, it can
utilize to peruse contribution from the client in the order line.
 Pros –
Helpful strategies for parsing natives (nextInt(), nextFloat(), … ) from the tokenized input.
General articulations can utilize to discover tokens.
 Cons –
The reading methods are not synchronized. Output
import java.util.Scanner;
Hai
class ConIOScannerread
{ You entered string Hai
public static void main(String args[]) 235
{
You entered integer 235
Scanner in = new Scanner(System.in);
String s = in.nextLine(); 456.789
System.out.println("You entered string "+s); You entered float 456.789
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b);
87
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Console Input and Output
 Using Console class
 It has been turning into a favored route for perusing client’s contribution from the command line. In
addition, it can utilize for password key like contribution without resounding the characters entered by
the client, the configuration string syntax structure can likewise utilize (like System.out.printf()).
 Pros –
Reading secret word without reverberating the entered characters.
Reading strategies that are synchronized.
Format string sentence structure can utilize.
 Cons –
Does not work in non-intelligent condition, (for example, in an IDE).

public class ConIOConsole


{
public static void main(String[] args) Output
{ Need to Collect
// Using Console to input data from user
String name = System.console().readLine();
System.out.println(name);
}
}
88
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Formatting Output
 Sometimes in Competitive programming, it is essential to print the output in a given specified
format. Most users are familiar with printf function in C. Let us see discuss how we can format
the output in Java:
 Formatting output using System.out.printf()
 This is the easiest of all methods as this is similar to printf in C.
 Note that System.out.print() and System.out.println() take a single argument, but printf() may
take multiple arguments.
 System.out.format() is equivalent to printf() and can also be used.

89
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Formatting Output
 Formatting output using System.out.printf() Output
Printing simple integer: x = 100
Formatted with precison: PI = 3.14
//A Java program to demonstrate working of printf() in Java
class SysoutPrnf Formatted to specific width: n = 5.2000
{ Formatted to right margin: n = 2324435.2500
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple integer: x = %d\n", x);
// this will print it upto 2 decimal places
System.out.printf("Formatted with precison: PI = %.2f\n", Math.PI);
float n = 5.2f;
// automatically appends zero to the rightmost part of decimal
System.out.printf("Formatted to specific width: n = %.4f\n", n);

n = 2324435.3f;
// here number is formatted from right margin and occupies a
// width of 20 characters
System.out.printf("Formatted to right margin: n = %20.4f\n", n);
} 90
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Formatting Output
 Formatting dates and parsing using SimpleDateFormat class:
//Java program to demonstrate working of SimpleDateFormat
import java.text.ParseException;
import java.text.SimpleDateFormat; OutPut:
import java.util.Date; Formatted Date : 23-07-2019
class DateFormatdemo Parsed Date : Sat Feb 18 00:00:00 IST 1995
{
public static void main(String args[]) throws ParseException
{
// Formatting as per given pattern in the argument
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
String str = ft.format(new Date());
System.out.println("Formatted Date : " + str);
// parsing a given String
str = "02/18/1995";
ft = new SimpleDateFormat("MM/dd/yyyy");
Date date = ft.parse(str);
// this will print the date as per parsed string
System.out.println("Parsed Date : " + date);
} 91
} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 In Java, a constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is called.
 It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
 There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
 Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor if
your class doesn't have any.
 Rules for creating Java constructor
 There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
92
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Purpose: Java provides a Constructor class which can be
used to get the internal information of a constructor in the
class. It is found in the java.lang.reflect package
 There are no “return value” statements in constructor, but
constructor returns current class instance. We can write
‘return’ inside a constructor.

 Types of Java constructors


 There are two types of constructors in Java:
Default constructor (no-argument constructor)
Parameterized constructor

93
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
Constructors
 Types of Java constructors
Default constructor (no-argument constructor)
A constructor that has no parameter is known as default
constructor. If we don’t define a constructor in a class, then
compiler creates default constructor(with no arguments) for the
class.
And if we write a constructor with arguments or no-arguments then
the compiler does not create a default constructor.

Default constructor is used to provide the default values to the


object like 0, null, etc. depending on the type.
94
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Types of Java constructors
Default constructor (no-argument constructor)
//Java Program to illustrate calling a no-argument constructor
import java.io.*;
class Geek
{ OutPut:
int num; Constructor called
String name; null
// this would be invoked while an object 0
// of that class is created.
Geek()
{
System.out.println("Constructor called");
} }
class ConNoArg
{
public static void main (String[] args)
{
// this would invoke default constructor.
Geek geek1 = new Geek();
// Default constructor provides the default values to the object like 0, null
System.out.println(geek1.name);
System.out.println(geek1.num); 95
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Types of Java constructors
Parameterized constructor
 A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with your own values, then use a parameterized constructor.
 A constructor which has a specific number of parameters is called a parameterized
constructor.
 Need of parameterized constructor:
 The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.

96
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Types of Java constructors
Parameterized constructor
//Java Program to demonstrate the use of the parameterized constructor.
class ConWithArgs{
int id;
String name;
//creating a parameterized constructor OutPut:
ConWithArgs(int i,String n){ 111 GNITC
id = i; 222 CSE
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
ConWithArgs s1 = new ConWithArgs(111,"GNITC");
ConWithArgs s2 = new ConWithArgs(222,"CSE");
//calling method to display the values of object
s1.display();
s2.display();
}
97
} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Constructor Overloading in Java
 In Java, a constructor is just like a method but without return type. It can also
be overloaded like Java methods.
 Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that
each constructor performs a different task. They are differentiated by the
compiler by the number of parameters in the list and their types.

98
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Constructor Overloading in Java
//Java program to overload constructors
class ConOverLoad{
int id;
String name;
int age;
//creating two arg constructor OutPut:
ConOverLoad(int i,String n){ 111 GNI 0
id = i;
name = n; 222 CSE Branch 25
}
//creating three arg constructor
ConOverLoad(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
ConOverLoad s1 = new ConOverLoad(111,"GNI");
ConOverLoad s2 = new ConOverLoad(222,"CSE Branch",25);
s1.display();
s2.display();
99
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Java Copy Constructor
 There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
 There are many ways to copy the values of one object into another in Java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
 In this example, we are going to copy the values of one object into another using Java
constructor.

100
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Java Copy Constructor
//Java program to initialize the values from one object to another object using copy constructor
class JavaCopyCons{
int id;
String name;
//constructor to initialize integer and string
JavaCopyCons(int i,String n){
OutPut:
id = i; 111 GNITC
name = n; 111 GNITC
}
//constructor to initialize another object
JavaCopyCons(JavaCopyCons s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
JavaCopyCons s1 = new JavaCopyCons(111,"GNITC");
JavaCopyCons s2 = new JavaCopyCons(s1);
s1.display();
s2.display(); 101
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Constructors
 Copying values without constructor
 We can copy the values of one object into another by assigning the objects values to another object.
In this case, there is no need to create the constructor.
class WOConstruct{
int id;
String name; OutPut:
WOConstruct(int i,String n){ 111 GNITC-CSE
id = i;
name = n;
111 GNITC-CSE
}
WOConstruct(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


WOConstruct s1 = new WOConstruct(111,"GNITC-CSE");
WOConstruct s2 = new WOConstruct();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
102
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Methods
 A class contains data declarations (static and instance
variables) and method declarations (behaviors)
 A program that provides some functionality can be
long and contains many statements
 A method groups a sequence of statements and
should provide a well-defined, easy-to-understand
functionality
 a method takes input, performs actions, and produces output
 In Java, each method is defined within specific class

103
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Methods
 A method declaration begins with a method
header.

 The header is followed by the method body:

class MyClass
{

static int min(int num1, int num2)
{
int minValue = num1 < num2 ? num1 : num2;
return minValue;
}


104
} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Methods
 Return Statement
 The return type of a method indicates the type of value that the method sends back to the calling
location
 A method that does not return a value has a void return type

 The return statement specifies the value that will be returned


 Its expression must conform to the return type
 Calling a Method
 Each time a method is called, the values of the actual arguments in the invocation are assigned to the
formal arguments

105
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Methods
 Method Control Flow
 A method can call another method, who can call another method, …

106
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Methods
 Method overloading
 A class may define multiple methods with the same name---this is called
method overloading
 usually perform the same task on different data types
 Example: The PrintStream class defines multiple println methods, i.e., println is
overloaded:
println (String s)
println (int i)
println (double d)

 The following lines use the System.out.print method for different data types:

System.out.println ("The total is:");


double total = 0;
System.out.println (total);
107
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Methods
 Method overloading: Signature
 The compiler must be able to determine which version of the method is being
invoked
 This is by analyzing the parameters, which form the signature of a method
 the signature includes the type and order of the parameters
 if multiple methods match a method call, the compiler picks the best match
 if none matches exactly but some implicit conversion can be done to match a method, then
the method is invoke with implicit conversion.
 the return type of the method is not part of the signature

108
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Difference between constructor and method in Java

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object.

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

109
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Parameter Passing
 There are different ways in which parameter data can be passed into and out of methods
and functions. Let us assume that a function B() is called from another function A().
 In this case A is called the “caller function” and B is called the “called function or callee
function”. Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
 Types of parameters:
 Formal Parameter : A variable and its type as they appear in the prototype of the function
or method.
 Syntax: function_name(datatype variable_name);
 Actual Parameter : The variable or expression corresponding to a formal parameter that
appears in the function or method call in the calling environment.
 Syntax: func_name(variable name(s));

110
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Parameter Passing
 If a modification of the formal argument has no effect on the actual argument,
 it is call by value
 If a modification of the formal argument can change the value of the actual argument,
 it is call by reference
 Depend on the type of the formal argument
 If a formal argument is a primitive data type, a modification on the formal argument has no effect on
the actual argument
 this is call by value, e.g. num1 = min(2, 3);
num2 = min(x, y);
 This is because primitive data types variables contain their values, and procedure call trigger an
assignment:
<formal argument> = <actual argument> int x = 2;
int x = 2; int y = 3; int y = 3;
int num = min (x, y); int num1 = x;
… int num2 = y;
static int num( int num1, int num2) { … }
{ … } 111
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Parameter Passing
•Shortcomings in Call by Value:
 Call by Value Example: •Inefficiency in storage allocation
1. // Java program to illustrate Call by Value •For objects and arrays, the copy semantics are costly
2. // Callee
3. class CallByValue {
4. // Function to change the value of the parameters
5. public static void Example(int x, int y)
6. { x++;
7. y++;
8. } } Output:
9. // Caller
Value of a: 10 & b: 20
10. public class ClbvMain{
11. public static void main(String[] args)
Value of a: 10 & b: 20
12. { int a = 10;
13. int b = 20;
14. // Instance of class is created
15. CallByValue object = new CallByValue();
16. System.out.println("Value of a: " + a + " & b: " + b);
17. // Passing variables in the class function
18. object.Example(a, b);
19. // Displaying values after calling the function
20. System.out.println("Value of a: "+ a + " & b: " + b);
21. }
22. } 112
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Parameter Passing
 If a formal argument is not a primitive data type, an operation on the formal
argument can change the actual argument
 this is call by reference
 This is because variables of object type contain pointers to the data that
represents the object
 Since procedure call triggers an assignment
<formal argument> = <actual argument>
it is the pointer that is copied, not the object itself!

MyClass x = new MyClass(); x = new MC();


MyClass y = new MyClass(); y = new MC();
MyClass.swap( x, y); x1 = x;

x2 = y;
static void swap( MyClass x1, MyClass x2)
{ … }
{ … }

113
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Parameter Passing
 Call by Reference Example
1. // Java program to illustrate Call by Reference
2. // Callee
3. class CallByReference {
4. int a, b;
5. // Function to assign the value to the class variables
6. CallByReference(int x, int y)
7. { a = x;
8. b = y;
9. } Output:
10. // Changing the values of class variables Value of a: 10 & b: 20
11. void ChangeValue(CallByReference obj) Value of a: 20 & b: 40
12. { obj.a += 10;
13. obj.b += 20;
14. }}
15. // Caller
16. public class ClbRef{
17. public static void main(String[] args)
18. { // Instance of class is created and value is assigned using constructor
19. CallByReference object = new CallByReference(10, 20);
20. System.out.println("Value of a: "+ object.a + " & b: "+ object.b);
21. // Changing values in class function
22. object.ChangeValue(object);
23. // Displaying values after calling the function
24. System.out.println("Value of a: "+ object.a + " & b: "+ object.b); 114
25. }} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Fields and Methods
 The static keyword in Java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than an
instance of the class.
 The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class

115
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Fields and Methods
 1) Java static variable
 If you declare any variable as static, it is known as a
static variable.
 The static variable can be used to refer to the
common property of all objects (which is not
unique for each object), for example, the
company name of employees, college name of
students, etc.
 The static variable gets memory only once in the
class area at the time of class loading.
 Advantages of static variable
 It makes your program memory efficient (i.e., it
saves memory).

116
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Fields and Methods
 1) Java static variable Example
class Student{ Output:
int rollno;//instance variable 111 Karan GNITC
String name; 222 Aryan GNITC
static String college ="GNITC";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n; }
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class StaticVar{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="GNIT";
s1.display(); 117
s2.display(); } } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Fields and Methods
 2) Java static Method
 If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
 Restrictions for the static method
 There are two main restrictions for the static method. They are:
 The static method can not use non static data member or call non-static method directly.
 this and super cannot be used in static context.
 Need of Java main method as static
 It is because the object is not required to call a static method. If it were a non-static method, JVM
creates an object first then call main() method that will lead the problem of extra memory allocation.

118
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Fields and Methods
 1) Java static Method Example
Java Program to demonstrate the use of a static method.
class Student{
int rollno; Output:
String name; 111 Karan GNITC
static String college = “GNITC"; 222 Aryan GNITC
//static method to change the value of static variable 333 Sonoo GNITC
static void change(){
college = "BBDIT";
} //constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
} //method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
} //Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method Creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
s1.display(); //calling display method
s2.display(); 119
s3.display(); } } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Static Fields and Methods
 3) Java static Block
 Is used to initialize the static data member.
 It is executed before the main method at the time of classloading.
 Example of static block
1.class A2{
2. static{System.out.println("static block is invoked");} Output:
3. public static void main(String args[]){ static block is invoked
4. System.out.println("Hello main"); Hello main
5. } }
 Can we execute a program without main() method?
 Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not
possible to execute a java class without the main method.
1.class A3{ Output:
2. static{ static block is invoked
3. System.out.println("static block is invoked"); Since JDK 1.7 and above, output would be:
4. System.exit(0); Error: Main method not found in class A3, please define the main method as:
5. } public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
6.}

120
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Access Control/Modifiers
 Access control/modifier specify what parts of a program can access the members of a class and so
prevent misuse.
 There are two types of modifiers in Java: access modifiers and non-access modifiers.
 The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.
 There are four types of Java access modifiers:
 Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
 Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
 Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
 Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
 There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
121
etc. Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Access Control/Modifiers

outside package by
Access Modifier within class within package outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

122
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Access Control/Modifiers
 1) Private
 The private access modifier is specified using the keyword private. The methods or data members
declared as private are accessible only within the class in which they are declared.
 Any other class of same package will not be able to access these members.
 Top level Classes or interface can not be declared as private because
 private means “only visible within the enclosing class”.
 protected means “only visible within the enclosing class and any subclasses”
 Hence these modifiers in terms of application to classes, they apply only to nested classes and not on
top level classes

123
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Access Control/Modifiers
 1) Private
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Privatexampledemo{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
} }
 If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error 124
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Access Control/Modifiers
 2) Default
 When no access modifier is specified for a class , method or data member – It is said to be
having the default access modifier by default.
 The data members, class or methods which are not declared using any access modifiers
i.e. having default access modifier are accessible only within the same package.
 In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
class A{
class B{
void msg(){System.out.println("Hello");}
public static void main(String args[]){
}
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

 In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package. 125
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Access Control/Modifiers
 1) Protected
 The protected access modifier is specified using the keyword protected. The methods or
data members declared as protected are accessible within same package or sub
classes in different package.
 In this example, we have created the two packages pack and mypack. The C class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
//save by C.java //save by D.java
package pack; package mypack; Output: Hello
public class C import pack.*;
{
protected void class D extends C{
msg(){System.out.println("Hello");} public static void main(String args[]){
} D obj = new D();
obj.msg();
}
}

126
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Access Control/Modifiers
 1) Public:
 The public access modifier is specified using the keyword public. The public access modifier has the
widest scope among all other access modifiers.
 Classes, methods or data members which are declared as public are accessible from every where in
the program. There is no restriction on the scope of a public data members.
 If other programmers use your class, try to use the most restrictive access level that makes sense for a
particular member. Use private unless you have a good reason not to.
 Avoid public fields except for constants.
//save by A.java //save by B.java Output:
package pack; package mypack; Hello GNITC
public class A{ import pack.*;
public void msg(){ public class B{
System.out.println("Hello GNITC");} public static void main(String args[]){
} A obj = new A();
obj.msg();
}
}
127
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 this Reference
 There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
 Usage of java this keyword
 Here is given the 6 usage of java this keyword.
 this can be used to refer current class instance variable.
 this() can be used to invoke current class constructor.
 this can be used to return the current class instance from the method.
 this can be passed as an argument in the method call.
 this can be used to invoke current class method (implicitly)
 this can be passed as argument in the constructor call.

128
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 this Reference
 Using ‘this’ keyword to refer current class instance variables
//Java code for using 'this' keyword to refer current class instance variables
class Test
{
int a;
int b;
Test(int a, int b) // Parameterized constructor
{ Output:
this.a = a; a = 10 b = 20
this.b = b;
}
void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test(10, 20);
object.display(); 129
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 this Reference
 this() can be used to invoke current class constructor.
// Java code for using this() to invoke current class constructor

class Test
{
int a;
int b; Output:
Test() //Default constructor Inside parameterized constructor
{ Inside default constructor
this(10, 20);
System.out.println("Inside default constructor \n");
}
Test(int a, int b) //Parameterized constructor
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}
public static void main(String[] args)
{
Test object = new Test();
130
} } Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 this Reference
 this can be used to return the current class instance from the method.
//Java code for using 'this' keyword to return the current class instance
class Test
{
int a;
int b; Output:
Test() //Default constructor a = 10 b = 20
{ a = 10;
b = 20; }
Test get() //Method that returns current class instance
{ return this; }
void display() //Displaying value of variables a and b
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test();
object.get().display();
} } 131
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 this Reference
 this can be passed as an argument in the method call.
// Java code for using 'this' keyword as method parameter
class Test
{
int a;
int b; Output:
Test() // Default constructor a = 10 b = 20
{ a = 10;
b = 20; }
// Method that receives 'this' keyword as parameter
void display(Test obj)
{ System.out.println("a = " + a + " b = " + b);
}
void get() // Method that returns current class instance
{ display(this);
}
public static void main(String[] args)
{ Test object = new Test();
object.get();
} } 132
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 this Reference
 this can be used to invoke current class method (implicitly)
// Java code for using this to invoke current class method
class Test {
void display() Output:
{
// calling fuction show() Inside show function
this.show(); Inside display function
System.out.println("Inside display function");
}
void show() {
System.out.println("Inside show function");
}

public static void main(String args[]) {


Test t1 = new Test();
t1.display();
}
}

133
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 this Reference
 this can be passed as argument in the constructor call.
// using this as an argument in constructor call Class with object of Class B as its data member
class A //A.java
{ B obj;
A(B obj) // Parameterized constructor with object of B as a parameter
{
this.obj = obj;
obj.display(); // calling display method of class B Output:
} } Value of x in Class B : 5
class B //B.java
{ int x = 5;
B() // Default Contructor that create a object of A with passing this as an argument in the constructor
{ A obj = new A(this);
}
void display() // method to show value of x
{
System.out.println("Value of x in Class B : " + x);
}
public static void main(String[] args) {
B obj = new B();
} } 134
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Overloading Methods and Constructors
 Constructor Overloading:
 constructor is used for initialization of instance variable . Constructor are invoked when the
object was created and the values are passed in that. Constructor overloading means that
different variable for multiple objects. One object can use only one constructor.

 Method Overloading :
 It can be defined as Using same Method name but calling it using different parameters.

135
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Recursion
 Recursion in java is a process in which a method calls itself continuously. A method in java that calls
itself is called recursive method.
 It makes the code compact but complex to understand.
 A method that calls itself is known as a recursive method. And, this technique is known as recursion.
import java.util.Scanner;
class Factorial {
static int factorial( int n ) {
Output:
if (n != 0)
Enter Number
return n * factorial(n-1); // recursive call
8
else
8 factorial = 40320
return 1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Number");
int number = in.nextInt();
int result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
136
}} Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Garbage Collection
 In C/C++, programmer is responsible for both creation and destruction of objects. Usually programmer
neglects destruction of useless objects. Due to this negligence, at certain point, for creation of new
objects, sufficient memory may not be available and entire program will terminate abnormally causing
OutOfMemoryErrors.
 But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage
collector destroys these objects.
 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words,
it is a way to destroy the unused objects.
 To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
 Advantage of Garbage Collection
 It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
137
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Garbage Collection
 Important terms :
 1. Unreachable objects : An object is said to be unreachable iff
it doesn’t contain any reference to it. Also note that objects
which are part of island of isolation are also unreachable.
Integer i = new Integer(4);
// the new Integer object is reachable via the reference in 'i'
i = null; // the Integer object is no longer reachable.

 2. Eligibility for garbage collection : An object is said to be


eligible for GC(garbage collection) iff it is unreachable. In
above image, after i = null; integer object 4 in heap area is
eligible for garbage collection.

138
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Garbage Collection
 Ways to make an object eligible for GC
 Even though programmer is not responsible to destroy useless objects but it is highly recommended to
make an object unreachable(thus eligible for GC) if it is no longer required.
 There are generally different ways to make an object eligible for garbage collection.
 By nulling the reference
 By assigning a reference to another
 By anonymous object etc.

139
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Garbage Collection
 By nulling the reference
1.Employee e=new Employee();
2.e=null;
 By assigning a reference to another

1.Employee e1=new Employee();


2.Employee e2=new Employee();
3.e1=e2; //now the first object referred by e1 is available for garbage collection
 By anonymous object

1.new Employee();

140
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
public class GarbageTest{
 Garbage Collection public void finalize()
{
 finalize() method System.out.println("object is garbage collected");
 The finalize() method is invoked each time }
before the object is garbage collected. public static void main(String args[])
This method can be used to perform {
GarbageTest s1=new GarbageTest();
cleanup processing. This method is defined
GarbageTest s2=new GarbageTest();
in Object class as: s1=null;
protected void finalize(){} s2=null;
System.gc();
 gc() method } }
 The gc() method is used to invoke the
garbage collector to perform cleanup
processing. The gc() is found in System and Output:
Runtime classes. object is garbage collected

public static void gc(){}


Note :
• There is no guarantee that any one of above two methods will definitely run Garbage Collector.
• The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()
141
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Garbage Collection
 Finalization
 Just before destroying an object, Garbage Collector calls finalize() method on the object to perform
cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.
 finalize() method is present in Object class with following prototype.
protected void finalize() throws Throwable
 Based on our requirement, we can override finalize() method for perform our cleanup activities like
closing connection from database.
 Note :
 The finalize() method called by Garbage Collector not JVM. Although Garbage Collector is one of the
module of JVM.
 Object class finalize() method has empty implementation, thus it is recommended to override finalize()
method to dispose of system resources or to perform other cleanup.
 The finalize() method is never invoked more than once for any given object.
 If an uncaught exception is thrown by the finalize() method, the exception is ignored and finalization of
that object terminates.
142
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.
 In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={‘G',‘n',‘i',‘t',‘c',‘c',‘s',‘e'};
String s=new String(ch);

is same as:
String s=“Gnitccse“;
 Java String class provides a lot of methods to perform operations on string
such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
 The java.lang.String class implements Serializable, Comparable and
CharSequence interfaces.
 But in Java, string is an object that represents a sequence of characters. The
java.lang.String class is used to create a string object.
143
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.
 Creating a string object:
 There are two ways to create String object:
By string literal
By new keyword
 String Literal
 Java String literal is created by using double quotes. For Example:

String s="welcome";
 Each time you create a string literal, the JVM checks the "string constant pool" first.
 If the string already exists in the pool, a reference to the pooled instance is returned.
 If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Note: String objects are stored in a special memory area known as the "string constant144pool".
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.
 Creating a string object:
 2) By new keyword
 String s=new String("Welcome");//creates two objects and one reference variable
 In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
public class StringEx{
public static void main(String args[]){
String s1="java";//creating string by java string literal Output:
char ch[]={'s','t','r','i','n','g','s'}; java
String s2=new String(ch);//converting char array to string strings
String s3=new String("example");//creating java string by new keyword example
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

145
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.
 Java String class methods
 The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

No. Method Description


1 char charAt(int index) returns char value for the particular index
2 int length() returns string length of the string
3 static String format(String format, Object... args) returns a formatted string.
static String format(Locale l, String format, Object...
4 returns formatted string with given locale.
args)
5 String substring(int beginIndex) returns substring for given begin index.
returns substring for given begin index and end
6 String substring(int beginIndex, int endIndex)
index.
returns true or false after matching the sequence of
7 boolean contains(CharSequence s)
char value.
146
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.

No. Method Description


static String join(CharSequence delimiter, CharSequence...
8 returns a joined string.
elements)
static String join(CharSequence delimiter, Iterable<? extends
9 returns a joined string.
CharSequence> elements)
10 boolean equals(Object another) checks the equality of string with the given object.
11 boolean isEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified string.

13 String replace(char old, char new) replaces all occurrences of the specified char value.

14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified CharSequence.

15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
16 String[] split(String regex) returns a split string matching regex.
17 String[] split(String regex, int limit) returns a split string matching regex and limit.
18 String intern() returns an interned string.
147
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.
No. Method Description
19 int indexOf(int ch) returns the specified char value index.

20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.
23 String toLowerCase() returns a string in lowercase.
24 String toLowerCase(Locale l) returns a string in lowercase using specified locale.
25 String toUpperCase() returns a string in uppercase.
26 String toUpperCase(Locale l) returns a string in uppercase using specified locale.

27 String trim() removes beginning and ending spaces of this string.

28 static String valueOf(int value) converts given type into string. It is an overloaded method.
148
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.
 Immutable String in Java
 In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable.
 Once string object is created its data or state can't be changed
but a new string object is created.

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}

Output:
Sachin

149
Dr. M V Narayana, Professor, GNITC
UNIT-I Java programming
 Exploring String Class.
 Immutable String in Java
class Testimmutablestring1
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar

 Because java uses the concept of string literal.


 Suppose there are 5 reference variables, all refers to one object "sachin".
 If one reference variable changes the value of the object, it will be affected to all the
reference variables. That is why string objects are immutable in java.
150
Dr. M V Narayana, Professor, GNITC

You might also like