Nothing Special   »   [go: up one dir, main page]

Programming in Java U19ITT42

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 205

PROGRAMMING IN JAVA – U19ITT42

Course Outcomes
 CO1: Explain the basic concepts of Object Oriented
programming used in java. (K1)
 CO2: Demonstrate the use of inheritance, interface and
package in relevant applications. (K3)
 CO3: Build java applications using exception handling,
thread and generic programming. (K3)
 CO4: Build java distributed applications using Collections
and IO streams. (K3)
 CO5: Exemplify simple graphical user interfaces using
GUI components. (K2)

2
Syllabus
 UNIT I- INTRODUCTION TO JAVAPROGRAMMING
 The History and Evolution of Java - Byte code - Java buzzwords - Data types – Variables – Arrays –
operators - Control statements - Type conversion and casting. Concepts of classes and objects: Basic
Concepts of OOPs – Constructors - Static keyword - Final with data - Access control - This key word -
Garbage collection - Nested classes and inner classes - String class.
 UNIT II- INHERITANCE, PACKAGES AND INTERFACES
 Inheritance: Basic concepts - Forms of inheritance - Super key word – Method overriding - Abstract
classes- Dynamic method dispatch - The Object class. Packages: Defining, Creating and Accessing -
Importing packages. Interfaces: Defining – Implementing – Applying - Variables and extending interfaces
 UNIT III- EXCEPTIONHANDLING,MULTITHREADING
 Concepts of Exception handling - Types of exceptions - Creating own exception - Concepts of
Multithreading - Creating multiple threads – Synchronization - Inter thread communication -
Enumeration - Autoboxing - Generics.
 UNIT IV –COLLECTIONS,I/OSTREAMS
 Collections: List –Vector – Stack - Queue – Deque –Set - SortedSet. Input / Output Basics – Streams –
Byte streams and Character streams – Reading and Writing Console – Reading and Writing Files.
 UNIT V – EVENT DRIVEN PROGRAMMINGAND JDBC
 Events - Delegation event model - Event handling - Adapter classes. AWT: Concepts of components - Font
class - Color class and Graphics - Introduction to Swing – Layout management - Swing Components -
Java Database Connectivity - Programming Example.

3
Text Books and References
 Text Books:
 Herbert Schildt, Java: The Complete Reference 11th Edition, TMH
Publishing Company Ltd, 2018.
 Reference Books:
 Cay S. Horstmann, Gary cornell, Core Java Volume – I Fundamentals, 9th Edition, Prentice
Hall,2013.
 H.M.Dietel and P.J.Dietel, Java How to Program, 11th Edition, Pearson Education/
PHI,2017.
 Cay.S.Horstmann and Gary Cornell, Core Java, Vol 2, Advanced Features, 8th Edition,
Pearson Education, 2008.
 Websites:
 http://www.ibm.com/developerworks/java/
 http://docs.oracle.com/javase/tutorial/rmi/.
 IBM’s tutorials on Swings, AWT controls and JDBC.
 https://www.edureka.co/blog
 https://www.geeksforgeeks.org

4
UNIT I

 INTRODUCTION TO JAVAPROGRAMMING
 The History and Evolution of Java - Byte code - Java buzzwords - Data types –
Variables – Arrays – operators - Control statements - Type conversion and
casting.
 Concepts of classes and objects: Basic Concepts of OOPs – Constructors - Static
keyword - Final with data - Access control - This key word - Garbage collection
- Nested classes and inner classes - String class.

5
INTRODUCTION TO PROGRAMMING
 A computer is a device that can accept human instruction,
processes it and responds to it or a computer is a computational
device which is used to process the data under the control of a
computer program. Program is a sequence of instruction along
with data.
 The basic components of a computer are:
 Input unit
 Central Processing Unit(CPU)
 Output unit
 The CPU is further divided into three parts-
 Memory unit
 Control unit
 Arithmetic Logic unit

6
 A program is a set of instructions given to a computer to perform a specific
operation.
 While executing the program, raw data is processed into a desired output format.
 These computer programs are written in a programming language which are high
level languages.
 High level languages are nearly human languages which are more complex then
the computer understandable language which are called machine language, or low
level language.
 So after knowing the basics, we are ready to create a very simple and basic
program. Like we have different languages to communicate with each other,
likewise, we have different languages like C, C++, C#, Java, python, etc to
communicate with the computers.
 The computer only understands binary language (the language of 0’s and 1’s) also
called machine-understandable language or low-level language but the programs
we are going to write are in a high-level language which is almost similar to
human language.

7
 Hierarchy of Computer language –

8
There have been many programming language some of
them are listed below:
 C  LISP  Dart
 Python  SCALA  Datalog
 C++  Swift  Dbase
 C#  Rust  Haskell
 R  Prolog  Dylan
 Ruby  Reia  Julia
 COBOL  Racket  Ksh
 ADA  Scheme  Metro
 Java  Shimula  Mumps
 Fortran  Perl  Nim
 BASIC  PHP  Ocaml
 Altair BASIC  JavaScript  Pick
 True BASIC  Coffee Script  TCL
 Visual BASIC  Visual FoxPro  D
 GW BASIC  Babel  CPL
 QBASIC  Logo  Curry
 PureBASIC  Lua  Action Script
 PASCAL  Smalltalk  Erlang
 Turbo Pascal  Matlab  Clojure
 GO  F  DarkBASCIC
 ALGOL  F#  Assembly

9
Most Popular Programming Languages –

 C
 Python
 C++
 Java
 SCALA
 C#
 R
 Ruby
 Go
 Swift
 JavaScript
10
Characteristics of a programming
Language –
 A programming language must be simple, easy to learn and use, have good
readability and human recognizable.
 Abstraction is a must-have Characteristics for a programming language in which
ability to define the complex structure and then its degree of usability comes.
 A portable programming language is always preferred.
 Programming language’s efficiency must be high so that it can be easily
converted into a machine code and executed consumes little space in memory.
 A programming language should be well structured and documented so that it is
suitable for application development.
 Necessary tools for development, debugging, testing, maintenance of a program
must be provided by a programming language.
 A programming language should provide single environment known as
Integrated Development Environment(IDE).
 A programming language must be consistent in terms of syntax and semantics.

11
The History and Evolution of Java
 The history of Java is very interesting. Java was originally designed for
interactive television, but it was too advanced technology for the digital
cable television industry at the time.
 The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for
digital devices such as set-top boxes, televisions, etc.
 However, it was suited for internet programming. Later, Java technology
was incorporated by Netscape.
 The principles for creating Java programming were "Simple, Robust,
Portable, Platform-independent, Secured, High Performance, Multithreaded,
Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". 
 Java was developed by James Gosling, who is known as the father of Java,
in 1995. James Gosling and his team members started the project in the early
'90s.

12
 Currently, Java is used in internet programming, mobile devices, games, e-business
solutions, etc. There are given significant points that describe the history of Java.
 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
 2) Initially designed for small, embedded systems in electronic appliances like set-
top boxes.
 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension
was .gt.
 4) After that, it was called Oak and was developed as a part of the Green project.
 Why Java named "Oak"?
 5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
 6) In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies.

13
 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 the first coffee was produced
(called java coffee). It is a kind of espresso bean. Java name was
chosen by James Gosling while having coffee near his office.
 9) Notice that Java is just a name, not an acronym.

14
 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). After the first release of
Java, there have been many additional features added to the language.
Now Java is being used in Windows applications, Web applications,
enterprise applications, mobile applications, cards, etc. Each new
version adds the new features in Java.

15
Java Versions
Release End of Free Extended
Version
date Public Updates Support Until
JDK Beta 1995 ? ?
JDK 1.0 January 1996 ? ?
JDK 1.1 February 1997 ? ?
J2SE 1.2 December 1998 ? ?
J2SE 1.3 May 2000 ? ?
J2SE 1.4 February 2002 October 2008 February 2013
J2SE 5.0 September 2004 November 2009 April 2015
December 2018
Java SE 6 December 2006 April 2013 December 2023, paid support for
Zulu[8]
Java SE 7 July 2011 April 2015 July 2022

January 2019 for Oracle (commercial)


December 2030 for Oracle (non-commercial)
Java SE 8 (LTS) March 2014 December 2030 for Zulu December 2030
At least May 2026 for AdoptOpenJDK
At least May 2026 for Amazon Corretto

Java SE 9 September 2017 March 2018 for OpenJDK N/A


Java SE 10 March 2018 September 2018 for OpenJDK N/A

September 2027 for Zulu


