0% found this document useful (0 votes)
21 views199 pages

Java Unit 1

The document outlines a Java programming course, detailing its outcomes, syllabus, and key topics including OOP concepts, inheritance, exception handling, collections, GUI programming, and JDBC. It also provides a brief history of Java, its evolution, and the significance of its various versions. Additionally, it lists textbooks and web resources for further learning in Java programming.

Uploaded by

Muruganandham J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views199 pages

Java Unit 1

The document outlines a Java programming course, detailing its outcomes, syllabus, and key topics including OOP concepts, inheritance, exception handling, collections, GUI programming, and JDBC. It also provides a brief history of Java, its evolution, and the significance of its various versions. Additionally, it lists textbooks and web resources for further learning in Java programming.

Uploaded by

Muruganandham J
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 199

PROGRAMMING IN JAVA – U23ITTC02

Course Outcomes
 CO1: Articulate the concept of Java
fundamentals, OOPs and Strings (K2)
 CO2: Demonstrate the principles of inheritance,
packages and interfaces with real time
applications (K3)
 CO3: Create real time applications using
exception handling and thread programming. (K3)
 CO4: Build distributed applications using
Collections and IO streams (K3)
 CO5: Design and build simple GUI programs using
AWT, Swings and build database applications
(K3)

2
Syllabus
 UNIT I- INTRODUCTION UNIT III- EXCEPTIONHANDLING AND
 Introduction: Java: History – Features – JVM - MULTITHREADING
JRE – JDK – Java Compilation and Execution – Exception Handling: Exception Hierarchy – Checked
Data Types - Variables, Types, Expressions, and Unchecked Exceptions – try, catch, throws, throw
Assignment Statements, Input/Output Statements: and finally– User Defined Exceptions.
Scanner/System class,Type Casting (Primitives to Multithreading: Thread – Life cycle – Defining and
Primitives), Conditional and Iterative Control Running – Implementation Types – Thread Priorities
Structures – Arrays – Thread Synchronization - Inter-Thread
 OOPs with Java: Introduction to OOPs Concepts - Communication
Class – Objects – Methods - Access Modifiers –
Creating Class and Objects, Object Life-Cycle - UNIT IV –COLLECTIONS AND I/OSTREAMS
Garbage Collection-Constructors - this – static – Collections: List: ArrayList and LinkedList. Set:
Array of Objects – Nested Classes. HashSet and TreeSet. Map: HashMap – Stack –
Queue. Lambda Expressions.
 String: String Class– Built-in Methods – I/O Streams: Streams – Byte Streams and Character
StringBuilder – StringBuffer Streams – FileInputStream and FileOutputStream –
 UNIT II- INHERITANCE, INTERFACES AND FileReader and FileWriter.
PACKAGES Object Serialization : ObjectInputStream and
 ObjectOutputStream
Inheritance: Types of Inheritance – is-a
Relationship, has-a Relationship – super keyword –
UNIT V – GUI AND JDBC
final keyword – Polymorphism - Method
AWT: Components – Controls – Event Handling.
overloading and Method overriding – Abstract
SWING: Swing Components – Layout Management.
Class
JDBC: JDBC Architecture – JDBC Driver Types –
 Interfaces: Define – Extend – Implement – Access - Implementation of JDBC.
Interfaces vs Abstract classes,
 Type Conversions (Primitives to Objects vice-
versa): Autoboxing and Auto unboxing
 Packages: Define – Create – Access – Import
3
Text Books and References

 Text Books:
 Allen B. Downey and Chris Mayeld, “Think Java - How to Think Like a
Computer Scientist”, 2nd Edition, Green Tea Press, 2020
 Herbert Schildt, “Java: The Complete Reference”, TMH Publishing Company
Ltd, 11th Edition, 2018.
 H.M.Dietel and P.J.Dietel, “Java How to Program”, 11th Edition, Pearson
Education/PHI, 2017
 Cay S. Horstmann, Gary Cornell, “Core Java Volume - I Fundamentals”, 9th
Edition, Prentice Hall, 2013.
 Reference Books:
 Sagayaraj, Denis, Karthik, Gajalakshmi, “JAVA Programming for core
and advanced learners”, Universities Press Private Limited, 2018.
 Poaul Deitel, Harvey Deitel, “Java SE 8 for programmers”, 3rd Edition,
Pearson, 2015.
 P.J. Dietel and H.M Dietel, “Java for Programmers”, Pearson Education,
9th Edition, 2011.
 Steven Holzner, “Java 2 Black book”, Dreamtech Press, 2011.
4
Text Books and References

 Web References
 1. https://www.javatpoint.com/java-tutorial
 2. https://docs.oracle.com/en/java/
 3. https://www.studytonight.com/java/
 4. https://onlinecourses.nptel.ac.in/

5
UNIT I
INTRODUCTION
 Introduction: Java: History – Features – JVM - JRE – JDK –
Java Compilation and Execution – Data Types - Variables, Types,
Expressions, Assignment Statements, Input / Output Statements:
Scanner/System class, Type Casting (Primitives to Primitives),
Conditional and Iterative Control Structures – Arrays

 OOPs with Java: Introduction to OOPs Concepts - Class –


Objects – Methods - Access Modifiers – Creating Class and
Objects, Object Life-Cycle - Garbage Collection-Constructors -
this – static – Array of Objects – Nested Classes.

 String: String Class– Built-in Methods – String Builder – String


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

8
 Hierarchy of Computer language –

9
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

10
Most Popular Programming Languages –

 C
 Python
 C++
 Java
 SCALA
 C#
 R
 Ruby
 Go
 Swift
 JavaScript
11
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.
12
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.
13
 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.

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

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

16
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
December 2030 for Zulu
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 At least October 2024 for AdoptOpenJDK
September 2018 or September 2027 for e.g.
(LTS) At least September 2027 for Amazon
Zulu[8]
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
March 2021 for OpenJDK, March 2023 for
Java SE 15 September 2020 N/A
Zulu[8]
Java
17 SE 16 March 2021 September 2021 for OpenJDK N/A
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.
18
 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.
19
 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.
20
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.

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

22
23
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.

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

26
 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).
27
 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.

28
 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.
29
 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.
30
 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).
31
Overall Execution Process of Java Program

32
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
 }
 }
33
 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.
34
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.

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

36
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
37
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.

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

39
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

40
 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
41String myText = "Hello"; // String
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.

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

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

45
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.
46
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

47
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

48
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 = += -= *= /= %= &= ^= |=
<<= >>= >>>=

49
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
 }}
50
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
 }}

51
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
 }}
52
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
 }}
53
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
 }}

54
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 (MS
B) to 0
 System.out.println(-20>>2);
 System.out.println(-20>>>2);
 }}
55
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);
 }}
56
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);
 }}
57
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
 }}
58
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
 }}
59
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.

60
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];

61
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]);
 }}
62
 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

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

64
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]);
 }}
65
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
 }}
66
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;

67
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
 }
 }}
68
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

69
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

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

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

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

73
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
74
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
 }
 }

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

77
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");
 }
 }
78
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;
 }
79
 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.

80
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.");
 }
 }
 }
81
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.
82
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.");
 }
 }
83
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.

84
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 + " ");
 }
 }
 }
85
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.");
 }
 }

86
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

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

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

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

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

91
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
 }
 }
92
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
 }

93
 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);
 }
 }
 }
94
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
 }

95
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);
 }
 }
 }
 }
96
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.
97
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
 }

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

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

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

102
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);
 }
 }
103
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

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

105
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
 }
 }
106
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;
107
 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.

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

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

110
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.
111
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.

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

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

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

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

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

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

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

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

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

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

122
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);
 }
 }
123
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.

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

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

126
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
 }
 }
127
2) Object and Class Example: Initialization
through method
 In this example, we are creating void displayInformation()
the two objects of Student class {System.out.println(rollno+" "+n
and initializing the value to these ame);}
objects by invoking the }
insertRecord method. Here, we class TestStudent4{
are displaying the state (data) of
public static void main(String a
the objects by invoking the
rgs[]){
displayInformation() method.  Student s1=new Student();
 File: TestStudent4.java  Student s2=new Student();
 class Student{  s1.insertRecord(111,"Karan");
 int rollno;  s2.insertRecord(222,"Aryan");
 String name;  s1.displayInformation();
 void insertRecord(int r, String n) 
{ s2.displayInformation();
 rollno=r;
 }
 name=n;
 }
 }
128
 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.
129
3) Object and Class Example: Initialization through
a constructor
 Object and Class Example:  public class TestEmployee {
Employee  public static void main(String[] ar
 File: TestEmployee.java gs) {
 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);
){  e3.insert(103,"nakul",55000);
 id=i;  e1.display();
 name=n;  e2.display();
 salary=s;  e3.display();
 }  }
 void display()  }
{System.out.println(id+" "+name+
" "+salary);}
 }

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

131
Real World Example: Account
 File: TestAccount.java  }  //
 //  void withdraw(float amt) Creating a test class to de