September 2026,
Java SE 11 (LTS) September 2018 At least October 2024 for AdoptOpenJDK
or September 2027 for e.g. Zulu[8]
At least September 2027 for Amazon Corretto

Java SE 12 March 2019 September 2019 for OpenJDK N/A


Java SE 13 September 2019 March 2020 for OpenJDK N/A
Java SE 14 March 2020 September 2020 for OpenJDK N/A
Java SE 15 September 2020 March 2021 for OpenJDK, March 2023 for Zulu[8] N/A
Java SE 16 March 2021 September 2021 for OpenJDK N/A
16
Java terminology
 Java Virtual Machine (JVM)
This is generally referred as JVM. Before, we discuss about JVM lets see the phases of
program execution. Phases are as follows: we write the program, then we compile the
program and at last we run the program.

1) Writing of the program is of course done by java programmer like you and me.

2) Compilation of program is done by javac compiler, javac is the primary java compiler
included in java development kit (JDK). It takes java program as input and generates java
bytecode as output.

3) In third phase, JVM executes the bytecode generated by compiler. This is called program
run phase.

 So, now that we understood that the primary function of JVM is to execute the bytecode
produced by compiler. Each operating system has different JVM, however the output
they produce after execution of bytecode is same across all operating systems. That is
why we call java as platform independent language.

17
 Bytecode

As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it
can be executed by JVM. The bytecode is saved in a .class file by compiler.

 Java Development Kit(JDK)

While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the name
suggests this is complete java development kit that includes JRE (Java Runtime Environment),
compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your computer.

 Java Runtime Environment(JRE)

JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your
system, you can run a java program however you won’t be able to compile it. JRE includes JVM,
browser plugins and applets support. When you only need to run a java program on your computer,
you would only need JRE.

18
 Garbage Collector
 In Java, programmers can’t delete the objects. To delete or recollect that
memory JVM has a program called Garbage Collector.
 Garbage Collector can recollect the of objects that are not referenced. So
Java makes the life of a programmer easy by handling memory
management.
 However, programmers should be careful about their code whether they are
using objects that have been used for a long time. Because Garbage cannot
recover the memory of objects being referenced.
 ClassPath
 The classpath is the file path where the java runtime and Java compiler
looks for .class files to load. By default, JDK provides many libraries. If
you want to include external libraries they should be added to the
classpath.

19
Java Byte Code
 Java bytecode is the instruction set for the Java Virtual Machine. It
acts similar to an assembler which is an alias representation of a C++
code.
 As soon as a java program is compiled, java bytecode is generated. In
more apt terms, java bytecode is the machine code in the form of
a .class file.
 With the help of java bytecode we achieve platform independence in
java.

20
 How does it works?

 When we write a program in Java, firstly, the compiler compiles that program and a bytecode is

generated for that piece of code.

 When we wish to run this .class file on any other platform, we can do so. After the first compilation,

the bytecode generated is now run by the Java Virtual Machine and not the processor in consideration.

 This essentially means that we only need to have basic java installation on any platforms that we want

to run our code on.

 Resources required to run the bytecode are made available by the Java Virtual Machine, which calls the

processor to allocate the required resources.

 JVM's are stack-based so they stack implementation to read the codes.

21
22
Advantage of Java Bytecode
 Hence bytecode is a very important component of any java program.
 The set of instructions for the JVM may differ from system to system but all can interpret the
bytecode.
 A point to keep in mind is that bytecodes are non-runnable codes and rely on the availability of an
interpreter to execute and thus the JVM comes into play.
 Bytecode is essentially the machine level language which runs on the Java Virtual Machine.
Whenever a class is loaded, it gets a stream of bytecode per method of the class.
 Whenever that method is called during the execution of a program, the bytecode for that method
gets invoked.
 Javac not only compiles the program but also generates the bytecode for the program. Thus, we
have realized that the bytecode implementation makes Java a platform-independent language.
 This helps to add portability to Java which is lacking in languages like C or C++. Portability
ensures that Java can be implemented on a wide array of platforms like desktops, mobile devices,
severs and many more.
 Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or
"WORA" in resonance to the bytecode interpretation.

23
Java Buzzwords or Features of Java
 The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java are also
known as java buzzwords.
 A list of most important features of Java language is given below.
 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Dynamic

24
 Simple
 Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
 Object-oriented
 Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior.
 Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.

25
 Platform Independent
 Java is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while Java
is a write once, run anywhere language. A platform is the hardware or software
environment in which a program runs.
 There are two types of platforms software-based and hardware-based. Java
provides a software-based platform.
 The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based platforms.
It has two components:
 Runtime Environment
 API(Application Programming Interface)
 Java code can be run on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere(WORA).

26
Secured
 Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
 No explicit pointer
 Java Programs run inside a virtual machine sandbox
 Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used
to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network
sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
 Security Manager: It determines what resources a class can access such as reading and writing
to the local disk.
 Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

27
 Robust
 Robust simply means strong. Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security problems.
 There is automatic garbage collection in java which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
 There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
 Architecture-neutral
 Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
 In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.

28
 Portable
 Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation.
 High-performance
 Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit
slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++,
etc.
 Distributed
 Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by calling
the methods from any machine on the internet.

29
 Multi-threaded
 A thread is like a separate program, executing concurrently. We
can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading
is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media,
Web applications, etc.
 Dynamic
 Java is a dynamic language. It supports dynamic loading of
classes. It means classes are loaded on demand. It also supports
functions from its native languages, i.e., C and C++.
 Java supports dynamic compilation and automatic memory
management (garbage collection).
30
Overall Execution Process of Java Program

31
Compilation and execution of Java Program
 Example
 public class MyFirstJavaProgram
 { 
  /* This is my first java program.      
  * This will print 'Hello World' as the output        
 */    
 public static void main(String []args)
 {   
 System.out.println("Hello World"); // prints Hello World    
 }
 }
32
 Let's look at how to save the file, compile, and run the program.
Please follow the subsequent steps −
 Open notepad and add the code as above.
 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where
you saved the class. Assume it's C:\.
 Type 'javac MyFirstJavaProgram.java' and press enter to compile
your code. If there are no errors in your code, the command prompt
will take you to the next line (Assumption: The path variable is
set).
 Now, type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see ' Hello World ' printed on the window.

33
Basic Syntax
 About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have a
different meaning in Java.
 Class Names − For all class names, the first letter should be in Upper Case. If several words are
used to form a name of the class, each inner word's first letter should be in Upper Case.
 Example: class MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter. If several words are
used to form the name of the method, then each inner word's first letter should be in Upper
Case.
 Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the class name.
 When saving the file, you should save it using the class name (Remember Java is case sensitive)
and append '.java' to the end of the name (if the file name and the class name do not match, your
program will not compile).
 Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
 public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.

34
Structure of Java Program
 Java is an object-oriented programming, platform-
independent, and secure programming language that makes it
popular. Using the Java programming language, we can develop a
wide variety of applications.

35
Writing a “HELLO WORLD” Program in Java
 // Basic java program
 // to print "Hello World"
   
 import java.io.*;
   
 class GFG
 {
     public static void main(String[] args)
     {
         // prints Hello World
         System.out.println("Hello World");
     }
 }
 Output
 Hello World

36
Explanation:
 1.  Comments: Comments are used for explaining code and are used in a similar manner in Java or C or C++.
Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple
lines.
 Single line Comments:
Syntax:
 // Single line commentMulti-line comments:
Syntax:
 /* Multi line comments*/2.  import java.io.*: Means all the classes of io package can be imported. Java io
package provides a set of input and output streams for reading and writing data to files or other input or output
sources.
 3.  class: The class contains the data and methods to be used in the program. Methods define the behaviour of
the class. Class GFG has only one method Main in JAVA.
 4.  static void Main(): static keyword tells us that this method is accessible without instantiating the class. 
 5.  void: keywords tells that this method will not return anything. The main() method is the entry point of our
application.
 6.  System.in: This is the standard input stream that is used to read characters from the keyboard or any other
standard input device.
 7.  System.out: This is the standard output stream that is used to produce the result of a program on an output
device like the computer screen.
 8.  println(): This method in Java is also used to display a text on the console. It prints the text on the console
and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.

37
Data Types in Java
 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.

38
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

39
 Example
 byte myNum = 100;
 short myNum = 5000;
 int myNum = 5; // Integer (whole number)
 long myNum = 15000000000L;
 float myFloatNum = 5.99f; // Floating point number
 double myNum = 19.99d;
 char myLetter = 'D'; // Character
 boolean myBool = true; // Boolean
 String myText = "Hello"; // String