Java Program to demonstr { posit and withdraw amoun
ate the working of a banki t
 if(amount<amt){
ng-system  class TestAccount{
 System.out.println("Insuffi
 class Account{ cient Balance");
 public static void main(S
 int acc_no; tring[] args){
 }else{
 String name;
 Account a1=new Account(
 amount=amount-amt; );
 float amount;  System.out.println(amt+"  a1.insert(832345,"Ankit",1
 void insert(int a,String n,f withdrawn"); 000);
loat amt){  }  a1.display();
 acc_no=a;  }  a1.checkBalance();
 name=n;  void checkBalance()  a1.deposit(40000);
 amount=amt; {System.out.println("Bala
nce is: "+amount);}
 a1.checkBalance();
 }
 a1.withdraw(15000);
 void deposit(float amt)
 void display()
{ {System.out.println(acc_n  a1.checkBalance();
o+" "+name+" "+amount) }}
 amount=amount+amt; ;}
 System.out.println(amt+"  }
132
deposited");
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.

133
ArrayOfObjects.java
 public class ArrayOfObjects  //  class Product
 { display the product object data  {
 public static void main(String
 System.out.println("Product Obje int pro_Id;
args[]) ct 1:");
 String pro_name;
 {
 obj[0].display();
 //Product class constructor
 //
 System.out.println("Product Obje
ct 2:");
 Product(int pid, String n)
create an array of product object
 obj[1].display();
 {
 Product[] obj = new Product[5] ;  System.out.println("Product Obje
 pro_Id = pid;
ct 3:");  pro_name = n;
 //  obj[2].display();  }
create & initialize actual product  System.out.println("Product Obje public void display()
objects using constructor ct 4:");  {
 obj[0] = new Product(23907,"D  obj[3].display();
ell Laptop");
 System.out.print("Product Id = "
 System.out.println("Product Obje +pro_Id + " " + " Product Name
 obj[1] = new Product(91240,"HP ct 5:"); = "+pro_name);
630");
 obj[4].display();  System.out.println();
 obj[2] = new Product(29823,"LG
OLED TV");
 }  }
 obj[3] = new Product(11908,"MI
 }  }
Note Pro Max 9");  //
 obj[4] = new Product(43590,"Ki Product class with product Id an
ngston USB"); d product name as attributes

134
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.
135
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:
 Default
constructor (no-arg constructor)
 Parameterized constructor
136
 Java Default Constructor
 A constructor is called "Default Constructor"
when it doesn't have any parameter.
 Syntax of default constructor:
 <class_name>()
 {
 }

137
Example of default constructor
 //
Java Program to create and call a default construct
or
 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();
 }
 }
138
139
Example of default constructor that displays the
default values
 class Student3  Student3 s1=new Student
 { 3();
 int id;  Student3 s2=new Student
3();
 String name;
 s1.display();
 s2.display();
 void display()
 }
 {
 }
 System.out.println(id+" "+
name); }
 public static void main(St
ring args[])
 {

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

141
Example of parameterized constructor
 class Student4
 {  }
 int id;  public static void main(S
 String name; tring args[])
 Student4(int i,String n)  {
 {  Student4 s1 = new Stude
nt4(111,"Karan");
 id = i;
 Student4 s2 = new Stude
 name = n;
nt4(222,"Aryan");
 }  s1.display();
 void display()  s2.display();
 {  }
 System.out.println(id+" "+ 
}
name);
142
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.

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

144
 class Student6 void display()
 { {System.out.println(id+" "+na
me);}
 int id;
public static void main(String
 String name;
args[]){
 Student6(int i,String n){
Student6 s1 = new Student6(1
 id = i; 11,"Karan");
 name = n; Student6 s2 = new Student6(s
 } 1);
 Student6(Student6 s) s1.display();
 { s2.display();
 id = s.id; }
 name =s.name; }
}
145
 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.
146
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

147
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).
148
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.
149
150
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.

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

152
 //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();
 }
 }
153
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.

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

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

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

158
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

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

160
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
161 instance from the method.
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);}
 }

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

164
 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();
 }}
165
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);
 }}

166
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();
 }}
167
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.
168
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 garbag
e collection
169
 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(){}

170
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();
 }
 }
171
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
 }
 }
172
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.

173
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

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

175
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();
 }
 }
176
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();
 }
 }
177
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.

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

179
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();
 }

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

181
 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{
 ...
 }
 }

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

183
 The java.lang.String class
implements Serializable, Comparable and CharSequence interface
s.

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

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

185
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

186
187
 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).

188
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);
 }}
189
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 the
s) sequence of char value.

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

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

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

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

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

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

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

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

198
End of I Unit

199

You might also like