40
Non-Primitive Data Types
 Non-primitive data types are called reference types because they refer to
objects.
 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.

41
Java Variables
 A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.
 Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
 Variable is name of reserved area allocated in memory. In other
words, it is a name of memory location. It is a combination of "vary +
able" that means its value can be changed.

42
 All Java variables must be identified with unique names.
 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
 The general rules for constructing names for variables (unique
identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs
 Names must begin with a letter
 Names should start with a lowercase letter and it cannot contain whitespace
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive ("myVar" and "myvar" are different variables)
 Reserved words (like Java keywords, such as int or boolean) cannot be used as
names

43
Declaring (Creating) Variables
 To create a variable, you must specify the type and assign
it a value:
 Syntax
 type variable = value;
 Where type is one of Java's types (such as int or String), and
 variable is the name of the variable (such as x or name). The equal
sign is used to assign values to the variable.

44
Types of Variables
 There are three types of variables in Java:
 local variable
 instance variable
 static variable
 1) Local Variable
 A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
 A local variable cannot be defined with "static" keyword.
 2) Instance Variable
 A variable declared inside the class but outside the body of the method, is called instance variable.
It is not declared as static.
 It is called instance variable because its value is instance specific and is not shared among
instances.
 3) Static variable
 A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.

45
Example to understand the types of variables in java
 class A
 {  
 int data=50; //instance variable  
 static int m=100; //static variable  
 void method(){  
 int n=90; //local variable  
 }  
 } //end of class  

46
Operators
 Operator in Java is a symbol which is used to perform operations. For example: +,
-, *, / etc.
 There are many types of operators in Java which are given below:
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator

47
Java Operator Precedence
Operator Type Category Precedence

Unary postfix expr++ expr--


prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |=
<<= >>= >>>=

48
Java Unary Operator
 The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a boolean
 Java Unary Operator Example: ++ and --
 class OperatorExample{  
 public static void main(String args[]){  
 int x=10;  
 System.out.println(x++);//10 (11)  
 System.out.println(++x);//12  
 System.out.println(x--);//12 (11)  
 System.out.println(--x);//10  
 }}  

49
Java Unary Operator Example: ~ and !
 class OperatorExample{  
 public static void main(String args[]){  
 int a=10;  
 int b=-10;  
 boolean c=true;  
 boolean d=false;  
 System.out.println(~a);//-
11 (minus of total positive value which starts from 0)  
 System.out.println(~b);//
9 (positive of total minus, positive starts from 0)  
 System.out.println(!c);//false (opposite of boolean value)  
 System.out.println(!d);//true  
 }}  
50
Java Arithmetic Operators
 Java arithmatic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.
 Java Arithmetic Operator Example
 class OperatorExample{  
 public static void main(String args[]){  
 int a=10;  
 int b=5;  
 System.out.println(a+b);//15  
 System.out.println(a-b);//5  
 System.out.println(a*b);//50  
 System.out.println(a/b);//2  
 System.out.println(a%b);//0  
 }}  
51
Java Left Shift Operator
 The Java left shift operator << is used to shift all of the bits
in a value to the left side of a specified number of times.
 Java Left Shift Operator Example
 class OperatorExample{  
 public static void main(String args[]){  
 System.out.println(10<<2);//10*2^2=10*4=40  
 System.out.println(10<<3);//10*2^3=10*8=80  
 System.out.println(20<<2);//20*2^2=20*4=80  
 System.out.println(15<<4);//15*2^4=15*16=240  
 }}  

52
Java Right Shift Operator
 The Java right shift operator >> is used to move left
operands value to right by the number of bits specified by
the right operand.
 Java Right Shift Operator Example
 class OperatorExample{  
 public static void main(String args[]){  
 System.out.println(10>>2);//10/2^2=10/4=2  
 System.out.println(20>>2);//20/2^2=20/4=5  
 System.out.println(20>>3);//20/2^3=20/8=2  
 }}  

53
Java Shift Operator Example: >> vs >>>
 class OperatorExample{  
 public static void main(String args[]){  
     //For positive number, >> and >>> works same  
     System.out.println(20>>2);  
     System.out.println(20>>>2);  
     //
For negative number, >>> changes parity bit (MSB) to 0  
     System.out.println(-20>>2);  
     System.out.println(-20>>>2);  
 }}  

54
Java Ternary Operator
 Java Ternary operator is used as one liner replacement for if-
then-else statement and used a lot in Java programming. it is
the only conditional operator which takes three operands.
 Java Ternary Operator Example
 class OperatorExample{  
 public static void main(String args[]){  
 int a=2;  
 int b=5;  
 int min=(a<b)?a:b;  
 System.out.println(min);  
 }}  
55
Java Assignment Operator
 Java assignment operator is one of the most common operator. It is
used to assign the value on its right to the operand on its left.
 Java Assignment Operator Example
 class OperatorExample{  
 public static void main(String args[]){  
 int a=10;  
 int b=20;  
 a+=4;//a=a+4 (a=10+4)  
 b-=4;//b=b-4 (b=20-4)  
 System.out.println(a);  
 System.out.println(b);  
 }}  

56
Java AND Operator Example: Logical && and Bitwise &
 The logical && operator doesn't check second condition if first
condition is false. It checks second condition only if first one is true.
 The bitwise & operator always checks both conditions whether first
condition is true or false.
 class OperatorExample{  
 public static void main(String args[]){  
 int a=10;  
 int b=5;  
 int c=20;  
 System.out.println(a<b&&a<c);//false && true = false  
 System.out.println(a<b&a<c);//false & true = false  
 }}  

57
Java OR Operator Example: Logical || and Bitwise |
 The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false.
 The bitwise | operator always checks both conditions whether first condition is true or false.
 class OperatorExample{  
 public static void main(String args[]){  
 int a=10;  
 int b=5;  
 int c=20;  
 System.out.println(a>b||a<c);//true || true = true  
 System.out.println(a>b|a<c);//true | true = true  
 //|| vs |  
 System.out.println(a>b||a++<c);//true || true = true  
 System.out.println(a);//10 because second condition is not checked  
 System.out.println(a>b|a++<c);//true | true = true  
 System.out.println(a);//11 because second condition is checked  
 }}  

58
Arrays
 An array is a collection of similar type of elements which has contiguous memory location.
 Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location.
 It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java
array.
 Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.

 Advantages
 Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.
 Disadvantages
 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.

59
Types of Array in java
 There are two types of array.
 Single Dimensional Array
 Multidimensional Array

Single Dimensional Array in Java


 Syntax to Declare an Array in Java
 dataType[] arr; (or)  
 dataType []arr; (or)  
 dataType arr[];  

 Instantiation of an Array in Java


 arrayRefVar=new datatype[size];  

60
Declaration, Instantiation and Initialization of Java
Array
 We can declare, instantiate and initialize the java array together by:
 int a[]={33,3,4,5};//declaration, instantiation and initialization  
 Example
 class Testarray1{  
 public static void main(String args[]){  
 int a[]={33,3,4,5};//declaration, instantiation and initialization  
 //printing array  
 for(int i=0;i<a.length;i++)//length is the property of array  
 System.out.println(a[i]);  
 }}  

61
 Access the Elements of an Array
 You access an array element by referring to the index number.
 This statement accesses the value of the first element in cars:
 Example
 String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars[0]);
 // Outputs Volvo
 Change an Array Element
 To change the value of a specific element, refer to the index number:
 Example
 cars[0] = "Opel";
 Array Length
 To find out how many elements an array has, use the length property:
 Example
 String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars.length); //
Outputs 4

62
 Loop Through an Array
 You can loop through the array elements with the for loop, and use the length property to
specify how many times the loop should run.
 The following example outputs all elements in the cars array:
 Example
 String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length; i++)
{ System.out.println(cars[i]); }
 Loop Through an Array with For-Each
 There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:
 Syntax
 for (type variable : arrayname) { ... }
 Example
 String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars)
{ System.out.println(i); }

63
Example of Java Array
 Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
 //Java Program to illustrate how to declare, instantiate, initialize  
 //and traverse the Java array.  
 class Testarray{  
 public static void main(String args[]){  
 int a[]=new int[5];//declaration and instantiation  
 a[0]=10;//initialization  
 a[1]=20;  
 a[2]=70;  
 a[3]=40;  
 a[4]=50;  
 //traversing array  
 for(int i=0;i<a.length;i++)//length is the property of array  
 System.out.println(a[i]);  
 }}  

64
Passing Array to a Method in Java
 We can pass the java array to method so that we can reuse the same logic on any array.
 Let's see the simple example to get the minimum number of an array using a method.
 class Testarray2{  
 //creating a method which receives an array as a parameter  
 static void min(int arr[]){  
 int min=arr[0];  
 for(int i=1;i<arr.length;i++)  
  if(min>arr[i])  
   min=arr[i];    
 System.out.println(min);  
 }  
 public static void main(String args[]){  
 int a[]={33,3,4,5};//declaring and initializing an array  
 min(a);//passing array to method  
 }}  

65
Multidimensional Arrays
 A multidimensional array is an array containing one or more arrays.
 Syntax to Declare Multidimensional Array in Java
 dataType[][] arrayRefVar; (or)  
 dataType [][]arrayRefVar; (or)  
 dataType arrayRefVar[][]; (or)  
 dataType []arrayRefVar[];   
 Example to instantiate Multidimensional Array in Java
 int[][] arr=new int[2][2];//2 row and 2 column  
 Example to initialize Multidimensional Array in Java
 arr[0][0]=1;  
 arr[0][1]=2;  
 arr[1][0]=4;  
 arr[1][1]=5;  

66
Example of Multidimensional Java Array
 //Java Program to demonstrate the addition of two matrices in Java  
 class Testarray5{  
 public static void main(String args[]){  
 //creating two matrices  
 int a[][]={{1,3,4},{3,4,5}};  
 int b[][]={{1,3,4},{3,4,5}};  
 //creating another matrix to store the sum of two matrices  
 int c[][]=new int[2][3];  
 //adding and printing addition of 2 matrices  
 for(int i=0;i<2;i++){  
 for(int j=0;j<3;j++){  
 c[i][j]=a[i][j]+b[i][j];  
 System.out.print(c[i][j]+" ");  
 }  
 System.out.println();//new line  
 }  
 }}  

67
Control statements
 A control statement in java is a statement that determines whether the
other statements will be executed or not. It controls the flow of a
program. An ‘if’ statement in java determines the sequence of
execution between a set of two statements.
 Control Statements can be divided into three categories, namely
 Selection statements
 Iteration statements
 Jump statements

68
Selection or Decision-Making Statements
 Statements that determine which statement to execute
and when are known as decision-making statements.
The flow of the execution of the program is controlled
by the control flow statement.
 There are four decision-making statements available in
java.
 Simple if statement
 if-else statement
 Nested if statement
 Switch statement

69
Simple if statement
 if statement is the most simple decision making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
 Syntax:
 if(condition)
{
 // Statements to execute if condition is true
 }
 Here, condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For example,
 if(condition)
 statement1;
 statement2;
 // Here if the condition is true, if block will consider only statement1 to be inside its block.

70
Example:
 // Java program to illustrate If statement
 class IfDemo
 {
     public static void main(String args[])
     {
         int i = 10;
         if (i > 15)
        System.out.println("10 is less than 15");
   // This statement will be executed
    // as if considers one statement by default
         System.out.println("I am Not in if");
     }
 }

71
if-else
 The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false. Here comes the else statement. We can use
the else statement with if statement to execute a block of code when the condition is
false.
 Syntax:
 if (condition)
 { // Executes this block if // condition is true }
 else
 { // Executes this block if // condition is false }

72
Example:
 // Java program to illustrate if-else statement
 class IfElseDemo
 {
     public static void main(String args[])
     {
         int i = 10;
   
         if (i < 15)
             System.out.println("i is smaller than 15");
         else
             System.out.println("i is greater than 15");
     }
 }
 Output:
 i is smaller than 15

73
nested-if: 
 A nested if is an if statement that is the target of another if or else. Nested if statements
means an if statement inside an if statement. Yes, java allows us to nest if statements within
if statements. i.e, we can place an if statement inside another if statement.
 Syntax:
 if (condition1)
 {
 // Executes when condition1 is true
 if (condition2)
 {
 // Executes when condition2 is true
 }
 }

74
Example:
 // Java program to illustrate nested-if statement
 class NestedIfDemo
 {
     public static void main(String args[])  {
         int i = 10;
           if (i == 10)
         {
                       if (i < 15)
                 System.out.println("i is smaller than 15");
                                     if (i < 12)
                 System.out.println("i is smaller than 12 too");
             else
                 System.out.println("i is greater than 15");
         }
     }
 }

75
if-else-if ladder:
 Here, a user can decide among multiple options.The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.
 Synatax:
 if (condition)
 statement;
 else if (condition)
 statement;
 .
 .
 else statement;

76
Example:
 // Java program to illustrate if-else-if ladder
 class ifelseifDemo
 {
     public static void main(String args[])
     {
         int i = 20;
           if (i == 10)
             System.out.println("i is 10");
         else if (i == 15)
             System.out.println("i is 15");
         else if (i == 20)
             System.out.println("i is 20");
         else
             System.out.println("i is not present");
     }
 }

77
switch-case 
 The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to
different parts of code based on the value of the expression.
 Syntax:
 switch (expression)
 {
 case value1:
 statement1;
 break;
 case value2:
 statement2;
 break;
 ..
 case valueN:
 statementN;
 break;
 default:
 statementDefault;
 }

78
 Expression can be of type byte, short, int char or an enumeration.
Beginning with JDK7, expression can also be of type String.
 Duplicate case values are not allowed.
 The default statement is optional.
 The break statement is used inside the switch to terminate a statement
sequence.
 The break statement is optional. If omitted, execution will continue
on into the next case.

79
Example:
 // Java program to illustrate switch-case
 class SwitchCaseDemo
 {
     public static void main(String args[])
     {
         int i = 9;
         switch (i)
         {
         case 0:
             System.out.println("i is zero.");
             break;
         case 1:
             System.out.println("i is one.");
             break;
                 default:
             System.out.println("i is greater than 2.");
         }
     }
 }

80
Jump Statements
 Java supports three jump statement: break, continue and return.
 These three statements transfer control to other part of the program.
 Break: In Java, break is majorly used for:
 Terminate a sequence in a switch statement
 To exit a loop.
 Used as a “civilized” form of goto.

 Using break to exit a Loop


 Using break, we can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the
innermost loop.

81
Example:
 // Java program to illustrate using
 // break to exit a loop
 class BreakLoopDemo
 {
     public static void main(String args[])
     {
         // Initially loop is set to run from 0-9
         for (int i = 0; i < 10; i++)
         {
             // terminate loop when i is 5.
             if (i == 5)
                 break;
               System.out.println("i: " + i);
         }
         System.out.println("Loop complete.");
     }
 }

82
Continue: 
 Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration.
 This is, in effect, a goto just past the body of the loop, to the loop’s end.
 The continue statement performs such an action.

83
Example:
 class ContinueDemo
 {
     public static void main(String args[])
     {
         for (int i = 0; i < 10; i++)
         {
             // If the number is even
             // skip and continue
             if (i%2 == 0)
                 continue;
             // If number is odd, print it
             System.out.print(i + " ");
         }
     }
 }

84
Return
 The return statement is used to explicitly return from a method. That is, it causes a program
control to transfer back to the caller of the method.
 Example:
 class Return
 {
     public static void main(String args[])
     {
         boolean t = true;
         System.out.println("Before the return.");
               if (t)
             return;
           // Compiler will bypass every statement 
         // after return
         System.out.println("This won't execute.");
     }
 }

85
Loops in Java
 In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true. There are three types of loops in
Java.
 for loop
 while loop
 do-while loop

86
Java For Loop vs While Loop vs Do While Loop
Comparison for loop while loop do while loop
Introduction The Java for loop is a control The Java while loop is a The Java do while loop is a
flow statement that iterates a control flow statement that control flow statement that
part of the programs multiple executes a part of the executes a part of the programs
times. programs repeatedly on the at least once and the further
basis of given boolean execution depends upon the
condition. given boolean condition.

When to use If the number of iteration is If the number of iteration is If the number of iteration is not
fixed, it is recommended to use not fixed, it is recommended fixed and you must have to
for loop. to use while loop. execute the loop at least once, it
is recommended to use the do-
while loop.

Syntax for(init;condition;incr/decr){ // while(condition){ //code to be do{ //code to be


code to be executed } executed } executed }while(condition);

Example //for loop for(int i=1;i<=10;i+ //while loop int i=1; //do-while loop int i=1;
+){ System.out.println(i); } while(i<=10) do{ System.out.println(i); i+
{ System.out.println(i); i+ +; }while(i<=10);
+; }
Syntax for for(;;){ //code to be executed } while(true){ //code to be do{ //code to be
infinitive loop executed } executed }while(true);

87
Java For Loop
 The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed,
it is recommended to use for loop.
 There are three types of for loops in java.
 Simple For Loop
 For-each or Enhanced For Loop
 Labeled For Loop
 Java Simple For Loop
 A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
 Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
 Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
 Statement: The statement of the loop is executed each time until the second condition is false.
 Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

88
 Syntax:
 for(initialization; condition; incr/decr)
 {  
 //statement or code to be executed  
 }  

89
 Example:
 //Java Program to demonstrate the example of for loop  
 //which prints table of 1  
 public class ForExample {  
 public static void main(String[] args) {  
     //Code of Java for loop  
     for(int i=1;i<=10;i++){  
         System.out.println(i);  
     }  
 }  
 }  
90
Java Nested For Loop
 If we have a for loop inside the another loop, it is known as nested for loop.
The inner loop executes completely whenever outer loop executes.
 Example:
 public class NestedForExample {  
 public static void main(String[] args) {  
 //loop of i  
 for(int i=1;i<=3;i++){  
 //loop of j  
 for(int j=1;j<=3;j++){  
         System.out.println(i+" "+j);  
 }//end of i  
 }//end of j  
 }  
 }  

91
Java for-each Loop
 The for-each loop is used to traverse array or collection in java. It is
easier to use than simple for loop because we don't need to increment
value and use subscript notation.
 It works on elements basis not index. It returns element one by one in
the defined variable.
 Syntax:
 for(Type var:array){  
 //code to be executed  
 }  

92
 Example:
 //Java For-each loop example which prints the  
 //elements of the array  
 public class ForEachExample {  
 public static void main(String[] args) {  
     //Declaring an array  
     int arr[]={12,23,44,56,78};  
     //Printing array using for-each loop  
     for(int i:arr){  
         System.out.println(i);  
     }  
 }  
 }  
93
Java Labeled For Loop
 We can have a name of each Java for loop. To do so, we use label
before the for loop. It is useful if we have nested for loop so that we
can break/continue specific for loop.
 Usually, break and continue keywords breaks/continues the innermost
for loop only.
 Syntax:
 labelname:  
 for(initialization;condition;incr/decr){  
 //code to be executed  
 }  

94
Example:
 //A Java program to demonstrate the use of labeled for loop  
 public class LabeledForExample {  
 public static void main(String[] args) {  
     //Using Label for outer and for loop  
     aa:  
         for(int i=1;i<=3;i++){  
             bb:  
                 for(int j=1;j<=3;j++){  
                     if(i==2&&j==2){  
                         break aa;  
                     }  
                     System.out.println(i+" "+j);  
                 }  
         }  
 }  
 }  

95
Java Infinitive For Loop
 If you use two semicolons ;; in the for loop, it will be infinitive for loop.
 Syntax:
 for(;;){  
 //code to be executed  
 }  
 Example:
 //Java program to demonstrate the use of infinite for loop  
 //which prints an statement  
 public class ForExample {  
 public static void main(String[] args) {  
     //Using no condition in for loop  
     for(;;){  
         System.out.println("infinitive loop");  
     }  
 }  
 }  
 you need to press ctrl+c to exit from the program.

96
Java While Loop
 The Java while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed, it is recommended to use
while loop.
 Syntax:
 while(condition)
 {  
 //code to be executed  
 }  

97
 Example:
 public class WhileExample {  
 public static void main(String[] args) {  
     int i=1;  
     while(i<=10){  
         System.out.println(i);  
     i++;  
     }  
 }  
 }  

98
Java Infinitive While Loop
 If you pass true in the while loop, it will be infinitive while loop.
 Syntax:
 while(true){  
 //code to be executed  
 }  
 Example:
 public class WhileExample2 {  
 public static void main(String[] args) {  
     while(true){  
         System.out.println("infinitive while loop");  
     }  
 }  
 }  
99
Java do-while Loop
 The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once,
it is recommended to use do-while loop.
 The Java do-while loop is executed at least once because condition is checked after
loop body.
 Syntax:
 do{  
 //code to be executed  
 }while(condition);  

100
 Example:
 public class DoWhileExample {  
 public static void main(String[] args) {  
     int i=1;  
     do{  
         System.out.println(i);  
     i++;  
     }while(i<=10);  
 }  
 }  

101
Java Infinitive do-while Loop
 If you pass true in the do-while loop, it will be infinitive do-while loop.
 Syntax:
 do{  
 //code to be executed  
 }while(true);  
 Example:
 public class DoWhileExample2 {  
 public static void main(String[] args) {  
     do{  
         System.out.println("infinitive do while loop");  
     }while(true);  
 }  
 }  
102
Type Conversion and 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.
 In Java, there are two types of casting:
 Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

103
Widening Casting
 Widening casting is done automatically when passing a smaller size type to a larger
size type:
 Example
 public class Main
 {
 public static void main(String[] args)
 {
 int myInt = 9;
 double myDouble = myInt; // Automatic casting: int to double
 System.out.println(myInt); // Outputs 9
 System.out.println(myDouble); // Outputs 9.0
 }
 }

104
Narrowing Casting
 Narrowing casting must be done manually by placing the type in
parentheses in front of the value:
 Example
 public class Main
 {
 public static void main(String[] args)
 {
 double myDouble = 9.78;
 int myInt = (int) myDouble; // Manual casting: double to int
 System.out.println(myDouble); // Outputs 9.78
 System.out.println(myInt); // Outputs 9
 }
 }

105
Difference Between Type Casting and Type Conversion
S.N Type Casting Type Conversion

1 Type casting is a mechanism in which one data type is Type conversion allows a compiler to convert one data
converted to another data type using a casting () type to another data type at the compile time of a
operator by a programmer. program or code.
2 It can be used both compatible data type and Type conversion is only used with compatible data
incompatible data type. types, and hence it does not require any casting
operator.
3 It requires a programmer to manually casting one data It does not require any programmer intervention to
into another type. convert one data type to another because the compiler
automatically compiles it at the run time of a program.

4 It is used while designing a program by the programmer. It is used or take place at the compile time of a
program.
5 When casting one data type to another, the destination When converting one data type to another, the
data type must be smaller than the source data. destination type should be greater than the source data
type.
6 It is also known as narrowing conversion because one It is also known as widening conversion because one
larger data type converts to a smaller data type. smaller data type converts to a larger data type.
7 It is more reliable and efficient. It is less efficient and less reliable.
8 There is a possibility of data or information being lost in In type conversion, data is unlikely to be lost when
type casting. converting from a small to a large data type.
8 float b = 3.0; int a = (int) b int x = 5, y = 2, c; float q = 12.5, p; p = q/x;
106
 Concepts of classes and objects: Basic Concepts of OOPs –
Constructors - Static keyword - Final with data - Access control -
This key word - Garbage collection - Nested classes and inner
classes - String class.

107
Introduction of Object Oriented
Programming
 Object-Oriented Programming or OOPs refers to
languages that use objects in programming.
 Object-oriented programming aims to implement real-
world entities like inheritance, hiding, polymorphism, etc
in programming.
 The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the
code can access this data except that function.

108
OOPs Concepts:
 Class
 Objects
 Data Abstraction 
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing

109
1. Class:
 A class is a user-defined data type. It consists of data members
and member functions, which can be accessed and used by
creating an instance of that class.
 It represents the set of properties or methods that are common to
all objects of one type. A class is like a blueprint for an object.  
 For Example: 
 Consider the Class of Cars.
 There may be many cars with different names and brands but all
of them will share some common properties like all of them will
have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is
the class, and wheels, speed limits, mileage are their properties.

110
2. Object: 
 It is a basic unit of Object-Oriented Programming and represents the real-
life entities.
 An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is allocated.
 An object has an identity, state, and behavior. Each object contains data and code to
manipulate the data. Objects can interact without having to know details of each
other’s data or code, it is sufficient to know the type of message accepted and type
of response returned by the objects. 
 For example “Dog” is a real-life Object, which has some characteristics like color,
Breed, Bark, Sleep, and Eats.

111
3. Data Abstraction & Encapsulation: 
 Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the
data to the outside world, hiding the background details or implementation.
 Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car, but he
does not know about how on pressing the accelerator the speed is increasing, he does not
know about the inner mechanism of the car or the implementation of the accelerator, brakes,
etc in the car. This is what abstraction is.
 Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates.
 In Encapsulation, the variables or data of a class are hidden from any other class and can be
accessed only through any member function of their 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.

112
4. Inheritance: 
 Inheritance is an important pillar of OOP(Object-Oriented Programming). The
capability of a class to derive properties and characteristics from another class is
called Inheritance.
 When we write a class, we inherit properties from other classes. So when we create
a class, we do not need to write all the properties and functions again and again, as
these can be inherited from another class that possesses it.
 Inheritance allows the user to reuse the code whenever possible and reduce its
redundancy.

113
5. Polymorphism: 
 The word polymorphism means having many forms. In simple
words, we can define polymorphism as the ability of a message to be
displayed in more than one form.
 For example, A person at the same time can have different
characteristics. Like a man at the same time is a father, a husband, an
employee. So the same person posses different behavior in different
situations. This is called polymorphism.

114
6. Dynamic Binding:
 In dynamic binding, the code to be executed in response to the
function call is decided at runtime. 
 Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. 
 Dynamic Method Binding One of the main advantages of inheritance
is that some derived class D has all the members of its base class B.
Once D is not hiding any of the public members of B, then an object
of D can represent B in any context where a B could be used. This
feature is known as subtype polymorphism.

115
7. Message Passing:
 It is a form of communication used in object-oriented programming
as well as parallel programming. Objects communicate with one
another by sending and receiving information to each other.
 A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates
the desired results.
 Message passing involves specifying the name of the object, the
name of the function, and the information to be sent.

116
Concepts of Class and Object
 What is an object in Java
 An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.

117
An object has three characteristics:
 State: represents the data (value) of an object.
 Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM
to identify each object uniquely.

118
 For Example, Pen is an object. Its name is Reynolds; color is white, known as its
state. It is used to write, so writing is its behavior.
 An object is an instance of a class. A class is a template or blueprint from which
objects are created. So, an object is the instance(result) of a class.
 Object Definitions:
 An object is a real-world entity.
 An object is a runtime entity.
 The object is an entity which has state and behavior.
 The object is an instance of a class.

119
 What is a class in Java
 A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical
entity. It can't be physical.
 A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface

120
Syntax to declare a class:
 class <class_name>
 {  
     field;  
     method;  
 }  
 Instance variable in Java
 A variable which is created inside the class but outside the method is known as an instance variable.
Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or
instance is created. That is why it is known as an instance variable.
 Method in Java
 In Java, a method is like a function which is used to expose the behavior of an object.
 Advantage of Method
 Code Reusability
 Code Optimization

 New Keyword
 The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.

121
Object and Class Example: main within the class
 In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.
 File: Student.java
 //Defining a Student class.  
 class Student{  
  //defining fields  
  int id;//field or data member or instance variable  
  String name;  
  //creating main method inside the Student class  
  public static void main(String args[]) {  
   //Creating an object or instance  
   Student s1=new Student();//creating an object of Student  
   //Printing values of the object  
   System.out.println(s1.id); //accessing member through reference variable  
   System.out.println(s1.name);  
  }  
 }  

122
Object and Class Example: main outside the class
 In real time development, we create classes and use it from another class. It is a
better approach than previous one. Let's see a simple example, where we are having
main() method in another class.
 We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has main() method.

123
File: TestStudent1.java
 //Java Program to demonstrate having the main method in   
 //another class  
 //Creating Student class.  
 class Student{  
  int id;  
  String name;  
 }  
 //Creating another class TestStudent1 which contains the main method  
 class TestStudent1{  
  public static void main(String args[]){  
   Student s1=new Student();  
   System.out.println(s1.id);  
   System.out.println(s1.name);  
  }  
 }  

124
3 Ways to initialize object
 There are 3 ways to initialize object in Java.
 By reference variable
 By method
 By constructor

125
1) Object and Class Example: Initialization through
reference
 Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.
 File: TestStudent2.java
 class Student
 {  
  int id;  
  String name;  
 }  
 class TestStudent2{  
  public static void main(String args[]){  
   Student s1=new Student();  
   s1.id=101;  
   s1.name="Sonoo";  
   System.out.println(s1.id+" "+s1.name);//printing members with a white space  
  }  
 }  

126
2) Object and Class Example: Initialization
through method
 In this example, we are creating the two   void displayInformation()
objects of Student class and initializing {System.out.println(rollno+" "+name);}  
the value to these objects by invoking the }  
insertRecord method. Here, we are class TestStudent4{  
displaying the state (data) of the objects
 public static void main(String args[]){  
by invoking the displayInformation()
   Student s1=new Student();  
method.
   Student s2=new Student();  
 File: TestStudent4.java
   s1.insertRecord(111,"Karan");  
 class Student{  
   s2.insertRecord(222,"Aryan");  
  int rollno;  
   s1.displayInformation();  
  String name;  
   s2.displayInformation();  
  void insertRecord(int r, String n){  
  }  
   rollno=r;  
 }  
   name=n;  
  }  

127
 As you can see in the above figure, object gets the memory in heap
memory area. The reference variable refers to the object allocated in
the heap memory area. Here, s1 and s2 both are reference variables
that refer to the objects allocated in memory.

128
3) Object and Class Example: Initialization through a
constructor
 Object and Class Example: Employee  public class TestEmployee {  
 File: TestEmployee.java  public static void main(String[] args) {  
 class Employee{        Employee e1=new Employee();  
     int id;        Employee e2=new Employee();  
     String name;        Employee e3=new Employee();  
     float salary;        e1.insert(101,"ajeet",45000);  
     void insert(int i, String n, float s) {        e2.insert(102,"irfan",25000);  
         id=i;        e3.insert(103,"nakul",55000);  
         name=n;        e1.display();  
         salary=s;        e2.display();  
     }        e3.display();  
     void display()  }  
{System.out.println(id+" "+name+" "+sa  }  
lary);}  
 }  

129
What are the different ways to create an object
in Java?
 There are many ways to create an object in java. They are:
 By new keyword
 By newInstance() method
 By clone() method
 By deserialization
 By factory method etc.

130
Real World Example: Account
 File: TestAccount.java ed");    }  
 //  }    //
Java Program to demonstrate the   void withdraw(float amt){   Creating a test class to deposit an
working of a banking-system   d withdraw amount  
 if(amount<amt){  
 class Account{    class TestAccount{  
 System.out.println("Insufficient 
 int acc_no;   Balance");  
 public static void main(String[] 
 String name;   args){  
 }else{  
 float amount;  
 Account a1=new Account();  
 amount=amount-amt;  
 void insert(int a,String n,float a
 a1.insert(832345,"Ankit",1000);  
 System.out.println(amt+" withdr
mt){   awn");  
 a1.display();  
 acc_no=a;    }  
 a1.checkBalance();  
 name=n;    }  
 a1.deposit(40000);  
 amount=amt;    void checkBalance()
 a1.checkBalance();  

 }   {System.out.println("Balance is:   a1.withdraw(15000);  


  void deposit(float amt){   "+amount);}    a1.checkBalance();  

 amount=amount+amt;  
 void display()  }}   
{System.out.println(acc_no+" "+
 System.out.println(amt+" deposit name+" "+amount);}  

131
Array of Objects in Java
 Java is an object-oriented programming language. Most of the work done with the
help of objects.
 We know that an array is a collection of the same data type that dynamically creates
objects and can have elements of primitive types.
 Java allows us to store objects in an array. In Java, the class is also a user-defined
data type.
 An array that conations class type elements are known as an array of objects. It
stores the reference variable of the object.

132
ArrayOfObjects.java
 public class ArrayOfObjects    System.out.println("Product Object 1:"  class Product  
 {   );    {  
 public static void main(String args[])  
 obj[0].display();    int pro_Id;  
 {  
 System.out.println("Product Object 2:"  String pro_name;  
);  
 //create an array of product object     //Product class constructor  
 obj[1].display();  
 Product[] obj = new Product[5] ;    Product(int pid, String n)  
 System.out.println("Product Object 3:"
 // );  
 {  
create & initialize actual product object  pro_Id = pid;  
 obj[2].display();  
s using constructor  
 System.out.println("Product Object 4:"  pro_name = n;  
 obj[0] = new Product(23907,"Dell Lapt
op");   );    }  
 obj[3].display();    public void display()  
 obj[1] = new Product(91240,"HP 630")
;    System.out.println("Product Object 5:"  {  
 obj[2] = new Product(29823,"LG OLE );    System.out.print("Product Id = "+pro_I
D TV");    obj[4].display();   d + "  " + " Product Name = "+pro_na
 obj[3] = new Product(11908,"MI Note   }   me);  
Pro Max 9");    }    System.out.println();  
 obj[4] = new Product(43590,"Kingston  //  }  
 USB");   Product class with product Id and prod  }  
 //display the product object data   uct name as attributes  

133
Constructor
 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.

134
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
 Types of Java constructors
 There are two types of constructors in Java:
 Defaultconstructor (no-arg constructor)
 Parameterized constructor

135
 Java Default Constructor
 A constructor is called "Default Constructor" when it
doesn't have any parameter.
 Syntax of default constructor:
 <class_name>()
 {
 }  

136
Example of default constructor
 //Java Program to create and call a default constructor  
 class Bike1{  
 //creating a default constructor  
 Bike1(){System.out.println("Bike is created");}  
 //main method  
 public static void main(String args[]){  
 //calling a default constructor  
 Bike1 b=new Bike1();  
 }  
 }  

137
138
Example of default constructor that displays the
default values
 class Student3  Student3 s1=new Student3();  
 {    Student3 s2=new Student3();  
 int id;    s1.display();  
 String name;    s2.display();  
 }  
 void display()  }  
 {
 System.out.println(id+" "+name);
}  
 public static void main(String arg
s[])
 {  

139
Java Parameterized Constructor
 A constructor which has a specific number of parameters is called a
parameterized constructor.
 Why use the parameterized constructor?
 The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.

140
Example of parameterized constructor
 class Student4  }  
 {    public static void main(String ar
     int id;   gs[])
     String name;    {  
     Student4(int i,String n)  Student4 s1 = new Student4(111,
"Karan");  
 {  
 Student4 s2 = new Student4(222,
     id = i;  
"Aryan");  
     name = n;        s1.display();  
     }        s2.display();  
  void display()     }  
 {  }  
 System.out.println(id+" "+name);
141
Difference between constructor and method in
Java
Java Constructor Java Method
A constructor is used to initialize A method is used to expose the
the state of an object. behavior of an object.

A constructor must not have a A method must have a return type.


return type.

The constructor is invoked The method is invoked explicitly.


implicitly.

The Java compiler provides a The method is not provided by the


default constructor if you don't compiler in any case.
have any constructor in a class.

The constructor name must be The method name may or may not
same as the class name. be same as the class name.

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

143
 class Student6 }  
 {   void display()
     int id;   {System.out.println(id+" "+name);}  
     String name;   public static void main(String args[]
){  
     Student6(int i,String n){  
Student6 s1 = new Student6(111,"Ka
     id = i;  
ran");  
     name = n;  
Student6 s2 = new Student6(s1);  
     }  
s1.display();  
     Student6(Student6 s)
s2.display();  
 {  
}  
     id = s.id;  
}  
 name =s.name;  
144
 Does constructor return any value?
 Yes, it is the current class instance (You cannot use return type yet it returns a
value).

 Can constructor perform other tasks instead of initialization?


 Yes, like object creation, starting a thread, calling a method, etc. You can perform
any operation in the constructor as you perform in the method.

 Is there Constructor class in Java?


 Yes.

 What is the purpose of Constructor class?


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

145
Java static keyword
 The static keyword in Java is used for memory
management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. 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

146
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).

147
Understanding the problem without static
variable
 class Student{  
      int rollno;  
      String name;  
      String college="ITS";  
 }  
 Suppose there are 500 students in my college, now all instance data
members will get memory each time when the object is created.
 All students have its unique rollno and name, so instance data
member is good in such case.
 Here, "college" refers to the common property of all objects. If we
make it static, this field will get the memory only once.

148
149
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.

150
 class Student{  
      int rollno;  
      String name;  
      static String college = "ITS";  
      //static method to change the value of static variable  
      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);}  
 }  

151
 //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");  
     //calling display method  
     s1.display();  
     s2.display();  
     s3.display();  
     }  
 }  

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

 Why is the Java main method static?


 Ans) 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.

153
 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
 class A2
 {  
   static
 {
 System.out.println("static block is invoked");
 }  
   public static void main(String args[])
 {  
    System.out.println("Hello main");  
   }  
 }  

154
 Q) 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.
 class A3
 {  
   static{  
   System.out.println("static block is invoked");  
   System.exit(0);  
   }  
 }  

155
Final Keyword In Java
 The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
 variable
 method
 class
 The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized
final variable. It can be initialized in the constructor only.
 The blank final variable can be static also which will be initialized in
the static block only.

156
1) Java final variable
 Ifyou make any variable as final, you cannot change the value of final variable(It will be constant).
 Example of final variable
 There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
class Bike9
{  
 final int speedlimit=90;//final variable  
 void run()
{  
  speedlimit=400;  
 }  
 public static void main(String args[])
{  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }  
}//end of class  

157
Java final method
 If you make any method as final, you cannot override it.
 class Bike{  
   final void run(){System.out.println("running");}  
 }  
      
 class Honda extends Bike
 {  
    void run(){System.out.println("running safely with 100kmph");}  
    public static void main(String args[]){  
    Honda honda= new Honda();  
    honda.run();  
    }  
 }  
158
Java final class
 If you make any class as final, you cannot extend it.
 final class Bike{}  
   
 class Honda1 extends Bike{  
   void run()
{System.out.println("running safely with 100kmph");}  
     
   public static void main(String args[]){  
   Honda1 honda= new Honda1();  
   honda.run();  
   }  
 }  
159
What is blank or uninitialized final
variable?
 A final variable that is not initialized at the time of declaration is known as blank final
variable.
 If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
 It can be initialized only in constructor
 class Bike10{  
   final int speedlimit;//blank final variable  
    Bike10(){  
   speedlimit=70;  
   System.out.println(speedlimit);  
   }  
     public static void main(String args[]){  
     new Bike10();  
  }  
 }  

160
static blank final variable
 A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can
be initialized only in static block.
 class A{  
   static final int data;//static blank final variable  
   static{ data=50;}  
   public static void main(String args[]){  
     System.out.println(A.data);  
  }  
 }  

161
 Q) Is final method inherited?
 Yes, final method is inherited but you cannot override it.
 Q) Can we declare a constructor final?
 No, because constructor is never inherited.
 Q) What is final parameter?
 If you declare any parameter as final, you cannot change
the value of it.

162
Access Modifiers in Java
 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 many non-access modifiers, such as static, abstract,
synchronized, native, volatile, transient, etc. Here, we are going to
learn the access modifiers only.

163
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.
164
Access within class within outside outside
Modifier package package by package
subclass only
Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

165
this keyword in java
 There can be a lot of usage of java this keyword. In
java, this is a reference variable that refers to the current
object.

166
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 method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the
method.

167
this: to refer current class instance variable
 The this keyword can be used to refer current class instance variable. If there is ambiguity between
the instance variables and parameters, this keyword resolves the problem of ambiguity.
 class Student
 {  
 int rollno;  
 String name;  
 float fee;  
 Student(int rollno,String name,float fee){  
 this.rollno=rollno;  
 this.name=name;  
 this.fee=fee;  
 }  
 void display(){System.out.println(rollno+" "+name+" "+fee);}  
 }  
   

168
 class TestThis2
 {  
 public static void main(String args[])
 {  
 Student s1=new Student(111,"ankit",5000f);  
 Student s2=new Student(112,"sumit",6000f);  
 s1.display();  
 s2.display();  
 }
 }  
 In the above example, parameters (formal arguments) and instance variables
are same. So, we are using this keyword to distinguish local variable and
instance variable.

169
this: to invoke current class method
 You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while
invoking the method. Let's see the example

170
 class A
 {  
 void m(){System.out.println("hello m");}  
 void n(){  
 System.out.println("hello n");  
 //m();//same as this.m()  
 this.m();  
 }  
 }  
 class TestThis4
 {  
 public static void main(String args[]){  
 A a=new A();  
 a.n();  
 }}  

171
this() : to invoke current class constructor
 The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.
 Calling default constructor from parameterized constructor:
 class A{  
 A(){System.out.println("hello a");}  
 A(int x){  
 this();  
 System.out.println(x);  
 }  
 }  
 class TestThis5{  
 public static void main(String args[]){  
 A a=new A(10);  
 }}  

172
Calling parameterized constructor from default
constructor:
 class A{  
 A(){  
 this(5);  
 System.out.println("hello a");  
 }  
 A(int x){  
 System.out.println(x);  
 }  
 }  
 class TestThis6{  
 public static void main(String args[]){  
 A a=new A();  
 }}  
173
Java Garbage Collection
 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.

174
How can an object be unreferenced?
 There are many ways:
 By nulling the reference
 By assigning a reference to another

 1) By nulling a reference:
 Employee e=new Employee();  
 e=null;  
 2) By assigning a reference to another:
 Employee e1=new Employee();  
 Employee e2=new Employee();  
 e1=e2;
//now the first object referred by e1 is available for garbage collection  

175
 finalize() method
 The finalize() method is invoked each time before the object is
garbage collected. This method can be used to perform cleanup
processing. This method is defined in Object class as:
 protected void finalize(){}  
 gc() method
 The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
 public static void gc(){}  

176
Simple Example of garbage collection in
java
 public class TestGarbage1
 {  
  public void finalize(){System.out.println("object is garbage collected");}  
  public static void main(String args[]){  
   TestGarbage1 s1=new TestGarbage1();  
   TestGarbage1 s2=new TestGarbage1();  
   s1=null;  
   s2=null;  
 // requesting JVM for running Garbage Collector 
  System.gc();  
 Runtime.getRuntime().gc();
  }  
 }  

177
Nested and Inner Class
 Java inner class or nested class is a class which is declared inside the
class or interface.
 We use inner classes to logically group classes and interfaces in one
place so that it can be more readable and maintainable.
 Additionally, it can access all the members of outer class including
private data members and methods.
 Syntax of Inner class
 class Java_Outer_class{  
  //code  
  class Java_Inner_class{  
   //code  
  }  
 }  
178
Advantage of java inner classes
 There are basically three advantages of inner classes in java. They are
as follows:
 1) Nested classes represent a special type of relationship that is it can
access all the members (data members and methods) of outer
class including private.
 2) Nested classes are used to develop more readable and
maintainable code because it logically group classes and interfaces
in one place only.
 3) Code Optimization: It requires less code to write.
 Difference between nested class and inner class in Java
 Inner class is a part of nested class. Non-static nested classes are
known as inner classes.

179
Types of Nested classes
 There are two types of nested classes non-static and static
nested classes. The non-static nested classes are also
known as inner classes.
 Non-static nested class (inner class)
 Member inner class
 Anonymous inner class
 Local inner class
 Static nested class

180
Type Description
Member Inner Class A class created within class and outside method.

Local Inner Class A class created within method.

Static Nested Class A static class created within class.

Nested Interface An interface created within class or interface.

181
Java Member inner class example
 In this example, we are creating msg() method in member inner class that
is accessing the private data member of outer class.
 class TestMemberOuter1{  
  private int data=30;  
  class Inner{  
   void msg(){System.out.println("data is "+data);}  
  }  
  public static void main(String args[]){  
   TestMemberOuter1 obj=new TestMemberOuter1();  
   TestMemberOuter1.Inner in=obj.new Inner();  
   in.msg();  
  }  
 }  

182
Java Local inner class
 A class i.e. created inside a method is called local inner class in java. If you want to invoke
the methods of local inner class, you must instantiate this class inside the method.
 public class localInner1{  
  private int data=30;//instance variable  
  void display(){  
   class Local{  
    void msg(){System.out.println(data);}  
   }  
   Local l=new Local();  
   l.msg();  
  }  
  public static void main(String args[]){  
   localInner1 obj=new localInner1();  
   obj.display();  
  }  
 }  

183
Rules for Java Local Inner class
 Local variable can't be private, public or protected.
 Local inner class cannot be invoked from outside the method.
 Local inner class cannot access non-final local variable till JDK 1.7.
Since JDK 1.8, it is possible to access the non-final local variable in
local inner class.

184
Java static nested class
 A static class i.e. created inside a class is called static nested class in
java. It cannot access non-static data members and methods. It can be
accessed by outer class name.
 It can access static data members of outer class including private.
 Static nested class cannot access non-static (instance) data member or
method.

185
Java static nested class example with instance
method
 class TestOuter1{  
   static int data=30;  
   static class Inner{  
    void msg(){System.out.println("data is "+data);}  
   }  
   public static void main(String args[]){  
   TestOuter1.Inner obj=new TestOuter1.Inner();  
   obj.msg();  
   }  
 }  

186
Java Nested Interface
 An interface i.e. declared within another interface or class is known
as nested interface.
 The nested interfaces are used to group related interfaces so that they
can be easy to maintain.
 The nested interface must be referred by the outer interface or class.
It can't be accessed directly.
 Points to remember for nested interfaces
 There are given some points that should be remembered by the java
programmer.
 Nested interface must be public if it is declared inside the interface
but it can have any access modifier if declared within the class.
 Nested interfaces are declared static implicitely.

187
 Syntax of nested interface which is declared within the interface
 interface interface_name{  
  ...  
  interface nested_interface_name{  
   ...  
  }  
 }   
 Syntax of nested interface which is declared within the class
 class class_name{  
  ...  
  interface nested_interface_name{  
   ...  
  }  
 }   

188
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={'j','a','v','a','t','p','o','i','n','t'};  
 String s=new String(ch);  
 is same as:
 String s="javatpoint";  
 Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.

189
 The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

 CharSequence Interface
 The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create
strings in java by using these three classes.

190
 The Java String is immutable which means it cannot be changed.
Whenever we change any string, a new instance is created. For
mutable strings, you can use StringBuffer and StringBuilder classes.
 What is String in java
 Generally, String is a sequence of characters. 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.
 How to create a string object?
 There are two ways to create String object:
 By string literal
 By new keyword

191
1) 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  

192
193
 In the above example, only one object will be created. Firstly, JVM
will not find any string object with the value "Welcome" in string
constant pool, that is why it will create a new object.
 After that it will find the string with the value "Welcome" in the pool,
it will not create a new object but will return the reference to the same
instance.
 String objects are stored in a special memory area known as the
"string constant pool".
 Why Java uses the concept of String literal?
 To make Java more memory efficient (because no new objects are
created if it exists already in the string constant pool).

194
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 StringExample{  
 public static void main(String args[]){  
 String s1="java";//creating string by java string literal  
 char ch[]={'s','t','r','i','n','g','s'};  
 String s2=new String(ch);//converting char array to string  
 String s3=new String("example");//creating java string by new keyword  
 System.out.println(s1);  
 System.out.println(s2);  
 System.out.println(s3);  
 }}  

195
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
3 static String format(String returns a formatted string.
format, Object... args)
4 static String format(Locale l, returns formatted string with given
String format, Object... args) locale.
5 String substring(int beginIndex) returns substring for given begin
index.
6 String substring(int beginIndex, returns substring for given begin index
int endIndex) and end index.
7 boolean contains(CharSequence returns true or false after matching
s) the sequence of char value.

196
8 static String join(CharSequence returns a joined string.
delimiter, CharSequence... elements)
9 static String join(CharSequence returns a joined string.
delimiter, Iterable<? extends
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.

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

15 static String compares another string. It


equalsIgnoreCase(String another) 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.

198
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 returns the specified substring
fromIndex) index starting with given index.
23 String toLowerCase() returns a string in lowercase.

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

200
Java StringBuffer class

No. String StringBuffer


1) String class is immutable. StringBuffer class is mutable.

2) String is slow and consumes more memory StringBuffer is fast and consumes
when you concat too many strings because less memory when you cancat
every time it creates new instance. strings.

3) String class overrides the equals() method StringBuffer class doesn't override
of Object class. So you can compare the the equals() method of Object
contents of two strings by equals() method. class.

201
Difference between StringBuffer and StringBuilder

No. StringBuffer StringBuilder


1) StringBuffer is synchronized i.e. thread StringBuilder is non-synchronized i.e.
safe. It means two threads can't call the not thread safe. It means two threads
methods of StringBuffer simultaneously. can call the methods of StringBuilder
simultaneously.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

202
Example
 // Java program to demonstrate difference
 // between String, StringBuilder and StringBuffer
 class Geeksforgeeks {
     // Concatenates to String
     public static void concat1(String s1)
     {
         s1 = s1 + "forgeeks";
     }
      // Concatenates to StringBuilder
     public static void concat2(StringBuilder s2)
     {
         s2.append("forgeeks");
     }
      // Concatenates to StringBuffer
     public static void concat3(StringBuffer s3)
     {
         s3.append("forgeeks");
     }
  

203
 public static void main(String[] args)    // s3 is changed
     {     concat3(s3);
   String s1 = "Geeks";   System.out.println("StringBuffer: " + s3);
   // s1 is not changed      }
   concat1(s1);  }
  System.out.println("String: " + s1);  OUTPUT:
    String: Geeks
 StringBuilder s2 = new  StringBuilder: Geeksforgeeks
StringBuilder("Geeks");  StringBuffer: Geeksforgeeks
  // s2 is changed
  concat2(s2);
 System.out.println("StringBuilder: " + s2);
  
 StringBuffer s3 = new
StringBuffer("Geeks");

204
End of I Unit

205

You might also like