0% found this document useful (0 votes)
26 views153 pages

Java Object-Oriented Programming Syllabus

The document outlines a syllabus for a course on Object-Oriented Programming (OOP) using Java, covering fundamentals, classes and objects, multithreading, exception handling, file handling, and GUI programming. It emphasizes the principles of OOP such as encapsulation, inheritance, and polymorphism, while also discussing the advantages and disadvantages of OOP. Additionally, it highlights various applications of OOP in real-world scenarios and provides reference books for further reading.

Uploaded by

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

Java Object-Oriented Programming Syllabus

The document outlines a syllabus for a course on Object-Oriented Programming (OOP) using Java, covering fundamentals, classes and objects, multithreading, exception handling, file handling, and GUI programming. It emphasizes the principles of OOP such as encapsulation, inheritance, and polymorphism, while also discussing the advantages and disadvantages of OOP. Additionally, it highlights various applications of OOP in real-world scenarios and provides reference books for further reading.

Uploaded by

sahanasaana19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Syllabus:

UNIT 1
Fundamentals of Object-oriented Programming: 11 Hours
Object-oriented Paradigm, Basic Principles of Object-oriented Programming, Advantages of
Object-Oriented Programming, Applications of Object-Oriented Programming.
Introduction to Java Language:
Java History, Features, Overview, Difference between C, C+ + and Java, Java Environment-
JDK, JVM, JRE and API, Java Program Structure, Java Tokens, Implementing a Java
Program, Command Line Arguments.
Java Programming Fundamentals:
Data types, Variables & Constants, Keywords & Naming Conventions, Type Casting,
Operators and Expressions, Control Structures, Jumping Statements.
UNIT 2
Classes & Objects 11 Hours
Basics of Objects and Classes, Constructors, Access Modifiers, Method Overloading,
Overloading Constructors, Static members, this keyword.
Arrays: One dimensional Arrays, Two dimensional Arrays, Array of Objects.
Strings: String Handling functions.
UNIT 3
Multithreading in Java 11 Hours
Concepts of Thread, Thread Life Cycle, Creating Threads & Implementing Runnable
Interface, Thread Synchronization & Thread Priority.
Exception Handling
Concepts of Exception, Different Types of Exceptions, Creating User-Defined Exceptions
Using Try-Catch-Finally-Throw Blocks, Nested Try, Catch, Throw, and Throws Blocks.
UNIT 4
File Handling: I/O Handling , Types of Files, Byte Stream, Binary I/O Classes & Its 11 Hours
Hierarchy, File Input Stream & File Output Stream Classes, Object I/O Classes.
Event Handling & GUI programming: Event Handling, Event Types, Event Handling
Mechanism, Keyboard & Mouse Handling, Introduction to AWT & GUI basics, AWT
hierarchy of classes, AWT controls – Frames, Panels, Layout managers & other controls of
AWT.
Reference Books:
1. D.S. Guru, M.T. Somashekara, & K.S. Manjunatha, Object Oriented Programming with Java, PHI
Learning, 2017.
2. E Balagurusamy, Programming with JAVA, TMH, 2007
3. Herbert Schildt, Java 7, The Complete Reference, 8th Edition, 2009.
UNIT 1

Introduction to Java:
Java is a high-level programming language originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.
Java is used to develop mobile apps, desktop apps, web apps, web servers, games, and enterprise-level
systems
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread
popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for
Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java
EE, and Java ME respectively. JDK 23 is the latest version of Java.
Java is guaranteed to be Write Once, Run Anywhere. Popular platforms like LinkedIn,
Amazon, and Netflix rely on Java for their back-end architecture, showcasing its stability and scalability across
different environments.

Fundamentals of Object-oriented Programming


Object-oriented programming (OOP) is a fundamental programming paradigm based on the concept of _
“objects” _. These objects can contain data in the form of fields (often known as attributes or properties) and
code in the form of procedures (often known as methods).
The core concept of the object-oriented approach is to break complex problems into smaller objects.
Simula and Smalltalk are considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object is known as truly object-oriented programming
language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology
or paradigm to design a program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object-oriented Paradigm
A paradigm is a fundamental model, pattern, or approach that defines the way something is structured or
performed. It provides a framework for thinking, working, or solving problems in a particular domain.
Object-Oriented Paradigm (OOP)
The Object-Oriented Paradigm (OOP) is a programming paradigm that focuses on organizing code using
objects and classes rather than functions and logic. It provides a structured way of designing and implementing
software systems by modeling real-world entities as objects.

Imperative Language
The programmers instruct the machine to perform a task by writing step-by-step instructions including
variables, conditions, loops etc.

Procedural Oriented
Procedural language breaks down a task into a collection of procedures(aka. subroutines, functions) to
perform a task. It maintains global variables to manage the state of the system. C, BASIC, and ALGOL
etc belong to the procedural-oriented paradigm.
Object Oriented
Object Oriented language breaks down a task into objects that expose behaviour(method) and data
(member or attribute), objects communicate with each other through message-passing techniques to
accomplish a given task. C++, Java, C#, Kotlin etc belong to the object-oriented paradigm

Declarative Language
The programmers instruct the machine What to perform without any instructions. The programmer asks for
the desired result.
Functional
Functional programming contains only functions without mutating the state or data. It means that there
are no global data/variables. Composing and applying function is the main driving force in this
paradigm. A function can take another as an argument and return a new function.
Logical
The Logical paradigm has its foundations in mathematical logic in which program statements express
facts and rules. Rules are written as logical clauses. The engine infers the answer to the user’s query
by using unification and backtracking techniques.

Basic Principles of Object-Oriented Programming

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

Class
Collection of objects is called class. It is a logical entity. 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

Data Abstraction:
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:
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.

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.

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

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.

Association
An association is a relationship between two distinct classes that are established with the aid of their objects.
One-to-one, one-to-many, many-to-one, and many-to-many associations are all possible. An association is a
connection between two things. The diversity between objects is defined by one of Java’s OOP concepts.

Aggregation
In this method, each object has a distinct lifecycle. Ownership, however, prevents the child object from being
a part of another parent object. Java aggregation depicts the link between an object that contains other objects
and is a weak association. This illustrates the connection between a component and a whole, where a part can
exist without a whole.

Composition
Composition is an association that depicts a relationship between a part and a whole in which a part cannot
exist without a whole.

Constructors and methods


A constructor is a specific kind of subroutine called to create an object. It sets up the new object for use and
frequently accepts arguments from the constructor to set up necessary member variables. In OOP, a method
is a procedure connected to a message and an object. An object’s state data and behaviour make up its interface,
which describes how any of its numerous consumers may use it. A method is a consumer-parameterized object
activity.
Why do we need object-oriented programming?

• To make the development and maintenance of projects more effortless.


• To provide the feature of data hiding that is good for security concerns.
• We can solve real-world problems if we are using object-oriented programming.
• It ensures code reusability.
• It lets us write generic code: which will work with a range of data, so we don’t have to write basic stuff
over and over again.

Advantages of Object-Oriented Programming


1. Modularity and Code Reusability
OOP encourages modular design by breaking down a system into smaller, manageable pieces (classes and
objects).
Code can be reused across applications through inheritance and polymorphism, reducing development time
and effort.
Example: A class like Vehicle can be reused and extended to create Car, Bike, or Truck classes.

2. Improved Code Maintainability


Encapsulation allows for changes in one part of the program without affecting other parts.
Clearly defined interfaces and modularity make debugging, testing, and updating the code more manageable.

3. Data Security and Integrity


By encapsulating data within classes and controlling access through methods (getters/setters), OOP ensures
that only authorized parts of the program can modify or access critical data.
This reduces the likelihood of errors caused by unintended modifications.
Example: Private fields in a class ensure sensitive information is hidden from external code.

4. Faster Development Through Abstraction


Abstraction hides complex implementation details, allowing developers to focus on solving specific problems
rather than worrying about lower-level details.
Abstract classes and interfaces provide a blueprint for creating objects.

5. Scalability and Flexibility


OOP makes it easier to scale applications by adding new features or modifying existing ones without affecting
the overall structure.
Polymorphism allows methods to adapt based on the context, enabling flexible code.
Example: In a banking system, you can add a new account type (e.g., Savings Account) without modifying
the base Account class.

6. Enhanced Collaboration in Teams


By clearly defining class responsibilities, OOP makes it easier for team members to work on different parts
of a system independently.
For example, one developer can focus on designing a Payment Processor class while another works on
Transaction.
7. Real-World Modelling
OOP concepts like classes and objects closely mirror real-world entities, making it easier to design systems
that are intuitive and aligned with real-world scenarios.
For example, a Car class might have attributes like speed and colour, and methods like accelerate() or brake().

8. Improved Productivity
Reusable code, modular design, and abstraction lead to faster development cycles and reduced development
costs.
Libraries and frameworks based on OOP (e.g., Java libraries, .NET frameworks) provide ready-to-use
components.

9. Easier Debugging
With modular code and encapsulation, errors are isolated to specific classes or methods, making it easier to
identify and fix bugs.

10. Support for Advanced Features


OOP supports advanced programming features like multithreading, event-driven programming, and graphical
user interfaces (GUIs).
Languages like Java, C++, Python, and C# leverage OOP for powerful application development.

Disadvantages

• OOP can introduce unnecessary complexity for small or simple programs, as defining classes, objects,
and relationships may feel excessive for straightforward tasks.

• OOP systems often require more memory and processing power due to features like dynamic dispatch,
inheritance hierarchies, and the creation of multiple objects.
• or small or quick applications, the setup required for creating classes, objects, and hierarchies can slow
down development compared to procedural programming.

Applications of Object-Oriented Programming

• Real-Time System design: Real-time system inherits complexities and makes it difficult to build
them. OOP techniques make it easier to handle those complexities.

• Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored, searched, and
edited easily. Hypermedia on the other hand is a superset of hypertext. OOP also helps in laying the
framework for hypertext and hypermedia.

• AI Expert System: These are computer application that is developed to solve complex problems
which are far beyond the human brain. OOP helps to develop such an AI expert System

• Office automation System: These include formal as well as informal electronic systems that primarily
concerned with information sharing and communication to and from people inside and outside the
organization. OOP also help in making office automation principle.

• Neural networking and parallel programming: It addresses the problem of prediction and
approximation of complex-time varying systems. OOP simplifies the entire process by simplifying the
approximation and prediction ability of the neural networking.

• Stimulation and modeling system: It is difficult to model complex systems due to varying
specifications of variables. Stimulating complex systems require modeling and understanding
interaction explicitly. OOP provides an appropriate approach for simplifying these complex models.

• Object-oriented database: The databases try to maintain a direct correspondence between the real
world and database object in order to let the object retain it identity and integrity.

• Client-server system: Object-oriented client-server system provides the IT infrastructure creating


object-oriented server internet (OCSI) applications.

• CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing applications as it
allows people to reduce the efforts involved. For instance, it can be used while designing blueprints
and flowcharts. So, it makes it possible to produce these flowcharts and blueprint accurately.
Introduction to Java Language

Java is a class-based, object-oriented programming language that is designed to have as few


implementation dependencies as possible. It is intended to let application developers Write Once and Run
Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the
need for recompilation. Java was developed by James Gosling at Sun Microsystems Inc. in May
1995 and later acquired by Oracle Corporation and is widely used for developing applications for desktop,
web, and mobile devices.

Java is known for its simplicity, robustness, and security features, making it a popular choice for enterprise-
level applications. Java applications are compiled to byte code that can run on any Java Virtual Machine. The
syntax of Java is similar to C/C++.

Java history
James Gosling and his team initially named their project "Greentalk" (.gt), later renaming it "Oak" after an
oak tree outside Gosling's office, symbolizing strength and being the national tree of several nations. However,
due to a trademark conflict with Oak Technologies, it was renamed "Java," inspired by coffee beans, during a
brainstorming session. Created to be robust, portable, platform-independent, and high-performance, Java was
recognized as one of TIME Magazine's Ten Best Products of 1995. Over time, it evolved from JDK 1.0 with
a few hundred classes to over 3,000 classes in J2SE 5, becoming vital in programming, mobile apps, and e-
business.

Version Release Date Major changes

JDK Beta 1995 ----


Version Release Date Major changes

The Very first version was released on January 23, 1996. The
JDK 1.0 January 1996
principal stable variant, JDK 1.0.2, is called Java 1.

Was released on February 19, 1997. There were many


additions in JDK 1.1 as compared to version 1.0 such as
• A broad retooling of the AWT occasion show
JDK 1.1 February 1997 • Inner classes added to the language
• JavaBeans
• JDBC
• RMI

“Play area” was the codename which was given to this form
and was released on 8th December 1998. Its real expansion
included: strictfp keyword
• the Swing graphical API was coordinated into the
centre classes
J2SE 1.2 December 1998
• Sun’s JVM was outfitted with a JIT compiler out of
the blue
• Java module
• Java IDL, an IDL usage for CORBA interoperability
• Collections system

Codename- “KESTREL” Release Date- 8th May 2000


Additions:
• HotSpot JVM included
J2SE 1.3 May 2000 • Java Naming and Directory Interface
• JPDA
• JavaSound
• Synthetic proxy classes

Codename- “Merlin” Release Date- 6th February 2002


Additions: Library improvements
• Regular expressions modelled after Perl regular
expressions
• The image I/O API for reading and writing images in
J2SE 1.4 February 2002 formats like JPEG and PNG
• Integrated XML parser and XSLT processor (JAXP)
(specified in JSR 5 and JSR 63)
• Preferences API ([Link])
Public Support and security updates for this version ended in
October 2008.
Version Release Date Major changes

Codename- “Tiger” Release Date- “30th September 2004”


Originally numbered as 1.5 which is still used as its internal
version. Added several new language features such as:
J2SE 5.0 September 2004 • for-each loop
• Generics
• Autoboxing
• Var-args

Codename- “Mustang” Released Date- 11th December 2006


Packaged with a database supervisor and encourages the
utilization of scripting languages with the JVM. Replaced the
name J2SE with java SE and dropped the .0 from the version
JAVA SE 6 December 2006 number. Additions:
• Upgrade of JAXB to version 2.0: Including integration
of a StAX parser.
• Support for pluggable annotations (JSR 269).
• JDBC 4.0 support (JSR 221)

Codename- “Dolphin” Release Date- 7th July 2011 Added


small language changes including strings in the switch. The
JVM was extended with support for dynamic languages.
JAVA SE 7 July 2011 Additions:
• Compressed 64-bit pointers.
• Binary Integer Literals.
• Upstream updates to XML and Unicode.

Released Date- 18th March 2014 Language level support for


JAVA SE 8 March 2014 lambda expressions and default methods and a new date and
time API inspired by Joda Time.

Release Date: 21st September 2017 Project Jigsaw: designing


and implementing a standard, a module system for the Java
JAVA SE 9 September 2017
SE platform, and to apply that system to the platform itself and
the JDK.

Released Date- 20th March Addition:


• Additional Unicode language-tag extensions
• Root certificates
JAVA SE 10 March 2018 • Thread-local handshakes
• Heap allocation on alternative memory devices
• Remove the native-header generation tool – javah.
• Consolidate the JDK forest into a single repository.
Version Release Date Major changes

Released Date- 25th September, 2018 Additions-


• Dynamic class-file constants
• Epsilon: a no-op garbage collector
• The local-variable syntax for lambda parameters
JAVA SE 11 September 2018
• Low-overhead heap profiling
• HTTP client (standard)
• Transport Layer Security (TLS) 1.3
• Flight recorder

Released Date- 19th March 2019 Additions-


• Shenandoah: A Low-Pause-Time Garbage Collector
(Experimental)
• Microbenchmark Suite
JAVA SE 12 March 2019
• Switch Expressions (Preview)
• JVM Constants API
• One AArch64 Port, Not Two
• Default CDS Archives

Released Date – 17th September 2019


Additions-
JAVA SE 13 September 2019 • Text Blocks (Multiline strings).
• Switch Expressions.
• Enhanced Thread-local handshakes.

Released Date – 17th March 2020


Additions-
JAVA SE 14 March 2020 • Records (new class type for data modeling).
• Pattern Matching for instance of.
• Helpful NullPointerExceptions.

Released Date – 15th September 2020


Additions-
JAVA SE 15 September 2020 • Sealed Classes.
• Hidden Classes.
• Foreign Function and Memory API (Incubator).

Released Date – 16th March 2021


Additions-
JAVA SE 16 March 2021 • Records (preview feature).
• Pattern Matching for switch (preview feature).
• Unix Domain Socket Channel (Incubator).
Version Release Date Major changes

Released Date – 14th September 2021


Additions-
• Sealed Classes (finalized).
JAVA SE 17 September 2021
• Pattern Matching for instanceof (finalized).
• Strong encapsulation of JDK internals by default.
• New macOS rendering pipeline.

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.

1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode generated by the
compiler. This byte code can run on any platform be it Windows, Linux, or macOS which means if we compile
a program on Windows, then we can run it on Linux and vice versa. Each operating system has a
different JVM, but the output produced by all the OS is the same after the execution of the byte code. That
is why we call java a platform-independent language.

2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing the program in the
terms of a collection of objects is a way of object-oriented programming, each of which represents an instance
of the class.
The four main concepts of Object-Oriented programming are:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It eliminates complex
features like pointers and multiple inheritances, making it easier to write, debug, and maintain code.

4. Robustness
Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into
checking errors as early as possible, that is why the java compiler is able to detect even those errors that are
not easy to detect by another programming language. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation.

5. Security
Java do not have pointers, so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound
Exception if we try to do so. That’s why several security flaws like stack corruption or buffer overflow are
impossible to exploit in Java. Also, java programs run in an environment that is independent of the OS
(operating system) environment which makes java programs more secure.

6. Distributed
We can create distributed applications using the java programming language. Remote Method Invocation and
Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily
distributed on one or more systems that are connected to each other through an internet connection.

7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a program. This feature
is particularly useful for applications that require high performance, such as games and real-time simulations.

8. Portability
As we know, java code written on one machine can be run on another machine. The platform-independent
feature of java in which its platform-independent bytecode can be taken to any platform for execution makes
java portable. WORA(Write Once Run Anywhere) makes java application to generates a ‘.class’ file that
corresponds to our applications(program) but contains code in binary format. It provides ease t architecture-
neutral ease as bytecode is not dependent on any machine architecture. It is the primary reason java is used in
the enterprising IT industry globally worldwide.
9. High Performance
Java architecture is defined in such a way that it reduces overhead during the runtime and at sometimes java
uses Just In Time (JIT) compiler where the compiler compiles code on-demand basis where it only compiles
those methods that are called making applications to execute faster.

Difference between C, C+ + and Java

Basis
[Link] C C++ Java

Origin The C language is The C++ language The Java


based on BCPL is based on the C programming
1 language. language is based
on both C and
C++.
Programming It is a procedural It is an object- It is a pure object-
Pattern language. oriented oriented
2
programming programming
language. language.
Approach It uses the top- It uses the bottom- It also uses the
3 down approach. up approach. bottom-up
approach.
Dynamic or Static It is a static It is also a static It is a dynamic
4 programming programming programming
language. language. language.
Code Execution The code is The code is The code is
5 executed directly. executed directly. executed by the
JVM.
Platform It is platform It is platform It is platform-
Dependency dependent. dependent. independent
6
because of byte
code
Translator It uses a compiler It also uses a Java uses both
only to translate compiler only to compiler and
7 the code into translate the code interpreter and it is
machine language. also known as an
into machine interpreted
language. language.
Source File The source file has The source file has The source file has
8
Extension a .c extension. a .cpp extension. a .java extension.
Pointer Concept It supports pointer. It also supports Java does not
pointer. support the pointer
9
concept because of
security.
It does not support It supports both It supports
Constructor/ constructor and constructor and constructors only
10 Destructor destructor. destructor.

Memory It uses the calloc(), It uses new and It uses a garbage


Management malloc(), free(), delete operator to collector to
11 and realloc() manage the manage the
methods to manage memory. memory.
the memory.
It is widely used to It is widely used It is used to
Used for develop drivers for system develop web
and operating programming. applications,
12 systems. mobile
applications, and
windows
applications.
Array Size An array should be An array should be An array can be
declared with size. declared with size. declared without
For example, int declaring the size.
13
num[10]. For example, int
num[].

Java Environment

JDK in Java
The Java Development Kit (JDK) is a cross-platformed software development environment that offers a
collection of tools and libraries necessary for developing Java-based software applications and applets. It is a
core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java Runtime
Environment).
JDK=JRE+Development Tools

Contents of JDK

The JDK has a private Java Virtual Machine (JVM) and a few other resources necessary for the development
of a Java Application.

JDK contains:

• Java Runtime Environment (JRE),

• An interpreter/loader (Java),

• A compiler (javac),

• An archiver (jar) and many more.

The Java Runtime Environment in JDK is usually called Private Runtime because it is separated from the
regular JRE and has extra content. The Private Runtime in JDK contains a JVM and all the class libraries
present in the production environment, as well as additional libraries useful to developers, e.g,
internationalization libraries and the IDL libraries.

Most Popular JDKs:

• Oracle JDK: the most popular JDK and the main distributor of Java11,

• OpenJDK: Ready for use: JDK 15, JDK 14, and JMC,

• Azul Systems Zing: efficient and low latency JDK for Linux os,
• Azul Systems: based Zulu brand for Linux, Windows, Mac OS X,

• IBM J9 JDK: for AIX, Linux, Windows, and many other OS,

• Amazon Corretto: the newest option with the no-cost build of OpenJDK and long-term support.

JVM Architecture
JVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls
the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java
code on one system and expect it to run on any other Java-enabled system without any adjustment. This is all
possible because of JVM.
When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file
are generated by the Java compiler. This .class file goes into various steps when we run it. These steps together
describe the whole JVM.

1) Class loader

Class loader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is
loaded first by the class loader. There are three built-in class loaders in Java.

1. Bootstrap Class Loader: This is the first class loader which is the super class of Extension class
loader. It loads the [Link] file which contains all class files of Java Standard Edition like [Link]
package classes, [Link] package classes, [Link] package classes, [Link] package classes, [Link]
package classes etc.

2. Extension Class Loader: This is the child class loader of Bootstrap and parent class loader of System
classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application Class Loader: This is the child class loader of Extension class loader. It loads
the classfiles from classpath. By default, classpath is set to current directory. You can change the
classpath using "-cp" or "-classpath" switch. It is also known as Application class loader.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains

1. A virtual processor

2. Interpreter: Read bytecode stream then execute the instructions.

3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output
to the Console or interact with OS libraries.

JAVA PACKAGES

Packages are Java’s way of grouping a variety of classes and / or interfaces together. The grouping isusually

done according to functionality. In fact, packages act as containers for classes.

Benefits:

• The classes contained in the packages of other programs can be easily reused.

• In packages, classes can be unique compared with classes in other packages. That is two classes

in two different packages can have the samename. They may be referred by their fully qualified

name, comprising thepackage name and the classname.

• Packages provide a way to “hide” classes thus preventing other programs or packages from

accessing classes that are meant for initernal use only.

• Packages also provide a way for separating “design” from “coding”. First we can design classes

and decide their relationships, and then we can implement the Java code needed for the

methods. It is possible to change the implementation of any method without affecting the rest

of the design.

JAVA API PACKAGES:

Java API provides a large number of classes grouped into different packages according to

[Link] of the time we use the packages available with the Java API. Table below shows the classes

that belongs to eachpackage.

requently used API packages

Package name

Contents

[Link]

Language support classes. These are classes that Java

compiler itself uses and therefore they are automatically


[Link] includeclasses for primitive types, strings,

math functions, threads

and exceptions.

[Link]

Language utility

classes

such

as

vectors,hash

tables,randomnumbers,date, etc.,

[Link]

Input/output support [Link] provide facilities for

the input

and output of data.

[Link]

Set of classes for implementing Graphical User

interface(GUI).

They include classes for windows,buttons, lists,menus

andsoon.

[Link]

Classes for [Link] include classes for

communicating with local computers as well as with

internet servers.

[Link]

Classes for creating and implementing applets.

Structure of Java Program


1. Documentation Section

The documentation section is an important section but optional for a Java program. It includes basic
information about a Java program. The information includes the author's name, date of creation, version,
program name, company name, and description of the program. It improves the readability of the program.
Whatever we write in the documentation section, the Java compiler ignores the statements during the execution
of the program. To write the statements in the documentation section, we use comments. The comments may
be single-line, multi-line, and documentation comments.

• Single-line Comment: It starts with a pair of forwarding slash (//). For example:

//First Java Program

• Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
For example:

/*It is an example of
multiline comment*/
• Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:

/**It is an example of documentation comment*/

2. The package declaration

The package declaration is optional. It is placed just after the documentation section. In this section, we declare
the package name in which the class is placed. Note that there can be only one package statement in a Java
program. It must be defined before any class and interface declaration. It is necessary because a Java class can
be placed in different packages and directories based on the module they are used. For all these classes package
belongs to a single parent directory. We use the keyword package to declare the package name. For example:

package javatpoint; //where javatpoint is the package name

package [Link]; //where com is the root directory and javatpoint is the subdirectory

3. Import Statements

The package contains the many predefined classes and interfaces. To use any class of a particular package,
we need to import that class. The import statement represents the class stored in the other package. We use
the import keyword to import the class. It is written before the class declaration and after the package
statement. We use the import statement in two ways, either import a specific class or import all classes of a
particular package. In a Java program, we can use multiple import statements. For example:

• import [Link]; //it imports the Scanner class only


• import [Link].*; //it imports all the class of the [Link] package

4. Interface Section
It is an optional section. We can create an interface in this section if required. We use the interface keyword
to create an interface. An interface is a slightly different from the class. It contains
only constants and method declarations. Another difference is that it cannot be instantiated. We can use
interface in classes by using the implements keyword. An interface can also be used with other interfaces by
using the extends keyword.

For example:

interface car

void start();

void stop();

5. Class Definition

In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any
Java program. A Java program may conation more than one class definition. We use the class keyword to
define the class. The class is a blueprint of a Java program. It contains information about user-defined methods,
variables, and constants. Every Java program has at least one class that contains the main() method.
For example:

class Student //class definition

6. Class Variables and Constants

In this section, we define variables and constants that are to be used later in the program. In a Java program,
the variables and constants are defined just after the class definition. The variables and constants store values
of the parameters. It is used during the execution of the program. We can also decide and define the scope of
variables by using the modifiers. It defines the life of the variables.

For example:

class Student //class definition

String sname; //variable

int id;

double percentage;

7. Main Method Class

In this section, we define the main() method. It is essential for all Java programs. Because the execution of
all Java programs starts from the main() method. In other words, it is an entry point of the class. It must be
inside the class. Inside the main method, we create objects and call the methods. We use the following
statement to define the main() method:

public static void main(String args[])

Example:

public class Student //class definition


{

public static void main(String args[])

//statements

8. Methods and behavior


In this section, we define the functionality of the program by using the methods. The methods are the set of
instructions that we want to perform. These instructions execute at runtime and perform the specified task.
For example:
public class Demo //class definition
{
public static void main(String args[])
{
void display()
{
[Link]("Welcome to javatpoint");
}
//statements
}
}

Example of Java program


Simple Java Program
import [Link].*;
public class Welcome
{
public static void main (String args[])
{
[Link] (“welcome to Java Program”);
}
}
• public: It is access specifier and this method can be called from outside also.
• static: This main method must always declared as static because the whole program has
only one main method and without using object the main method can be executed by
using the class name.
• void: The main method does not return anything.
• main: - The main method similar to main function in c and c++. This main method call
first (execute first) by the interpreter to run the java program.
• String: It is built-in class under language package.
• args []: This is an array of type string. a command line argument holds the argument
in this array. [Link]:
• System: It is a class which contains several useful methods.
• out: It is an object for a system class to execute the method.
• println: This is a method to print string which can be given within the double coats.
After printed the contents the cursor should be positioned at beginning of next line
• print: after printed the content the cursor should be positioned next to the printed content.

Java Tokens
A token in Java is a sequence of characters that represents a single element of a program. They are also
known as the fundamental building blocks of the program. Tokens can be classified as follows:

1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators

1. Keyword
Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform
a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as
variable names because by doing so, we are trying to assign a new meaning to the keyword which is not
allowed.
There are a total of 53 keywords in Java.

keyword Descriptions
byte A data type that can store whole numbers from -128 and 127

Declares a variable. New in Java 10


var

int A data type that can store whole numbers from -2147483648 to 2147483647

float A data type that can store fractional numbers from 3.4e−038 to 3.4e+038

double A data type that can store fractional numbers from 1.7e−308 to 1.7e+308

Char A data type that is used to store a single character

else Used in conditional statements


if Makes a conditional statement

while Used together with while to create a do-while loop

do Used together with while to create a do-while loop

Char A data type that is used to store a single character

Boolean A data type that can only store true or false values

A non-access modifier used for classes, attributes and methods, which makes
final
them non-changeable (impossible to inherit or override)

class Defines a class

break Breaks out of a loop or a switch block

2. Identifiers

Identifiers are used as the general terminology for naming of variables, functions and arrays. These are user-
defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the
underscore (_) as a first character. Identifier names must differ in spelling and case from any keywords.
keywords cannot be used as identifiers; they are reserved for special use. Once declared, can use the identifier
in later program statements to refer to the associated value.

Rules For Naming Java Identifiers

There are certain rules for defining a valid Java identifier. These rules must be followed, otherwise, we get a
compile-time error. These rules are also valid for other languages like C, and C++.

• The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]),
‘$‘(dollar sign) and ‘_‘ (underscore). For example “geek@” is not a valid Java identifier as it contains
a ‘@’ a special character.
• Identifiers should not start with digits([0-9]). For example “123geeks” is not a valid Java identifier.

• Java identifiers are case-sensitive.

• There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15
letters only.

• Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement
as a while is a reserved word. There are 53 reserved words in Java.

Examples of Valid Identifiers:

MyVariable
MYVARIABLE
myvariable
x

_myvariable
$myvariable
sum_of_array
geeks123

Examples of Invalid Identifiers:


My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric characte

3. Constants/Literals

Constants are also like normal variables. But the only difference is, their values cannot be modified by the
program once they are defined. Constants refer to fixed values. They are also called as literals. In programming
literal is a notation that represents a fixed value (constant) in the source code. It can be categorized as an
integer literal, string literal, Boolean literal, etc. It is defined by the programmer. Once it has been defined
cannot be changed Constants may belong to any of the data type.

Syntax:

final data_type variable_name;

4. Operators
Java provides many types of operators which can be used according to the need. They are classified based on
the functionality they provide. Some of the types are-

• Arithmetic Operators

• Unary Operators

• Assignment Operator

• Relational Operators

• Logical Operators

• Ternary Operators

• Bitwise Operators

• Shift Operators

• instance of operator

• Precedence and Associativity

5. Separators
Separators are used to separate different parts of the codes. It tells the compiler about completion of a
statement in the program. The most commonly and frequently used separator in java is semicolon (;).
The separators in Java is also known as punctuators. There are nine separators in

Java, are as follows:

• Square Brackets []: It is used to define array elements. A pair of square brackets

• represents the single-dimensional array, two pairs of square brackets represent the

• two-dimensional array.

• Parentheses (): It is used to call the functions and parsing the parameters.

• Curly Braces {}: The curly braces denote the starting and ending of a code block.

• Comma (,): It is used to separate two values, statements, and parameters.

• Assignment Operator (=): It is used to assign a variable and constant.

• Semicolon (;): It is the symbol that can be found at end of the statements. It

• separates the two statements.

• Period (.): It separates the package name form the sub-packages and class. It also
• separates a variable or method from a reference variable.
Example:
int variable; //here the semicolon (;) ends the declaration of the variable

Command Line Arguments


Command-line arguments in Java allow you to pass information to a program when it is executed. These
arguments are passed as strings and can be accessed in the main method through the String[] args parameter.

Here’s an example program demonstrating how to use command-line arguments in Java:

// [Link]

public class CommandLineArgumentsExample

public static void main(String[] args)

// Check if any arguments are passed

if ([Link] == 0)

[Link]("No command-line arguments provided!");

else

[Link]("Command-line arguments are:");

// Loop through and print all arguments

for (int i = 0; i < [Link]; i++)

[Link]("Argument " + (i + 1) + ": " + args[i]);

}
}

How to Run the Program

1. Save the code in a file named [Link].

2. Compile the program using:

• javac [Link]
3. Run the program with command-line arguments:
java CommandLineArgumentsExample arg1 arg2 arg3

Example Output
For the command:
java CommandLineArgumentsExample Hello World Java
The output will be:
Command-line arguments are:
Argument 1: Hello
Argument 2: World
Argument 3: Java
Explanation
• [Link]: Returns the number of arguments passed.
• args[i]: Accesses the ith argument (starting from 0).
• If no arguments are provided, the program informs the user that no arguments were passed.

Java Programming Fundamentals

Data Types

Data types in Java are of different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases.

Java is statically typed and also a strongly typed language because, in Java, each type of data (such as integer,
character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and
all constants or variables defined for a given program must be described with one of the Java data types.

Java has two categories in which data types are segregated


1. Primitive Data Type: such as Boolean, char, int, short, byte, long, float, and double. The Boolean
with uppercase B is a wrapper class for the primitive data type Boolean in Java.

2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

// Java Program to demonstrate int data-type

import [Link].*;

class GFG

public static void main (String[] args)

// declaring two int variables

int a = 10;

int b = 20;

[Link]( a + b );

Output

30
Primitive Data Types in Java

Primitive data are only single values and have no special capabilities. There are 8 primitive data types. They
are depicted below in tabular format below as follows:
Primitive Data Types
1. Boolean Data Type
The Boolean data type represents a logical value that can be either true or false. Conceptually, it represents a
single bit of information, but the actual size used by the virtual machine is implementation-dependent and
typically at least one byte (eight bits) in practice. Values of the Boolean type are not implicitly or explicitly
converted to any other type using casts. However, programmers can write conversion code if needed.

Syntax:

boolean booleanVar;

Example:

Boolean one = false;

2. Byte Data Type

The Byte data type is an 8-bit signed two’s complement integer. The Byte data type is useful for saving
memory in large arrays.

Syntax:

byte byteVar;

Example:

byte a = 10, byte b = -20 ;

3. Short Data Type

The short data type is a 16-bit signed two’s complement integer. Similar to byte, a short is used when
memory savings matter, especially in large arrays where space is constrained.

Syntax:

short shortVar;

short myNum = 5000;

[Link](myNum);

Example:

short s = 10000, short r = -5000 ;

4. int Data Type


The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.

Syntax:

int intVar;

int myNum = 100000;

[Link](myNum);

5. long Data Type

The long data type is a 64-bit signed two’s complement integer. It is used when an int is not large enough to
hold a value, offering a much broader range.

Syntax:

long longVar;

long myNum = 15000000000L;

[Link](myNum);

6. Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you
need to save memory in large arrays of floating-point numbers. The size of the float data type is 4 bytes (32
bits).

Syntax:

float floatVar;

float myNum = 5.75f;

[Link](myNum);

7. Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type
is generally the default choice. The size of the double data type is 8 bytes or 64 bits.

Syntax: double doubleVar;

double myNum = 19.99d;

[Link](myNum);
8. char Data Type

The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).

Syntax:

char charVar;

Non-Primitive (Reference) Data Types


The Non-Primitive (Reference) Data Types will contain a memory address of variable values because the
reference types won’t store the variable value directly in memory. They are strings, objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a character array and a string in Java is,
that the string is designed to hold a sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities. Unlike C/C++, Java strings are not terminated with a null character.

a. Syntax: Declaring a string


b. <String_Type> <string_variable> = “<sequence_of_string>”;
2. Array

An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java work
differently than they do in C/C++. The following are some important points about Java arrays.

• In Java, all arrays are dynamically allocated. (discussed below)

• Since arrays are objects in Java, we can find their length using member length. This is different from
C/C++ where we find length using size.

• A Java array variable can also be declared like other variables with [] after the data type.

• The variables in the array are ordered and each has an index beginning with 0.

• Java array can also be used as a static field, a local variable, or a method parameter.

• The size of an array must be specified by an int value and not long or short.

• The direct superclass of an array type is Object.

Interface

Like a class, an interface can have methods and variables, but the methods declared in an interface are by
default abstract (only method signature, no body).

• Interfaces specify what a class must do and not how. It is the blueprint of the class.
• An Interface is about capabilities like a Player may be an interface and any class implementing
Player must be able to (or must implement) move(). So it specifies a set of methods that the class has
to implement.

Variables & Constants


Variables
Variables are the containers for storing the data values or can also call it a memory location name for the data.
A variable is a container that holds data which can change during program execution.

Declaration Syntax:

dataType variableName = value; // e.g., int age = 25;


Declare Java Variables

1. datatype: In Java, a data type define the type of data that a variable can hold.
2. data_name: Name was given to the variable.
Every variable has a:
• Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
• Variable Name – To identify the variable uniquely within the scope.
• Value – The data assigned to the variable.
Types of Java Variables

1. Local Variables
• The Local variable is created at the time of declaration and destroyed after exiting from the block or
when the call returns from the function.

• The scope of these variables exists only within the block in which the variables are declared, i.e., we
can access these variables only within that block.

• Initialization of the local variable is mandatory before using it in the defined scope.

Example
// Java Program to show the use of local variables
import [Link].*;
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


[Link]("Local Variable: " + var);
}
}
Output :10
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any method, constructor, or
block.

• As instance variables are declared in a class, these variables are created when an object of the class is
created and destroyed when the object is destroyed.

• Unlike local variables, we may use access specifiers for instance variables. If we do not specify any
access specifier, then the default access specifier will be used.

• Initialization of an instance variable is not mandatory. Its default value is dependent on the data type
of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it
is null, etc.

• Scope of instance variables are throughout the class except the static contexts.

Example
// Instance Variables
import [Link].*;
class GFG {
// Declared Instance Variable
public String geek;
public int i;
public Integer I;
public GFG()
{
// Default Constructor
// initializing Instance Variable
[Link] = "Shubham Jain";
}
// Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();
// Displaying O/P
[Link]("Geek name is: " + [Link]);
[Link]("Default value for int is "+ name.i);
// toString() called internally
[Link]("Default value for Integer is "+ name.I);
}
}
Output:
Geek name is: Shubham Jain
Default value for int is 0
Default value for Integer is null
3. Static Variables
Static variables are also known as class variables.

• These variables are declared similarly to instance variables. The difference is that static variables are
declared using the static keyword within a class outside of any method, constructor, or block. Unlike
instance variables, we can only have one copy of a static variable per class, irrespective of how many
objects we create.

• Static variables are created at the start of program execution and destroyed automatically when
execution ends.

• Initialization of a static variable is not mandatory. Its default value is dependent on the data type of
variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it
is null, etc. If we access a static variable like an instance variable (through an object), the compiler will
show a warning message, which won’t halt the program. The compiler will replace the object name
with the class name automatically.

Example:
// Java Program to show the use of
// Static variables
import [Link].*;
class GFG {
// Declared static variable
public static String geek = "Shubham Jain";
public static void main(String[] args)
{
// geek variable can be accessed without object
// creation Displaying O/P [Link] --> using the
// static variable
[Link]("Geek Name is : " + [Link]);

// static int c = 0;
// above line, when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50; //instance variable
}
}//end of class

Constants
A constant is a variable whose value cannot change after initialization. Constants in Java are declared using
the final keyword.
Declaration Syntax:
final dataType CONSTANT_NAME = value; // e.g., final int MAX_AGE = 100;
Characteristics of Constants:
• The value must be assigned at the time of declaration or in a constructor.
• By convention, constant names are written in uppercase with underscores separating words.
Example:
public class ConstantsExample {
// Declaring constants using `final`
public static final double PI = 3.14159; // Constant for Pi
public static final int MAX_AGE = 100; // Maximum age constant

public static void main(String[] args) {


// Using constants in a program
double radius = 5.0; // Radius of a circle
double area = PI * radius * radius; // Calculate area using the constant PI

[Link]("The radius of the circle is: " + radius);


[Link]("The area of the circle is: " + area);

// Printing another constant


[Link]("The maximum age allowed is: " + MAX_AGE);
}
}

Output:
The radius of the circle is: 5.0
The area of the circle is: 78.53975
The maximum age allowed is: 100

Keywords in java
Java has a set of keywords that are reserved words that cannot be used as variables, methods, classes, or any
other identifiers:

Keyword Description

abstract A non-access modifier. Used for classes and methods: An abstract class
cannot be used to create objects (to access it, it must be inherited from
another class). An abstract method can only be used in an abstract class,
and it does not have a body. The body is provided by the subclass (inherited
from)

assert For debugging

boolean A data type that can only store true or false values

break Breaks out of a loop or a switch block

byte A data type that can store whole numbers from -128 and 127

case Marks a block of code in switch statements

catch Catches exceptions generated by try statements

char A data type that is used to store a single character

class Defines a class

continue Continues to the next iteration of a loop

const Defines a constant. Not in use - use final instead

default Specifies the default block of code in a switch statement

do Used together with while to create a do-while loop

double A data type that can store fractional numbers from 1.7e−308 to 1.7e+308

else Used in conditional statements


enum Declares an enumerated (unchangeable) type

exports Exports a package with a module. New in Java 9

extends Extends a class (indicates that a class is inherited from another class)

final A non-access modifier used for classes, attributes and methods, which
makes them non-changeable (impossible to inherit or override)

finally Used with exceptions, a block of code that will be executed no matter if there
is an exception or not

float A data type that can store fractional numbers from 3.4e−038 to 3.4e+038

for Create a for loop

goto Not in use, and has no function

if Makes a conditional statement

implements Implements an interface

import Used to import a package, class or interface

instanceof Checks whether an object is an instance of a specific class or an interface

int A data type that can store whole numbers from -2147483648 to
2147483647

interface Used to declare a special type of class that only contains abstract methods

long A data type that can store whole numbers from -9223372036854775808 to
9223372036854775808

module Declares a module. New in Java 9

native Specifies that a method is not implemented in the same Java source file (but
in another language)

new Creates new objects

package Declares a package

private An access modifier used for attributes, methods and constructors, making
them only accessible within the declared class

protected An access modifier used for attributes, methods and constructors, making
them accessible in the same package and subclasses

public An access modifier used for classes, attributes, methods and constructors,
making them accessible by any other class
requires Specifies required libraries inside a module. New in Java 9

return Finished the execution of a method, and can be used to return a value from
a method

short A data type that can store whole numbers from -32768 to 32767

static A non-access modifier used for methods and attributes. Static


methods/attributes can be accessed without creating an object of a class

strictfp Obsolete. Restrict the precision and rounding of floating point calculations

switch Selects one of many code blocks to be executed

synchronized A non-access modifier, which specifies that methods can only be accessed by
one thread at a time

this Refers to the current object in a method or constructor

throw Creates a custom error

throws Indicates what exceptions may be thrown by a method

transient Used to ignore an attribute when serializing an object

try Creates a try...catch statement

var Declares a variable. New in Java 10

void Specifies that a method should not have a return value


Java Naming Convention
Java naming convention is a rule to follow as you decide what to name identifiers such as class, package,
variable, constant, method, [Link], it is not forced to follow. So, it is known as convention not rule. These
conventions are suggested by several Java communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given according
to the Java naming convention.

Naming Conventions of the Different Identifiers

The following table shows the popular conventions used for the different identifiers.

Identifiers Type Naming Rules Examples

It should start with the uppercase


letter. public class Employee
It should be a noun such as Color, {
Class
Button, System, Thread, etc. //code snippet
Use appropriate words, instead of }
acronyms.

It should start with the uppercase


letter.
interface Printable
It should be an adjective such as
{
Interface Runnable, Remote,
//code snippet
ActionListener.
}
Use appropriate words, instead of
acronyms.

It should start with lowercase class Employee


letter. {
It should be a verb such as // method
main(), print(), println(). void draw()
Method
If the name contains multiple {
words, start it with a lowercase //code snippet
letter followed by an uppercase }
letter such as actionPerformed(). }
It should start with a lowercase
letter such as id, name.
It should not start with the special
characters like & (ampersand), $ class Employee
(dollar), _ (underscore). {
If the name contains multiple // variable
Variable
words, start it with the lowercase int id;
letter followed by an uppercase //code snippet
letter such as firstName, }
lastName.
Avoid using one-character
variables such as x, y, z.

It should be a lowercase letter //package


such as java, lang. package [Link];
If the name contains multiple class Employee
Package
words, it should be separated by {
dots (.) such as [Link], //code snippet
[Link]. }

class Employee
{
//constant
It should be in uppercase letters static final int MIN_AGE = 18;
such as RED, YELLOW. //code snippet
If the name contains multiple }
words, it should be separated by
Constant
an underscore(_) such as
MAX_PRIORITY.
It may contain digits but not as
the first letter.

CamelCase in Java naming conventions

Java follows camel-case syntax for naming the class, interface, method, and variable.

If the name is combined with two words, the second word will start with uppercase letter always such as
actionPerformed(), firstName, ActionEvent, ActionListener, etc.

Typecasting in Java

Typecasting in Java is the process of converting one data type to another data type using the casting
operator. When a valueis assigned from one primitive data type to another type, this is known as type
casting. To enable the use of a variable in a specific manner, this method requires explicitly instructing the
Java compiler to treat a variable of one data type as a variable of another data type.

Syntax: <datatype> variableName = (<datatype>) value;


Types of Type Casting
There are two types of Type Casting in java:
• Widening Type Casting
• Narrow Type Casting
Widening Type Casting

A lower data type is transformed into a higher one by a process known as widening type casting. Implicit
type casting and casting down are some names for it. It occurs naturally. Since there is no chance of data
loss, it is secure. Widening Type casting occurs when:

• The target type must be larger than the source type.


• Both data types must be compatible with each other.

Syntax:
larger_data_type variable_name = smaller_data_type_variable;

EXAMPLES
// Java program to demonstrate Widening TypeCasting
import [Link].*;
class GFG {
public static void main(String[] args)
{
int i = 10;
// Wideing TypeCasting (Automatic Casting)
// from int to long
long l = i;
// Wideing TypeCasting (Automatic Casting)
// from int to double
double d = i;
[Link]("Integer: " + i);
[Link]("Long: " + l);
[Link]("Double: " + d);
}
}
Output
Integer: 10
Long: 10
Double: 10.0

Narrow Type Casting

The process of downsizing a bigger data type into a smaller one is known as narrowing type casting. Casting
up or explicit type casting are other names for it. It doesn’t just happen by itself. If we don’t explicitly do that,
a compile-time error will occur. Narrowing type casting is unsafe because data loss might happen due to the
lower data type’s smaller range of permitted values. A cast operator assists in the process of explicit casting.

Syntax: smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

// Java Program to demonstrate Narrow type casting


import [Link].*;
class GFG {
public static void main(String[] args)
{
double i = 100.245;
// Narrowing Type Casting
short j = (short)i;
int k = (int)i;
[Link]("Original Value before Casting" + i);
[Link]("After Type Casting to short " + j);
[Link]("After Type Casting to int "+ k);
}
}

Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100

Explicit Upcasting
Upcasting is the process of casting a subtype to a supertype in the inheritance tree’s upward direction. When
a sub-class object is referenced by a superclass reference variable, an automatic process is triggered without
any further effort.

Example:
/ Java Program to demonstrate Narrow type casting
import [Link].*;
class GFG {
public static void main(String[] args)
{
double i = 100.245;

// Narrowing Type Casting


short j = (short)i;
int k = (int)i;
[Link]("Original Value before Casting" + i);
[Link]("After Type Casting to short " + j);
[Link]("After Type Casting to int " + k);
}
}

Types of Explicit Casting


Mainly there are two types of Explicit Casting:
• Explicit Upcasting
• Explicit Downcasting
Explicit Upcasting

Upcasting is the process of casting a subtype to a supertype in the inheritance tree’s upward direction. When
a sub-class object is referenced by a superclass reference variable, an automatic process is triggered without
any further effort.

Explicit Downcasting

When a subclass type refers to an object of the parent class, the process is referred to as downcasting. If it is
done manually, the compiler issues a runtime ClassCastException error. It can only be done by using the
instanceof operator. Only the downcast of an object that has already been upcast is possible.

Operators and Expressions


In programming, operators are the special symbol that tells the compiler to perform a special operation.
Java operators are special symbols that perform operations on variables or values. They can be classified
into several categories based on their functionality. These operators play a crucial role in performing
arithmetic, logical, relational, and bitwise operations etc.
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
• Arithmetic Operators: Arithmetic operators are used to perform common mathematical
operations.

• Unary operators: Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1.

• Assignment Operators: Assignment operators are used to assign values to variables.


• Relational Operators: Relational operators are used to check the relationship between two
operands.

• Logical Operators: Logical operators are used to determine the logic between variables or values.
• Ternary Operator : The ternary operator (conditional operator) is shorthand for the if-then-else
statement.
Syntax :- variable = Expression ? expression1 : expression2 ;
Here's how it works.
o If the Expression is true, expression1 is assigned to the variable.
o If the Expression is false, expression2 is assigned to the variable.

• Bitwise Operators :Bitwise operators in Java are used to perform operations on individual bits.

• Shift Operators: Shift Operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number by two, respectively.
o << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
o >> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with the leftmost bit
depending on the sign.
o >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always 0.

• instanceof operator: The instance of operator is used for type checking. It can be used to test if an
object is an instance of a class, a subclass, or an interface .

Expressions in java
Expression: An expression is a combination of operators, constants and variables. An expression may
consist of one or more operands, and zero or more operators to produce a value.
Types of Expression

• Constant expressions: Constant Expressions consists of only constant values. A constant value is
one that doesn’t change.
• Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
• Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
• Relational expressions: Relational Expressions yield results of type bool which takes a value true
or false.
• Logical expressions: Logical Expressions combine two or more relational expressions and
produces bool type results.
• Pointer expressions: Pointer Expressions produce address values.
• Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits.

Control Structures in java

Java compiler executes the code from top to bottom. The statements in the code are executed according to
the order in which they appear. However, Java provides statements that can be used to control the flow of
Java code. Such statements are called control flow statements.
Java provides three types of control flow statements.

1. Decision Making statements

o if statements

o switch statement

2. Loop statements

o do while loop

o while loop

o for loop

o for-each loop

3. Jump statements

o break statement

o continue statement

Decision-Making statements:-

As the name suggests, decision-making statements decide when and which statement to execute. Decision-
making statements evaluate the Boolean expression and control the program flow depending upon the result
of the condition provided.

If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending
upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In
Java, there are four types of if-statements

1. Simple if statement

2. if-else statement

3. if-else-if ladder

4. Nested if-statement
1) Simple if statement:-

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true

Example :

If statement program
public class Student
{
public static void main(String[] args)
{
int x =10;
int y = 12;
if(x+y>2)
{
[Link]("x + y is greater than 20");
}
}
}
2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
Else {
statement 2; //executes when condition is false
}

Example:

If-else Statement

public class Student


{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y<10)
{
[Link]("x + y is less than 10");
}
else
{
[Link]("x + y is greater than 10");}
}
}
}

• if-else-if ladder:-

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true.

Syntax of if-else-if statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Example:

If -else- if ladder
public class Student
{
public static void main(String[] args)
{
String city ="Delhi";
if(city == "Meerut")
{
[Link]("city is meerut");
}
else if (city == "Noida")
{
[Link]("city is noida");
}
else if(city == "Agra")
{
[Link]("city is agra");
}
else
{
[Link](city);
}
}

• Nested if-statement:

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.

Syntax of Nested if-statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true

if(condition 2) {

statement 2; //executes when condition 2 is true

Else {

statement 2; //executes when condition 2 is false

Example 1: nested if statemet

public class Test


{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
[Link]("X = 30 and Y = 10");
}
}
}
}
Example 2:- Nested if -else statement

public class Test


{
public static void main(String args[]) {
int x = 30;
int y = 10;
if( x < 30 )
{
[Link]("X < 30");
}
else
{
if( y > 9 )
{
[Link]("X > 30 and Y > 9");
}
}
}
Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
The syntax to use the switch statement is given below.

switch(expression)
{
case value1:
// Statements
break; // break is optional

case value2:
// Statements
break; // break is optional
....
....
....
default :
// default Statement
}
Example: -

public class SwitchExample


{
public static void main(String[] args)
{
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number)
{
//Case statements
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
//Default case statement
default: [Link]("Not in 10, 20 or 30");
}
}
}
Loop Statements:

In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates
to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution
of the set of instructions depends upon a particular condition. In Java, we have three types of loops that execute
similarly. However, there are differences in their syntax and condition checking time.

1. for loop

2. while loop

3. do-while loop
1. for loop:

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition,
and increment/decrement in a single line of code. We use the for loop only when we exactly know the
number of times, we want to execute the block of code.

Syntax:-

for(initialization, condition, increment/decrement) {

//block of statements

Example

// Java program to demonstrates the working of for loop

import [Link].*;

class Geeks {

public static void main(String[] args)

for (int i = 0; i <= 10; i++) {

[Link](i + " ");

}
Output 0 1 2 3 4 5 6 7 8 9 10

2. for-each loop:

Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop,
we don't need to update the loop variable. This loop is used to iterate over arrays or collections.

Syntax:

for (dataType variable : arrayOrCollection) {

// code to be executed

Example

// Java program to demonstrates the working of for each loop


import [Link].*;
class Geeks {
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };

for (int i : arr) {


[Link](i + " ");
}
}
}
Output

12345

3. while Loop

A while loop is used when we want to check the condition before running the code.

Syntax:

while (condition) {

// code to be executed
}

Example

// Java program to demonstrates


// the working of while loop
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int i = 0;
while (i <= 10) {
[Link](i + " ");
i++;
}
}
}
Output
0 1 2 3 4 5 6 7 8 9 10

4. do-while Loop

The do-while loop in Java ensures that the code block executes at least once before the condition is checked.

Syntax:

do {
// code to be executed

} while (condition);

Example
// Java program to demonstrates
// the working of do-while loop
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int i = 0;
do {
[Link](i + " ");
i++;
} while (i <= 10);
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

Jump Statements in Java


Jumping statements are control statements that transfer execution control from one point to another point in
the program. There are three Jump statements that are provided in the Java programming language:

1. Break statement.

2. Continue statement.

3. Return Statement.

Break statement: Break Statement to exit a loop:

In java, the break statement is used to terminate the execution of the nearest looping statement or switch
statement. The break statement is widely used with the switch statement, for loop, while loop, do-
while loop.
Syntax:

break;

Example

// Java program to illustrate the


// break keyword in Java
import [Link].*;
class GFG {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
[Link](i);
}
}
}

Output

1
2

Continue Statement

The continue statement pushes the next repetition of the loop to take place, hopping any code between itself
and the conditional expression that controls the loop.

Example:

// Java program to illustrate the


// continue keyword in Java
import [Link].*;

class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 6) {
[Link]();
// using continue keyword
// to skip the current iteration
continue;
}
[Link](i);
}
}
}

Output

0
1
2
3
4
5

7
8
9
Return Statement

The “return” keyword can help you transfer control from one method to the method that called it. Since the
control jumps from one part of the program to another, the return is also a jump statement.

• “return” is a reserved keyword means we can’t use it as an identifier.

• It is used to exit from a method, with or without a value.

Example:

import [Link].*;
class ReturnExample {
// A simple method that takes two integers as input and
// returns their sum
public static int calculateSum(int num1, int num2)
{
// Print a message indicating the method has started
[Link]("Calculating the sum of " + num1
+ " and " + num2);
int sum = num1 + num2;
[Link]("The sum is: " + sum);
// Return the calculated sum
return sum;
// Note: Any code after the 'return' statement will
// not be executed. But "Final" is an exception in
// the case of try-catch-final block.
// [Link]("end"); // error : unreachable
// statement
}
public static void main(String[] args)
{
// Call the calculateSum method
int result = calculateSum(5, 10);

// Print the result


[Link]("Result: " + result);
}
}
Output
Calculating the sum of 5 and 10
The sum is: 15
Result: 15

UNIT 2

CLASSES AND OBJECTS

CLASSES AND OBJECTS

Classes

Classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent
real-world concepts and entities. The class represents a group of objects having similar properties and
behaviour. A class can also be called a logical template to create the objects that share common properties and
methods. Java provides a reserved keyword class to define a class. The keyword must be followed by the class
name. Inside the class, methods and variables are declared. For example, Student is a class while a particular
student named Ravi is an object.

class declaration includes the following in the order as it appears:


1. Modifiers: A class can be public or has default access.
2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by convention).
4. Superclass (if any): The name of the class's parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
5. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.

Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}
Example:
class Simple
{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
Properties of Java Classes

1. Fields

Variables stated inside a class that indicate the status of objects formed from that class are called fields,
sometimes referred to as instance variables. They specify the data that will be stored in each class object.
Different access modifiers, such as public, private, and protected, can be applied to fields to regulate their
visibility and usability.

2. Methods

Methods are functions defined inside a class that includes the actions or behaviours that objects of that class
are capable of performing. These techniques allow the outside world to function and change the object's
state (fields). Additionally, methods can be void (that is, they return nothing) or have different access
modifiers. They can also return values.

3. Constructors

Constructors are unique methods that are used to initialize class objects. When an object of the class is created
using the new keyword, they are called with the same name as the class. Constructors can initialize the fields
of an object or carry out any additional setup that's required when an object is created.

4. Blocks

Within a class, Java allows two different kinds of blocks: instance blocks, commonly referred to as
initialization blocks and static blocks. Static blocks, which are usually used for static initialization, are only
executed once when the class is loaded into memory. Instance blocks can be used to initialize instance
variables and are executed each time a class object is generated.

5. Nested Class and Interface

Java permits the nesting of classes and interfaces inside other classes and interfaces. The members (fields,
methods) of the enclosing class are accessible to nested classes, which can be static or non-static. Nested
interfaces can be used to logically group related constants and methods together because they are implicitly
static.

Example:

// Define a class named Person


class Person {
// Instance variables (attributes)
String name;
int age;
// Constructor to initialize the object
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// Method to display person details
public void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
// Main method to create and use the object
public static void main(String[] args) {
// Creating an object of the Person class
Person p1 = new Person("Alice", 25);
// Calling the display method
[Link]();
}
}
Output:

Name: Alice

Age: 25

OBJECTS
Object: An object in Java is a basic unit of Object-Oriented Programming and represents real life entities.
Objects are the instances of a class that are created to use the attributes and methods of a class. A typical
Java program creates many objects, which, interact by invoking methods. An object consists of:

• State: It is represented by attributes of an object. It also reflects the properties of an object.

• Behavior: It is represented by the methods of an object. It also reflects the response of an object with
other objects.

• Identity: It gives a unique name to an object and enables one object to interact with other objects.

Syntax :-

Class_name object_name = new Constructor_name( );

Accessing object :-

Using (.) dot operators we can access object.

Example:

// Define a class named Car


class Car {
// Instance variables (attributes)
String brand;
int year;
// Constructor to initialize the object
public Car(String brand, int year) {
[Link] = brand;
[Link] = year;
}
// Method to display car details
public void display() {
[Link]("Car Brand: " + brand);
[Link]("Manufacturing Year: " + year);
}
// Main method to create and use objects
public static void main(String[] args) {
// Creating objects of the Car class
Car car1 = new Car("Toyota", 2020);
Car car2 = new Car("Honda", 2018);
// Calling the display method on both objects
[Link]();
[Link]();
}
}
Output:

Car Brand: Toyota


Manufacturing Year: 2020
Car Brand: Honda
Manufacturing Year: 2018

Difference Between Java Classes and Objects

The main differences between class and object in Java are as follows:

Class Object

Class is the blueprint of an object. It is used to


An object is an instance of the class.
create objects.

No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.

An object is a real-world entity such as a book, car,


A class is a group of similar objects.
etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as per


A class can only be declared once.
requirement.
Class Object

Objects of the class car can be BMW, Mercedes,


An example of class can be a car.
Ferrari, etc.

Example program for classes and objects


// Define a class named Student
class Student {
// Instance variables (attributes)
String name;
int age;
String grade;
// Constructor to initialize the object
public Student(String name, int age, String grade) {
[Link] = name;
[Link] = age;
[Link] = grade;
}
// Method to display student details
public void displayDetails() {
[Link]("Student Name: " + name);
[Link]("Age: " + age);
[Link]("Grade: " + grade);
}
// Main method to create and use objects
public static void main(String[] args) {
// Creating objects of the Student class
Student student1 = new Student("Alice", 20, "A");
Student student2 = new Student("Bob", 22, "B");
// Calling the displayDetails method on both objects
[Link]("Student 1 Details:");
[Link]();
[Link]("\nStudent 2 Details:");
[Link]();
}
}
Output:

Student 1 Details:
Student Name: Alice
Age: 20
Grade: A

Student 2 Details:
Student Name: Bob
Age: 22
Grade: B
Java Constructors

Java constructors or constructors in Java is a terminology used to construct something in our programs. A
constructor in Java is a special method that is used to initialize objects. The constructor is called when an
object of a class is created. It can be used to set initial values for object attributes. Every time an object is
created using the new() keyword, at least one constructor is called.

It is a special type of method which is used to initialize the object. 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.
Rules for creating Java constructor

Each time an object is created using a new() keyword, at least one constructor (it could be the default
constructor) is invoked to assign initial values to the data members of the same class. Rules for writing
constructors are as follows:

• The constructor(s) of a class must have the same name as the class name in which it resides.

• A constructor in Java cannot be abstract, final, static, or Synchronized.

• Access modifiers can be used in constructor declaration to control its access i.e which other class can
call the constructor.

Types of Constructors in Java


• Default Constructor
• Parameterized Constructor

• Copy Constructor

1. Default Constructor in Java


A constructor that has no parameters is known as default constructor. A default constructor is invisible. And
if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken
out. It is being overloaded and called a parameterized constructor. The default constructor changed into the
parameterized constructor. But Parameterized constructor can’t change the default constructor. The defaul t
constructor can be implicit or explicit.
Implicit Default Constructor: If no constructor is defined in a class, the Java compiler automatically
provides a default constructor. This constructor doesn’t take any parameters and initializes the object with
default values, such as 0 for numbers, null for objects.
Explicit Default Constructor: If we define a constructor that takes no parameters, it’s called an explicit
default constructor. This constructor replaces the one the compiler would normally create
automatically. Once you define any constructor (with or without parameters), the compiler no longer
provides the default constructor for you.
Example:
class Student {
String name;
int age;
// Default Constructor
public Student() {
name = "Unknown";
age = 0;
}

// Method to display student details


public void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}

public static void main(String[] args) {


// Creating an object of Student class
Student s1 = new Student(); // Calls default constructor
[Link]();
}
}
Output
Name: Unknown
Age: 0

2. Parameterized Constructor in Java


A constructor that has parameters is known as parameterized constructor. To initialize fields of the class
with our own values, then use a parameterized constructor. Initializing objects with parameterized
constructors requires the same number and order of arguments to be passed by the user concerning the
parameterized constructor being used.

Example:

class Car {
String brand;
int year;

// Parameterized Constructor
public Car(String brand, int year) {
[Link] = brand;
[Link] = year;
}
// Method to display car details
public void display() {
[Link]("Car Brand: " + brand);
[Link]("Manufacturing Year: " + year);
}
public static void main(String[] args) {
// Creating objects with parameterized constructor
Car car1 = new Car("Toyota", 2020);
Car car2 = new Car("Honda", 2018);

[Link]();
[Link]();
}
}
Output
Car Brand: Toyota
Manufacturing Year: 2020
Car Brand: Honda
Manufacturing Year: 2018
3. Copy Constructor

• A copy constructor creates a new object by copying values from an existing object.

• It is useful when we want to create a duplicate object.

Example:

class Employee {
String name;
int id;
// Parameterized Constructor
public Employee(String name, int id) {
[Link] = name;
[Link] = id;
}
// Copy Constructor
public Employee(Employee emp) {
[Link] = [Link];
[Link] = [Link];
}
// Method to display employee details
public void display() {
[Link]("Employee Name: " + name);
[Link]("Employee ID: " + id);
}
public static void main(String[] args) {
// Creating an object using parameterized constructor
Employee emp1 = new Employee("Alice", 101);
// Creating a copy of emp1 using copy constructor
Employee emp2 = new Employee(emp1);
[Link]();
[Link]();
}
}
Output
Employee Name: Alice

Employee ID: 101

Employee Name: Alice

Employee ID: 101

Note:

Finalizer ():- Finalize() is the method of Object class. This method is called just before an object is garbage

collected. finalize() method overrides to dispose system resources, perform clean-up activities

and minimize memory leaks.

Difference Between Constructor and Method

Feature Constructor Method

Purpose Initializes an object Performs a task (operation)

Name Same as class name Can be any valid name

Return Type No return type Has a return type (void, int, String, etc.)

Calling Called automatically when an object is created Called explicitly using [Link]()

Overloading Yes, we can overload constructors Yes, we can overload methods

Use of constructor

• To initialize objects automatically at the time of creation.


• To enforce initial values for object attributes.
• To create multiple variations of an object using overloading.

Access Modifiers

Access modifiers helps to restrict the scope of a class, constructor, variable, method, or data member. It
provides security, accessibility, etc. to the user depending upon the access modifier used with the element.
Access Modifiers in Java control the visibility and accessibility of classes, methods, and variables, ensuring
better security and encapsulation.

Types of Access Modifiers


There are 4 types of access modifiers

1. Default Access Modifier

When no access modifier is specified for a class, method, or data member, it is said to be having the default
access modifier by default. The default access modifiers are accessible only within the same package.

Example

// default access modifier


package p1;
// Class Geek is having
// Default access modifier
class Geek
{
void display()
{
[Link]("Hello World!");
}
}
[Link] Access Modifier

The private access specifier in Java is the most restrictive access level. The private access modifier is
specified using the keyword private. Members (fields, methods, or inner classes) marked with private are
only accessible within the class in which they are declared. The methods or data members declared as
private are accessible only within the class in which they are declared.

• Any other class of the same package will not be able to access these members.

• Top-level classes or interfaces can not be declared as private because, private means “only visible
within the enclosing class”.

Example

class MyClass {
// Private variable
private int number;
// Private method
private void display() {
[Link]("This is a private method.");
}
// Public method to set value of private variable
public void setNumber(int num) {
[Link] = num;
}
// Public method to get value of private variable
public int getNumber() {
return number;
}
// Public method to call the private method within the class
public void callPrivateMethod() {
display(); // Can access the private method within the same class
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
// [Link] = 10; // Error: 'number' has private access
// [Link](); // Error: 'display()' has private access

// Using setter method to set the private variable


[Link](10);
// Using getter method to retrieve the private variable
[Link]("The number is: " + [Link]());
// Calling the private method through a public method
[Link]();
}
}
Output

This is a private method.


The number is: 10

Example for understanding


class MyClass {
private int number; // private variable
private void display() { // private method
[Link]("This is a private method.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
// The following lines will cause compilation errors due to private access:
// [Link] = 10; // Error: number has private access in MyClass
// [Link](); // Error: display() has private access in MyClass
}
}
Output

Error: number has private access in MyClass

Error: display() has private access in MyClass

3. Protected Access Modifier: The protected access modifier is specified using the keyword protected. The
methods or data members declared as protected are accessible within the same package or subclasses in
different packages.

Example

// protected modifier
package p2;
// importing all classes
// in package p1
import p1.*;
// Class B is subclass of A
class B extends A {
public static void main(String args[]) {
B obj = new B();
[Link]();
}
}
4. Public Access Modifier

The public access modifier is specified using the keyword public.

• The public access modifier has the widest scope among all other access modifiers.

• Classes, methods, or data members that are declared as public are accessible from everywhere in the
program. There is no restriction on the scope of public data members.

Example

// public access modifier


package p2;
import p1.*;
class B {
public static void main(String args[]) {
A obj = new A();
[Link]();
}
}
Method Overloading in Java: A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. It is used to achieve the reusability of code. Method
Overloading allows different methods to have the same name, but different signatures where the signature
can differ by the number of input parameters or type of input parameters, or a mixture of both. Method
overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism, or Early binding.

Method Declaration:

The method declaration provides information about method attributes, such as visibility,

return-type, name, and arguments. It has six components that are known as method header

Syntax of Method :-

<access_modifier> <return_type> <method_name>( list_of_parameters)

//body

Naming a Method :-

While defining a method, remember that the method name must be a verb and start with a lowercase letter.
In the multi-word method name, the first letter of each word must be in uppercase except the first word.
o Single-word method name: sum(), area()

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

It is also possible that a method has the same name as another method name in the same class, it is known as
method overloading

Example

// Java program to demonstrate working of method


// overloading in Java
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}
Output

30

60

31.0

Types of Method

There are two types of methods in Java:

o Predefined Method

o User-defined Method
Predefined Method: In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods.

It is also known as the standard library method or built-in method. We can directly use these methods just
by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.

Example :-

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
}
}
▪ In the above method signature, we see that the method signature has access specifier public, non-access
modifier static, return type int, method name max(), parameter list (int a, int b). In the above example,
instead of defining the method, we have just invoked the method. This is the advantage of a predefined
method. It makes programming less complicated.

User-defined Method :-

The method written by the user or programmer is known as a user-defined method. These methods are
modified according to the requirement.

To Create a User-defined Method

//user defined method


public static void findEvenOdd(int num)
{ //method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. The calling of a method in a program is

simple. When we call or invoke a user-defined method, the program control transfer to the called

method.

Example:
import [Link];
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from the user
int num=[Link]();
//method calling
findEvenOdd(num);
}
Math class :-

Java Math class provides several methods to work on math calculations like min(), max(), avg(),

sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Math Methods :-

The [Link] class contains various methods for performing basic numeric operations

such as the logarithm, cube root, and trigonometric functions etc.

Method Description

sin Returns the trigonometric value of the sine of an angle.

cos Returns the trigonometric value of the cosine of an angle.

exp Returns Euler’s number e raised to the power of a double value

sqrt Returns the correct rounded positive square root of a double value
pow Returns(pow(a,b)) the value of ab

min Returns the maximum out of the two arguments

max Returns the minimum out of the two arguments

Overloading :-

In object oriented programming, overloading refers to the ability of a class to have multiple

constructors or multiple methods with the same name but different signatures, i.e. arguments

list.

Types of overloading

1. Constructor overloading

2. Method overloading

3. Operator overloading

Constructor overloading

The constructor overloading can be defined as the concept of having more than one constructor with
different parameters so that every constructor can perform a different task.

Example :-

class A
{
A()
{
[Link](“ Constructor without arguments “);
}
A(int a)
{
[Link](“ Constructor with arguments “);
}
}
class Coverload
{
public static void main( String arg[])
{
A obj = new A( );
A obj1= new A (10);
}
}
Static member: In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.

The static keyword can be used with methods, fields, classes (inner/nested), blocks.

Static Methods − create a static method by using the keyword static. Static methods can access only static
fields, methods. To access static methods there is no need to instantiate the class.

Example

public class StaticExample {


// Static variable
static int count;
// Static block
static {
count = 10;
[Link]("Static block executed. Initial count: " + count);
}
// Static method
static void displayCount() {
[Link]("Static method called. Count is: " + count);
}
public static void main(String[] args) {
// Access static method directly using class name (optional here)
[Link]();
// Modify static variable
[Link] = 25;
// Call static method again
displayCount();
}
}
this keyword

The this keyword refers to the current object in a method or constructor. The most common use of
this keyword is to eliminate the confusion between class attributes and parameters with the same name
(because a class attribute is shadowed by a method or constructor parameter).

this can also be used to:

• Invoke current class constructor

• Invoke current class method

• Return the current class object

• Pass an argument in the method call

• Pass an argument in the constructor call

Example
// Java Program to implement
// Java this reference
// Driver Class
public class Person {
// Fields Declared
String name;
int age;
// Constructor
Person(String name, int age)
{
[Link] = name;
[Link] = age;
}
// Getter for name
public String get_name() { return name; }
// Setter for name
public void change_name(String name)
{
[Link] = name;
}
// Method to Print the Details of
// the person
public void printDetails()
{
[Link]("Name: " + [Link]);
[Link]("Age: " + [Link]);
[Link]();
}
// main function
public static void main(String[] args)
{
// Objects Declared
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);
[Link]();
[Link]();
first.change_name("PQR");
[Link]("Name has been changed to: + first.get_name());
}
}

Output

Name: ABC

Age: 18

Name: XYZ

Age: 22

Name has been changed to: PQR


ARRAY

ARRAY

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 . An object
of a dynamically formed class is called an array in Java. Java arrays implement the Serializable and Cloneable
interfaces and derive from the Object class. In Java, an array can hold objects or primitive values.

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

o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

o Random access: We can get any data located at an index position.

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.

To declare an array, define the variable type with square brackets:

String[] cars;

Declared a variable that holds an array of strings. To insert values to it, place the values in a comma-
separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link](cars[0]);
// Outputs Volvo
Change an Array Element
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
[Link](cars[0]);
// Now outputs Opel instead of Volvo
Array Length
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link]([Link]);
// Outputs 4

One Dimensional Array


There are two types of array :

1. One-dimensional array

2. Multi-dimensional array

One-dimensional array: The name that a one-dimensional array in java must deal with only one parameter.
Entities of similar types can be stored together using one-dimensional arrays. It can store primitive data
types (int, float, char, etc.) or objects.

A one-dimensional array can be visualized as a single row or a column of array elements that are represented
by a variable name and whose elements are accessed by index values.

Declaration of one-dimensional array

data-type var-name[];
OR
data-type[] var-name;
OR
data-type []var-name;
An array declaration has two components :
data-type: The data type determines the data type of each element present in the array-like char, int, float,
objects etc.
var-name: It is the name of the reference variable which points to the array object stored in the heap
memory.
[ ] : It is called subscript.

Construction of one-dimensional array in Java


There are mainly two ways to create an array in java :
1. We can declare and store the values directly at the time of declaration :
int marks[ ] = { 90, 97, 95, 99, 100 };
2. The second way of creating an array is by first declaring the array and then allocating the memory
through the new keyword :
var-name = new type[size];
eg: int[] Number = new int[10];

Example 1 only for understanding

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
public class Main{
public static void main(String args[]){
//declaration and instantiation of an array
int a[]=new int[5];
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++){//length is the property of array
[Link](a[i]);
}
}
}

Example for one Dimensional array

import [Link];
public class OneDimensionalArrayInput {
public static void main(String args[]) {
// creating object of Scanner class
Scanner scan = new Scanner([Link]);
[Link]("Enter length of Array: ");
int arrLength = [Link]();
int[] anArray = new int[arrLength];
[Link]("Enter the elements of the Array");
for (int i = 0; i < arrLength; i++) {
// taking array input
anArray[i] = [Link]();
}
[Link]("One dimensional array elements are:");
for (int i = 0; i < arrLength; i++) {
// printing array elements
[Link](anArray[i] + " ");
}
}
}
output
Enter length of Array:
5
Enter the elements of the Array
1
2
3
4
5
One dimensional array elements are:
12345

Two Dimensional Array

A 2D array is like a table made of rows and columns.

It is a data structure used to store data in a grid-like format with rows and columns.

You can think of it as a table or matrix, where:

• Each element is accessed using two indices – one for the row and one for the column.

• It is declared as: dataType[][] arrayName;

// Declaring 2D array
DataType[][] ArrayName;
// Creating a 2D array
ArrayName = new DataType[r][c];

Eg : //Declaring 2D array
int[][] a;
//Creating a 2D array
a = new int[3][3];

// Creating a 2D Array
DataType[][] ArrayName = new DataType[r][c]
// Accessing an element
DataType var = ArrayName[i][j];

Example for 2d array

public class Main {


public static void main(String args[]) {
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}
Output
123
456
789
Example 2
import [Link];
public class Main {
public static void main(String args[]) {
int[][] StudentMarks = new int[3][3];

// Marks Attained By Student 1


StudentMarks[0][0] = 90; // English
StudentMarks[0][1] = 70; // Maths
StudentMarks[0][2] = 84; // Science

// Marks Attained By Student 2


StudentMarks[1][0] = 75; // English
StudentMarks[1][1] = 77; // Maths
StudentMarks[1][2] = 89; // Science

// Marks Attained By Student 3


StudentMarks[2][0] = 69; // English
StudentMarks[2][1] = 93; // Maths
StudentMarks[2][2] = 83; // Science

// Displaying Marks of Students


[Link]("Student Marks Matrix");
[Link]([Link](StudentMarks));
}
}
Output

Student Marks Matrix


[[90, 70, 84], [75, 77, 89], [69, 93, 83]]

Array of objects

An array of objects is a collection (or list) where each item in the array is an object, and each object can store
multiple related values as properties.

let students = [
{ name: "Alice", age: 20 },
{ name: "Bob", age: 22 },
{ name: "Charlie", age: 19 }
];
In this example:
• students is an array.
• Each item inside the array is an object with properties like name and age.
Instantiate array of object
syntax
ClassName obj[ ]= new ClassName[Array_Length];
Eg:
Groceries groceriesObjects = new Groceries[2];

Example for array of objects

class Food {
String name;
int calories;

// Constructor
Food(String name, int calories) {
[Link] = name;
[Link] = calories;
}
// Method to display food info
void display() {
[Link](name + " has " + calories + " calories.");
}
}

public class FoodArrayExample {


public static void main(String[] args) {
// Creating an array of Food objects
Food[] foods = new Food[3];

// Initializing each object in the array


foods[0] = new Food("Apple", 95);
foods[1] = new Food("Banana", 105);
foods[2] = new Food("Pizza", 285);

// Displaying the food info


for (int i = 0; i < [Link]; i++) {
foods[i].display();
}
}
}

Strings

String is a sequence of characters. In Java, string is an object that represents a sequence of characters. The
[Link] class is used to create a string object.

There are two ways to create String object:


1. By string literal
2. By new keyword
String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

By new keyword
String s=new String("Welcome");//creates two objects and one reference variable

Example

public class StringExample {


public static void main(String[] args) {
// Creating a string
String name = "John";

// Printing the string


[Link]("Hello, " + name + "!");

// String length
[Link]("Length of name: " + [Link]());
}
}
Output
Hello, John!
Length of name: 4

String handling function


String handling functions in Java are built-in methods provided by the String class that allow you to perform
various operations on strings, such as comparing, searching, modifying, and extracting parts of a string.
The string class has a set of built-in-methods, defined below.
Function Description Example

length() Returns the length of the string "Hello".length() →5

toUpperCase() Converts string to uppercase "hello".toUpperCase() → "HELLO"

toLowerCase() Converts string to lowercase "JAVA".toLowerCase() → "java"

charAt(index) Returns the character at the given index "Java".charAt(1) → 'a'

substring(start, end) Extracts part of the string "Hello".substring(1, 4) → "ell"

equals(str) Checks if two strings are equal "hi".equals("hi") → true

contains(str) Checks if string contains another string "hello".contains("lo") → true

replace(a, b) Replaces characters "apple".replace('a', 'A') → "Apple"

Example program
public class StringHandlingExample {
public static void main(String[] args) {
String text = "Hello Java";

// 1. length()
[Link]("Length: " + [Link]());

// 2. toUpperCase()
[Link]("Uppercase: " + [Link]());

// 3. toLowerCase()
[Link]("Lowercase: " + [Link]());

// 4. charAt()
[Link]("Character at index 1: " + [Link](1));

// 5. substring()
[Link]("Substring (0 to 5): " + [Link](0, 5));

// 6. equals()
[Link]("Equals 'Hello Java': " + [Link]("Hello Java"));

// 7. contains()
[Link]("Contains 'Java': " + [Link]("Java"));

// 8. replace()
[Link]("Replace 'Java' with 'World': " + [Link]("Java", "World"));
}
}

Output
Length: 10
Uppercase: HELLO JAVA
Lowercase: hello java
Character at index 1: e
Substring (0 to 5): Hello
Equals 'Hello Java': true
Contains 'Java': true
Replace 'Java' with 'World': Hello World

UNIT 3
Multithreading in Java
Multithreading in Java
Concepts of Thread
Threads

A thread is a fundamental unit of execution within a program, allowing to execute multiple tasks concurrently,
improving performance, especially for time-consuming operations like I/O or network
communications. Threads share the same memory space and resources within a process, making
communication efficient but requiring careful coordination to avoid issues like race conditions.
Key Concepts:
• Concurrency:
Threads allow multiple parts of a program to execute concurrently, creating the illusion of simultaneous
execution.
• Process vs. Thread:
A process is an independent program, while a thread is a subpart of a process that can run independently.
• Main Thread:
Every Java program starts with at least one thread, the main thread, which is also the parent thread.
• Thread Life Cycle:
A thread progresses through different states (new, runnable, running, blocked, dead) during its execution.
• Thread Priority:
Threads can have different priorities, influencing the order of their execution.
• Synchronization:
Mechanisms like synchronized blocks or the wait()/notify() methods help coordinate access to shared
resources and prevent race conditions.
• ThreadLocal:
Used to create thread-specific storage, allowing each thread to have its own copy of data.
Use of Threads
Threads are used to perform multiple tasks at the same time (concurrently). This is useful for:
• Improving performance
• Keeping applications responsive (like a UI app)
• Performing background tasks (like downloading files, playing music, etc.)
Advantages of Using Threads:
• Better CPU usage
• Faster performance for tasks like file processing or network calls
• Allows parallel processing

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously. Multiprocessing and
multithreading, both are used to achieve multitasking

Thread Life Cycle(states of thread)


A thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
1. New: A thread is in the New state when it's created but not yet started (i.e., the start() method hasn't been
called).
2. Runnable: After the start() method is called, the thread becomes Runnable. It's ready to run and waiting
for its turn to be scheduled by the CPU.
3. Blocked (or Waiting): A thread can be blocked when it's waiting for a resource or a condition, such as a
lock held by another thread.
4. Waiting: A thread in the Waiting state is waiting indefinitely for another thread to perform a specific
action or for a condition to become true.
5. Timed Waiting: Similar to Waiting, but with a specified time limit. The thread will automatically resume
after the time period elapses, or if the condition it's waiting for becomes true.
6. Terminated (Dead): The thread has completed its execution, either normally or due to an uncaught
exception, and is no longer alive.

Creating Threads & Implementing Runnable Interface


There are two main ways to create threads in Java:
1. By extending the Thread class
2. By implementing the Runnable interface
Method 1: Extending the Thread Class
Concept:
Starting a Thread
The start() method of the Thread class is used to start a newly created thread. It performs the following
tasks:
o A new thread starts (with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
syntax:
1. Using Thread Class (Extending Thread)
class MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // Create thread
[Link](); // Start thread
}
}
2. Using Runnable Interface
class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
}
}

public class Main {


public static void main(String[] args) {
MyRunnable obj = new MyRunnable(); // Create Runnable object
Thread t1 = new Thread(obj); // Pass it to Thread constructor
[Link](); // Start thread
}
}
Why are there two methods to create threads in Java?
Java provides two ways to create threads to give developers flexibility based on the needs of their application
and object-oriented design principles.
Method 1: Extending Thread class
When to use:
• When your class doesn’t need to extend any other class.
• You want to customize or extend the behaviour of the Thread class itself.
Limitation:
• Java doesn't support multiple inheritance, so if you extend Thread, you can’t extend any other
class.

Method 2: Implementing Runnable interface


When to use:
• When your class already extends another class.
• You want to separate the task (Runnable) from the thread control (Thread class).
Advantage:
• More flexible and clean design.
• Promotes separation of concerns: Your task logic (Runnable) is separate from thread management
(Thread).
• Easier to share the same Runnable with multiple threads.

Examples
Method 1: Extending the Thread Class
// File: [Link]

// Method 1: Extending Thread class


class Hai Thread extends Thread {
public void run() {
for (int i = 1; i <= 20; i++) {
[Link]("Hai " + i);
try {
[Link](50);
} catch (InterruptedException e) {} // Sleep to allow switching between threads
}
}
}

// Method 2: Implementing Runnable interface

class HelloRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 20; i++) {
[Link]("Hello " + i);
try { [Link](50);
} catch (InterruptedException e) {} // Sleep to allow switching between threads
}
}
}

public class ThreadExampleBothMethods {


public static void main(String[] args) {
// Creating threads using both methods

// Method 1: Extending Thread class


HaiThread t1 = new HaiThread();

// Method 2: Implementing Runnable interface


HelloRunnable helloRunnable = new HelloRunnable();
Thread t2 = new Thread(helloRunnable);

// Starting both threads


[Link]();
[Link]();
}
}
Output
Hai
Hello
Hai
Hello
Hai
Hai
Hello
Hello
Hai
Hello
Hai
Hai
Hello
Hello
Hai
Hai
Hello
Hello
Hai
Hai
Note: The actual order will vary each time you run the program because of the random nature of thread
execution and the time the operating system gives each thread to execute.
In Method 1 (extending Thread), you directly extend the Thread class and override its run() method to
handle printing "Hai" and "Hello".
In Method 2 (implementing Runnable), you create classes that implement the Runnable interface, providing
more flexibility in your design, especially when your class needs to extend something else (like another class).
Differences:
Thread Class Runnable Interface
1 Extends the Thread class Implements the Runnable interface
2 Cannot extend another class Can extend another class
3 Less flexible due to inheritance More flexible due to composition
4 Creates a thread by creating an object Creates a thread by passing to Thread class
5 Code is tightly coupled with thread Code is separate from thread
6 Suitable for small, simple programs Better for large-scale applications
7 Uses more memory Uses less memory
8 Difficult to share resources Easier to share resources
9 Less preferred in modern Java More preferred approach
10 Example: `class MyThread extends Thread` Example: `class MyRunnable implements Runnable`

Thread Synchronization & Thread Priority.


Thread synchronization is a technique that ensures that only one thread can access a resource or a piece of
code at a time. This is particularly important in multithreaded environments where multiple threads may
attempt to modify shared data or resources concurrently, leading to inconsistent or erroneous behaviour.

Why Do We Need Synchronization?


In a multithreading scenario, race conditions can occur if two or more threads try to access and modify shared
resources simultaneously. This can cause data corruption, inconsistent results, or unexpected behaviors.
Synchronization ensures that only one thread can access the critical section of code at any given time,
preventing race conditions.
How Synchronization Works:
In Java, we can use the synchronized keyword to ensure that a method or block of code is accessed by only
one thread at a time. This prevents multiple threads from accessing the critical section concurrently.
Syntax for Synchronization
1. Synchronizing Methods:
To synchronize a method, you use the synchronized keyword in the method declaration. This ensures that only
one thread can execute that method at a time for the same object.
synchronized void methodName() {
// Critical section
}
2. Synchronizing Blocks:
Synchronize specific blocks of code within a method. This allows for more fine-grained control over
synchronization, especially when you don’t want to synchronize the entire method.
synchronized (lockObject) {
// Critical section
}
Here, lockObject is an object that will be used as a monitor to ensure that only one thread can execute the
synchronized block.
Example
class Counter {
int count = 0;
// Synchronized method to avoid race condition
synchronized void increment() {
count++; // This is now thread-safe
}
// Getter method
synchronized int getCount() {
return count;
}
}
public class SynchronizedExample {
public static void main(String[] args) {
Counter counter = new Counter()
// Thread 1
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
}
});
// Thread 2
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
}
});
// Start both threads
[Link]();
[Link]();
// Wait for both threads to finish
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}
// Output the final count (should be 2000)
[Link]("Final count: " + [Link]());
}
}
Output
Final count: 2000

Thread Priority in Java


Thread priority in Java refers to the relative importance or urgency of a thread in comparison to other
threads. The operating system's thread scheduler uses the thread priority to decide which thread to execute
and for how long. A higher priority thread may be allocated more CPU time compared to a lower priority
thread, although it’s not a guarantee.

In Java, each thread has a priority, which is an integer value between Thread.MIN_PRIORITY (1) and
Thread.MAX_PRIORITY (10), with the default being Thread.NORM_PRIORITY (5).
• Thread.MIN_PRIORITY (1): The lowest priority a thread can have.
• Thread.MAX_PRIORITY (10): The highest priority a thread can have.
• Thread.NORM_PRIORITY (5): The default priority for a thread.
While Java allows you to set the priority of a thread, it’s up to the underlying operating system's thread
scheduler to decide how to handle the priorities.

Why Do We Need Thread Priority?


Thread priority can be useful when you have multiple threads performing different tasks, and you want to
ensure that:
1. Critical tasks get more CPU time (higher priority).
2. Non-critical tasks (like background operations) don’t block critical operations (lower priority).
However, thread priority doesn’t guarantee that a thread with a higher priority will always get executed
first. It simply gives it a preference.
Syntax:
To set the priority of a thread, you use the setPriority(int priority) method of the Thread class, passing an
integer between 1 and 10.
[Link](int priority);
Example
class SimpleThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " - " + i);
try {
[Link](100); // Sleep to allow the other thread to run
} catch (InterruptedException e) {}
}
}
}

public class ThreadPrioritySimpleExample {


public static void main(String[] args) {
SimpleThread t1 = new SimpleThread(); // Thread with default priority (NORM_PRIORITY)
SimpleThread t2 = new SimpleThread(); // Thread with default priority (NORM_PRIORITY)

// Set priorities
[Link](Thread.MIN_PRIORITY); // Low priority (1)
[Link](Thread.MAX_PRIORITY); // High priority (10)

// Start both threads


[Link]();
[Link]();
}
}
Output
Thread-1 - 1
Thread-2 - 1
Thread-2 - 2
Thread-2 - 3
Thread-2 - 4
Thread-2 - 5
Thread-1 - 2
Thread-1 - 3
Thread-1 - 4
Thread-1 - 5

Exception Handling
Concepts of Exception
An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e.,
at runtime) and disrupts the normal flow of the program’s instructions. It occurs when something unexpected
happens, like accessing an invalid index, dividing by zero, or trying to open a file that does not exist.
Types of Java Exceptions
In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions.
Additionally, there is a third category known as errors.
1. Checked Exception
2. Unchecked Exception
3. Error

1. Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means that the compiler verifies
that the code handles these exceptions either by catching them or declaring them in the method signature using
the throws keyword. Examples of checked exceptions include:
IOException: An exception is thrown when an input/output operation fails, such as when reading from or
writing to a file.
SQLException: It is thrown when an error occurs while accessing a database.
ParseException: Indicates a problem while parsing a string into another data type, such as parsing a date.
ClassNotFoundException: It is thrown when an application tries to load a class through its string name using
methods like [Link](), but the class with the specified name cannot be found in the classpath.

2. Unchecked Exceptions (Runtime Exceptions)


Unchecked exceptions, also known as runtime exceptions, are not checked at compile-time. These exceptions
usually occur due to programming errors, such as logic errors or incorrect assumptions in the code. They do
not need to be declared in the method signature using the throws keyword, making it optional to handle them.
Examples of unchecked exceptions include:
NullPointerException: It is thrown when trying to access or call a method on an object reference that is null.
ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an invalid index.
ArithmeticException: It is thrown when an arithmetic operation fails, such as division by zero.
IllegalArgumentException: It indicates that a method has been passed an illegal or inappropriate argument.

Arithmetic exception
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
[Link] ("Result = " + c);
}
catch(ArithmeticException e) {
[Link] ("Can't divide a number by 0");
}
}
}
Output
Can't divide a number by 0
NullPointer Exception

//Java program to demonstrate NullPointerException


class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
[Link]([Link](0));
} catch(NullPointerException e) {
[Link]("NullPointerException..");
}
}
}
}
}
StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = [Link](24); // accessing 25th element
[Link](c);
}
catch(StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException");
}
}
}
FileNotFound Exception
//Java program to demonstrate FileNotFoundException
import [Link];
import [Link];
import [Link];
class File_notFound_Demo {

public static void main(String args[]) {


try {

// Following file does not exist


File file = new File("E://[Link]");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
[Link]("File does not exist");
}
}
}

3. Errors
Errors represent exceptional conditions that are not expected to be caught under normal circumstances. They
are typically caused by issues outside the control of the application, such as system failures or resource
exhaustion. Errors are not meant to be caught or handled by application code. Examples of errors include:
OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate enough memory for
the application.
StackOverflowError: It is thrown when the stack memory is exhausted due to excessive recursion.
NoClassDefFoundError: It indicates that the JVM cannot find the definition of a class that was available at
compile-time.

Exception handling mechanism


Exception handling in Java is a mechanism to handle runtime errors and maintain the normal flow of the
program. It uses five keywords: try, catch, throw, throws, and finally.
• Try Block:
Encloses the code that might throw an exception.
• Catch Block:
Catches and handles specific types of exceptions thrown within the try block. Multiple catch blocks can
handle different exception types.
• Throw Keyword:
Explicitly throws an exception, either a predefined exception or a custom exception.
• Throws Keyword:
Declares that a method might throw a specific exception, requiring the calling method to handle it or declare
it in its throws clause.
• Finally Block:
Contains code that executes regardless of whether an exception is thrown or caught, often used for cleanup
tasks like closing resources.
When an exception occurs within a try block, the JVM creates an exception object and searches for a
matching catch block. If a match is found, the code within the catch block executes. If no
matching catch block is found, the exception propagates up the call stack until it is caught or the program
terminates. The finally block, if present, always executes after the try and catch blocks, ensuring that
necessary cleanup actions are performed.

1. Java try...catch block


The try-catch block is used to handle exceptions in Java. Here's the syntax of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
Example
class Main {
public static void main(String[] args) {

try {

// code that generate exception


int divideByZero = 5 / 0;
[Link]("Rest of code in try block");
}

catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}
}
}
Output
ArithmeticException => / by zero

2. Java finally block


In Java, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
The basic syntax of finally block is:
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after
the try block. For each try block, there can be only one finally block.

The basic syntax of finally block is:


try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after
the try block. For each try block, there can be only one finally block.

Example
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}

catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}

finally {
[Link]("This is the finally block");
}
}
}
Output
ArithmeticException => / by zero
This is the finally block

3. Java throw and throws keyword


The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from the try block to the catch block.
Example: Exception handling using Java throw
class Main {
public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {


divideByZero();
}
}
Output
Exception in thread "main" [Link]: Trying to divide by 0
at [Link]([Link])
at [Link]([Link])

Example: Java throws keyword


import [Link].*;

class Main {
// declareing the type of exception
public static void findFile() throws IOException {

// code that may generate IOException


File newFile = new File("[Link]");
FileInputStream stream = new FileInputStream(newFile);
}

public static void main(String[] args) {


try {
findFile();
}
catch (IOException e) {
[Link](e);
}
}
}
Output
[Link]: [Link] (The system cannot find the file specified)

Creating User-Defined Exceptions Using Try-Catch-Finally-Throw Blocks


Creating our own Exception is known as a custom exception in Java or a user-defined exception in Java. In
simple words, we can say that a User-Defined Custom Exception or custom exception is creating your own
exception class and throwing that exception using the “throw” keyword.

// A Class that represents user-defined exception


class MyException extends Exception {
public MyException(String m) {
super(m);
}
}

// A Class that uses the above MyException


public class setText {
public static void main(String args[]) {
try {

// Throw an object of user-defined exception


throw new MyException("This is a custom exception");
}
catch (MyException ex) {
[Link]("Caught");
[Link]([Link]());
}
}
}

Nested Try Catch


we can use a try block within another try block. This is called nested try blocks. Each time a try statement is
entered, the context of that exception is pushed onto a stack. If an exception occurs in the inner try block and
is not caught by its corresponding catch block, the exception propagates to the outer try block. This process
continues until the exception is either caught or reaches the default exception handler.
• Nested try blocks are useful for handling exceptions at different levels of code.
• If an exception occurs in a parent try block, the control jumps directly to the matching catch block in
the parent or outer try block, and any nested try blocks are skipped.
• If an exception occurs in an inner try block and is not caught, it propagates to the outer try block.

class Geeks {

// Main method
public static void main(String args[]) {
// Main try block
try {
// Initializing array
int a[] = { 1, 2, 3, 4, 5 };

// Trying to print element at index 5


[Link](a[5]);

// Inner try block (try-block2)


try {
// Performing division by zero
int x = a[2] / 0; // This will throw ArithmeticException
} catch (ArithmeticException e2) {
[Link]("Division by zero is not possible");
}
} catch (ArrayIndexOutOfBoundsException e1) {
[Link]("ArrayIndexOutOfBoundsException");
[Link]("Element at such index does not exist");
}
}
}

Java throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We
can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom
exceptions.
Syntax of throw in Java
throw Instance
The flow of execution of the program stops immediately after the throw statement is executed and the nearest
enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds
a match, controlled is transferred to that statement otherwise next enclosing try block is checked, and so on.
If no matching catch is found then the default exception handler will halt the program.

// Java program to demonstrate


// how to throw an exception
class Geeks {
static void fun()
{
try {
throw new NullPointerException("demo");
}
catch (NullPointerException e) {
[Link]("Caught inside fun().");
throw e; // rethrowing the exception
}
}

public static void main(String args[])


{
try {
fun();
}
catch (NullPointerException e) {
[Link]("Caught in main.");
}
}
}

Java throws
throws is a keyword in Java that is used in the signature of a method to indicate that this method might throw
one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch
block.
Syntax of Java throws
type method_name(parameters) throws exception_list
// Demonstrating how to throw an exception
class Geeks {

static void fun() throws IllegalAccessException


{
[Link]("Inside fun(). ");
throw new IllegalAccessException("demo");
}

public static void main(String args[])


{
try {
fun();
}
catch (IllegalAccessException e) {
[Link]("Caught in main.");
}
}
}
UNIT 4
File Handling

Java File Handling


The File class from the [Link] package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:
ExampleGet your own Java Server
import [Link]; // Import the File class

File myObj = new File("[Link]"); // Specify the filename

The File class has many useful methods for creating and getting information about files. For example:

Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if
the file was successfully created, and false if the file already exists. Note that the method is enclosed in
a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be
created for some reason):

Example
import [Link]; // Import the File class
import [Link]; // Import the IOException class to handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}
Output:
File created: [Link]

Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to
the file we created in the example above. Note that when you are done writing to the file, you should close it
with the close() method:
Example
import [Link]; // Import the FileWriter class
import [Link]; // Import the IOException class to handle errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("[Link]");
[Link]("Files in Java might be tricky, but it is fun enough!");
[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}
output
Successfully wrote to the file.

Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the
previous chapter:
import [Link]; // Import the File class
import [Link]; // Import this class to handle errors
import [Link]; // Import the Scanner class to read text files

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("[Link]");
Scanner myReader = new Scanner(myObj);
while ([Link]()) {
String data = [Link]();
[Link](data);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("An error occurred.");
[Link]();
}
}
}

Type of files in java


Java classifies files primarily into two types: text files and binary files. Additionally, specific file types like
serialized files and properties files serve particular purposes.
• Text Files:
These files store data as a sequence of characters, readable by humans. Examples include .txt files, source
code files (.java), and XML/YAML configuration files. Classes like FileReader and FileWriter are commonly
used for reading and writing text files.
• Binary Files:
Binary files store data in bytes, not directly readable as text. They can contain various data formats, such as
images (.jpg, .gif), audio (.mp3), video (.mp4), or compiled Java class files
(.class). FileInputStream and FileOutputStream are used for handling binary data.
• Serialized Files:
These files store the state of Java objects, allowing for persistence. The ObjectOutputStream class is used to
write objects to a file, and ObjectInputStream is used to read them back.
• Properties Files:
Used for storing application configuration data in key-value pairs, typically with
a .properties extension. The Properties class in Java provides methods for reading and writing these files.
• Other specific file types:
Libraries can be used to manage other file types like .zip for compressed files.
The [Link] class provides methods for interacting with files and directories, such as creating, deleting,
renaming, and checking file attributes. Classes in [Link] package offer more advanced file handling
capabilities.

Class/Interface Description
File Represents a file or directory path.
FileReader/FileWriter For reading/writing character (text) files.
BufferedReader/BufferedWriter Efficient character stream processing.
FileInputStream/FileOutputStream For reading/writing binary data.
ObjectInputStream/ObjectOutputStream Read/write objects (serialization).
Byte stream
In Java, a byte stream is used for handling the input and output of 8-bit bytes, which is suitable for working
with binary data like images, audio files, and other non-textual data. Byte streams are built upon two abstract
classes: InputStream for reading data and OutputStream for writing data.
Common Byte Stream Classes
• InputStream:
• FileInputStream: Reads bytes from a file.
• ByteArrayInputStream: Reads bytes from a byte array.
• DataInputStream: Reads primitive data types from an input stream.
• BufferedInputStream: Provides buffering for efficient reading of bytes.
• OutputStream:
• FileOutputStream: Writes bytes to a file.
• ByteArrayOutputStream: Writes bytes to a byte array.
• DataOutputStream: Writes primitive data types to an output stream.
• BufferedOutputStream: Provides buffering for efficient writing of bytes.
Example
import [Link].*;

public class ByteStreamExample {


public static void main(String[] args) {
String filePath = "[Link]";

// Writing bytes to a file


try (FileOutputStream fos = new FileOutputStream(filePath)) {
byte[] data = {65, 66, 67, 68, 69}; // ASCII values for A, B, C, D, E
[Link](data);
[Link]("Bytes written to " + filePath);
} catch (IOException e) {
[Link]();
}

// Reading bytes from a file


try (FileInputStream fis = new FileInputStream(filePath)) {
int byteRead;
[Link]("Bytes read from " + filePath + ": ");
while ((byteRead = [Link]()) != -1) {
[Link]((char) byteRead + " "); // Casting to char for display purposes
}
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
Binary I/O Classes and its hierarchy
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations.
These streams support all the types of objects, data-types, characters, files etc. to fully execute the I/O
operations.

[Link]
This is the standard input stream([Link]) that is used to read characters from the keyboard or any other
standard input device.
[Link]
This is the standard output stream([Link]) that is used to produce the result of a program on an output
device like the computer screen. Here is a list of the various print functions that we use to output statements:
– print(): This method in Java is used to display a text on the console. This text is passed as the parameter to
this method in the form of String. This method prints the text on the console and the cursor remains at the end
of the text at the console. The next printing takes place from just here.
Syntax:
[Link](parameter);

Key Binary I/O Classes


• InputStream: Abstract class representing the base of all byte input streams. It provides methods for
reading bytes from a source.
• FileInputStream: Reads raw bytes from a file.
• BufferedInputStream: Adds buffering to an input stream, improving reading efficiency by reducing
the number of disk accesses.
• DataInputStream: Reads primitive data types (int, float, etc.) from a binary stream.
• ObjectInputStream: Deserializes objects from a binary stream.
• OutputStream: Abstract class representing the base of all byte output streams. It provides methods for
writing bytes to a destination.
• FileOutputStream: Writes raw bytes to a file.
• BufferedOutputStream: Adds buffering to an output stream, improving writing efficiency.
• DataOutputStream: Writes primitive data types to a binary stream.
• ObjectOutputStream: Serializes objects to a binary stream.
These classes enable the manipulation of binary data, which is essential for handling files like images, audio,
and other non-textual data.

FileInputStream and FileOutputStream classes

FileInputStream and FileOutputStream are two of the most important classes in the Java programming
language for reading and writing data to files, respectively. They are both byte streams, which means that they
read and write data in binary format, consisting of exactly 8-bit bytes.
FileInputStream is used to read data from a file, one byte at a [Link] create a FileInputStream object, you
must pass the path to the file you want to read as a constructor argument.
FileOutputStream is used to write data to a file, one byte at a time. It can be used to write any type of file,
including text files, image files, and audio files. To create a FileOutputStream object, you must pass the path
to the file you want to write to as a constructor argument.
FileInputStream and FileOutputStream are very powerful classes for reading and writing data to files in Java.
They are used in a wide variety of applications, including text editors, image viewers, and audio players.
• Both FileInputStream and FileOutputStream are subclasses of the InputStream and OutputStream
classes, respectively. This means that they inherit all of the methods from these parent classes.
• FileInputStream and FileOutputStream are both AutoCloseable classes. This means that they can be
automatically closed using the try-with-resources statement.
• If you are writing to a file that does not exist, FileOutputStream will create the file for you.
• If you are writing to a file that already exists, FileOutputStream will overwrite the contents of the file.
• To append data to an existing file, you can use the FileOutputStream constructor that takes a boolean
parameter. If you set this parameter to true, FileOutputStream will append data to the end of the file
instead of overwriting it.
Methods of FileInputStream Class
Method Description

Returns an estimate of the number of bytes that can be read (or skipped over)
available() from this input stream without blocking, which may be 0, or 0 when end of stream
is detected.

Closes this input stream and releases any system resources associated with the
close()
stream.

Marks the current position in this input stream. A subsequent reset() will attempt
mark(int readlimit)
to reposition the stream to this point.

markSupported() Tells whether this input stream supports the mark() and reset() methods.

read() Reads a byte of data from this input stream.

read(byte[] b) Reads up to [Link] bytes of data from this input stream into an array of bytes.

read(byte[] b, int off, Reads up to len bytes of data from this input stream into an array of bytes, starting
int len) at offset off in the array.

reset() Repositions this stream to the position at which the last mark() was set.

skip(long n) Skips over and discards n bytes of data from this input stream.

Methods of FileOutputStream Class


Method Description

Closes this output stream and releases any system resources associated
close()
with this stream.

Flushes this output stream and forces any buffered output bytes to be
flush()
written out to the underlying device.

write(int b) Writes a byte to this output stream.

write(byte[] b) Writes [Link] bytes from the specified byte array to this output stream.
Method Description

Writes len bytes from the specified byte array starting at offset off to this
write(byte[] b, int off, int len)
output stream.

writeBytes(String s) Writes the specified string to this output stream.

writeChars(String s) Writes the specified string of characters to this output stream.

writeChars(String s, int off, Writes len characters from the specified string starting at offset off to this
int len) output stream.

Example
package javaprogrammingdemo;
import [Link];
import [Link];
import [Link];
import [Link].*;
public class javalabclass{
public static void main(String args[]) throws IOException{
try
{
FileInputStream fs = new FileInputStream("[Link]");
int data=[Link]();
[Link]((char)data);
[Link]();

}
catch(FileNotFoundException e)
{
[Link]("Check File");
}
}
}

I/O Handling: Input-output in Java


Java brings various Streams with its I/O package that helps the user to perform all the input-output operations.
These streams support all the types of objects, data-types, characters, files etc. to fully execute the I/O
operation.
In Java, an I/O (Input/Output) stream represents a flow of data that can be read from or written to. It acts as a
channel for transferring data between a source and a destination. The [Link] package provides various classes
to handle different types of streams.
I/O streams are categorized into two main types:
• Input Streams:
Used for reading data from a source, such as a file, network connection, or memory.
• Output Streams:
Used for writing data to a destination, such as a file, network connection, or memory.
These streams are further divided into byte streams and character streams:
• Byte Streams:
Handle data in the form of bytes, suitable for binary data like images and audio. Classes
like InputStream and OutputStream are part of this category.
• Character Streams:
Handle data in the form of characters, suitable for text data. Classes like Reader and Writer are part of this
category and they handle character encoding automatically.
Some commonly used I/O stream classes include:
• FileInputStream and FileOutputStream: For reading from and writing to files.
• BufferedInputStream and BufferedOutputStream: For efficient reading and writing using buffers.
• BufferedReader and BufferedWriter: For efficient reading and writing of text data using buffers.
• DataInputStream and DataOutputStream: For reading and writing primitive data types.
I/O streams are fundamental for performing file handling, network communication, and other data transfer
operations in Java.

Examples:
1. Reading from the console using Scanner:
java
CopyEdit
import [Link];

public class ConsoleInput {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name);
[Link]();
}
}
Common I/O Classes and Interfaces:
Interface / Class Description
InputStream, OutputStream Base classes for byte streams
Reader, Writer Base classes for character streams
File, FileReader, FileWriter File representation and read/write
BufferedReader, BufferedWriter Efficient reading/writing of text
Scanner Parses input from various sources
PrintWriter Formatted text output to file or console

Object I/O classes

Object I/O classes in Java facilitate the reading and writing of objects to and from streams. These classes are
essential for serializing and deserializing objects, which is useful for saving and retrieving object states, as
well as for transmitting objects across networks. The core classes for object I/O
are ObjectInputStream and ObjectOutputStream, both belonging to the [Link] package.
• ObjectOutputStream:
This class is used to write objects to an output stream. It takes an OutputStream as an argument in its
constructor, allowing it to write to various destinations such as files or network
sockets. The writeObject() method is used to serialize an object and write it to the stream. For an object to be
serializable, its class must implement the Serializable interface.
• ObjectInputStream:
This class is used to read objects from an input stream. It takes an InputStream as an argument in its
constructor. The readObject() method is used to deserialize an object from the stream. The object read must
have been previously written using ObjectOutputStream, and the class definition must be available.
Example
import [Link].*;
public class ObjectIOExample {
public static void main(String[] args) {
// Object to be serialized
MyClass obj = new MyClass(1, "example");
String filename = "[Link]";

// Serialization
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
[Link](obj);
[Link]("Object serialized successfully.");
} catch (IOException e) {
[Link]();
}

// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
MyClass retrievedObj = (MyClass) [Link]();
[Link]("Object deserialized successfully.");
[Link]("Retrieved object: " + retrievedObj);
} catch (IOException | ClassNotFoundException e) {
[Link]();
}
}
}

class MyClass implements Serializable {


private int id;
private String name;

public MyClass(int id, String name) {


[Link] = id;
[Link] = name;
}

@Override
public String toString() {
return "MyClass{" +
"id=" + id +
"name='" + name + '\'' +
'}';
}
}

Event Handling in Java


Event handling is fundamental to Java programming because it is used to create event driven programs eg
• Applets
• Web Application
• Event handling mechanism have been changed significantly between the original version of Java (1.0) and
all subsequent versions of Java, beginning with version 1.1.
• The modern approach to handling events is based on the delegation event model

An event is a change in the state of a • GUI based windows application


n object triggered by some action such as Clicking a button, Moving the cursor, Pressing a key on the
keyboard, Scrolling a page, etc. In Java, the [Link] package provides various event classes to handle
these actions.

Types of event handling

Events in Java can be broadly classified into two categories based on how they are generated:
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user. They are generated as
consequences of a person interacting with the graphical components in Graphical User Interface. For example,
clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list,
scrolling the page etc.

Background Events - Those events that require the interaction of end user are known as background events.
Operating system interrupts, hardware or software failure, timer expires, an operation completion are the
example of background events.

Event handling mechanism


Event Handling is the mechanism that controls the event and decides what should happen if an event occurs.
This mechanism have the code which is known as event handler that is executed when an event occurs. Java
Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate
and handle the events.. The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing information of
the occurred event to it's handler. Java provides classes for source object.

Listener - It is also known as event handler. Listener is responsible for generating response to an event. From
java implementation point of view the listener is also an object. Listener waits until it receives an event. Once
the event is received , the listener process the event an then returns.

The design goals of the event delegation model are as following:

o It is easy to learn and implement

o It supports a clean separation between application and GUI code.

o It provides robust event handling program code which is less error-prone (strong compile-time
checking)

o It is Flexible, can enable different types of application models for event flow and propagation.

o It enables run-time discovery of both the component-generated events as well as observable events.

o It provides support for the backward binary compatibility with the previous model.

Registering the Source With Listener


To handle events, the source must be registered with a listener. Java provides specific methods for
registering listeners based on the type of event.
Syntax:
addTypeListener()
For example,
• addKeyListener() for KeyEvent
• addActionListener() for ActionEvent

Event Classes and Listener Interfaces


Java provides a variety of event classes and corresponding listener interfaces.

Event Class Listener Interface Description

An event that indicates that a component-


ActionEvent ActionListener defined action occurred like a button click or
selecting an item from the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a component


ComponentEvent ComponentListener moved, the size changed or changed its
visibility.

When a component is added to a container (or)


ContainerEvent ContainerListener removed from it, then this event is generated
by a container object.

These are focus-related events, which include


FocusEvent FocusListener
focus, focusin, focusout, and blur.

An event that indicates whether an item was


ItemEvent ItemListener
selected or not.

An event that occurs due to a sequence of


KeyEvent KeyListener
keypresses on the keyboard.
Event Class Listener Interface Description

MouseListener & The events that occur due to the user


MouseEvent
MouseMotionListener interaction with the mouse (Pointing Device).

An event that specifies that the mouse wheel


MouseWheelEvent MouseWheelListener
was rotated in a component.

An event that occurs when an object’s text


TextEvent TextListener
changes.

An event which indicates whether a window


WindowEvent WindowListener
has changed its status or not.

Methods in Listener Interfaces

Each listener interface contains specific methods that must be implemented to handle events.

Listener Interface Methods

ActionListener actionPerformed()

AdjustmentListener adjustmentValueChanged()

componentResized()

componentShown()
ComponentListener
componentMoved()

componentHidden()
Listener Interface Methods

componentAdded()
ContainerListener
componentRemoved()

focusGained()
FocusListener
focusLost()

ItemListener itemStateChanged()

keyTyped()

KeyListener keyPressed()

keyReleased()

mousePressed()

mouseClicked()

MouseListener mouseEntered()

mouseExited()

mouseReleased()

mouseMoved()
MouseMotionListener
mouseDragged()

MouseWheelListener mouseWheelMoved()

TextListener textChanged()
Listener Interface Methods

windowActivated()

windowDeactivated()

windowOpened()

WindowListener windowClosed()

windowClosing()

windowIconified()

windowDeiconified()

Keyboard & Mouse Handling

In Java, handling mouse and keyboard interactions involves using event listeners. These listeners detect when
a user interacts with the application through the mouse or keyboard, triggering specific actions defined by the
programmer.

Mouse Handling

To handle mouse events, it's necessary to implement


the MouseListener and MouseMotionListener interfaces. The MouseEvent class provides information about
the mouse event, such as the coordinates of the mouse cursor and which button was pressed.

• MouseListener Interface:

• mouseClicked(MouseEvent e): Invoked when a mouse button has been clicked (pressed and
released) on a component.

• mousePressed(MouseEvent e): Invoked when a mouse button has been pressed on a


component.

• mouseReleased(MouseEvent e): Invoked when a mouse button has been released on a


component.

• mouseEntered(MouseEvent e): Invoked when the mouse cursor enters a component.

• mouseExited(MouseEvent e): Invoked when the mouse cursor exits a component.

• MouseMotionListener Interface:
• mouseDragged(MouseEvent e): Invoked when a mouse button is pressed on a component and
then dragged.

• mouseMoved(MouseEvent e): Invoked when the mouse cursor has been moved onto a
component but no buttons have been pushed.

Example

import [Link];

import [Link];

import [Link];

public class MouseHandler implements MouseListener {

public static void main(String[] args) {

JFrame frame = new JFrame("Mouse Events");

[Link](JFrame.EXIT_ON_CLOSE);

[Link](400, 300);

MouseHandler mouseHandler = new MouseHandler();

[Link](mouseHandler);

[Link](true);

@Override

public void mouseClicked(MouseEvent e) {

[Link]("Mouse Clicked at: (" + [Link]() + ", " + [Link]() + ")");

@Override
public void mousePressed(MouseEvent e) {

[Link]("Mouse Pressed at: (" + [Link]() + ", " + [Link]() + ")");

@Override

public void mouseReleased(MouseEvent e) {

[Link]("Mouse Released at: (" + [Link]() + ", " + [Link]() + ")");

@Override

public void mouseEntered(MouseEvent e) {

[Link]("Mouse Entered at: (" + [Link]() + ", " + [Link]() + ")");

@Override

public void mouseExited(MouseEvent e) {

[Link]("Mouse Exited at: (" + [Link]() + ", " + [Link]() + ")");

Keyboard Handling

For keyboard events, the KeyListener interface is used. The KeyEvent class provides details about the key
event, such as which key was pressed or released.

• KeyListener Interface:

o keyPressed(KeyEvent e): Invoked when a key has been pressed.

o keyReleased(KeyEvent e): Invoked when a key has been released.

o keyTyped(KeyEvent e): Invoked when a key has been typed.

Introduction to AWT & GUI basics


AWT (Abstract Window Toolkit) is Java's original platform-dependent GUI toolkit, providing classes and
interfaces for building user interfaces. It relies on the underlying operating system to create components,
AWT Basics
• Components: Basic building blocks like buttons, labels, text fields, and checkboxes.
• Containers: Objects that hold components, such as windows, frames, panels, and dialogs.
• Layout Managers: Control the arrangement of components within containers.
• Event Handling: Mechanism for responding to user interactions like clicks and key presses.
GUI Creation Steps
• Create a Frame: The main window of the application.
Frame frame = new Frame("My AWT App");
• Add Components: Create and add components to the frame or other containers.
Button button = new Button("Click Me");
[Link](button);
• Set Layout: Choose a layout manager to arrange components.
[Link](new FlowLayout()); // Example using FlowLayout
• Handle Events: Implement listeners to respond to user interactions.
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}
});
• Set Size and Visibility: Define the frame's size and make it visible.
[Link](300, 200);
[Link](true);

Java AWT Hierarchy


• Components: AWT provides various components such as buttons, labels, text fields, checkboxes, etc
used for creating GUI elements for Java Applications.
• Containers: AWT provides containers like panels, frames, and dialogues to organize and group
components in the Application.
• Layout Managers: Layout Managers are responsible for arranging data in the containers some of the
layout managers are BorderLayout, FlowLayout, etc.
• Event Handling: AWT allows the user to handle the events like mouse clicks, key presses, etc. using
event listeners and adapters.
• Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images and write text
in the components of a Java Application.
Types of Containers in Java AWT(AWT controls)
There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or dialog box. The
Window class extends the Container class, which means it can contain other components, such as
buttons, labels, and text fields.

2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for grouping
other components together within a window or a frame.

3. Frame: The Frame is the container that contains the title bar and border and can have menu bars.

4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.
Java AWT Label

Syntax of AWT Label


public class Label extends Component implements Accessible
AWT Label Class Constructors
There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
Java AWT Button
AWT Button is a control component with a label that generates an event when clicked on. Button Class is
used for creating a labeled button that is platform-independent.
Syntax of AWT Button
public class Button extends Component implements Accessible

Java AWT Button Class Constructors


There are two types of Button class constructors as mentioned below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click Here” button with show click here as
the value.
3. Java AWT TextField
Syntax of AWT TextField:
public class TextField extends TextComponent

TextField Class constructors


There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns (col).

Java AWT Checkbox


Syntax of AWT Checkbox:
public class Checkbox extends Component implements ItemSelectable, Accessible
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.

Java AWT CheckboxGroup


CheckboxGroup Class is used to group together a set of Checkbox.
Syntax of AWT CheckboxGroup:
public class CheckboxGroup extends Object implements Serializable
Note: CheckboxGroup enables the use of radio buttons in AWT.

Java AWT Choice


The object of the Choice class is used to show a popup menu of choices.
Syntax of AWT Choice:
public class Choice extends Component implements ItemSelectable, Accessible
AWT Choice Class constructor
Choice(): It creates a new choice menu.

Java AWT List


The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable, Accessible
AWT List Class Constructors
The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.

Java AWT Canvas


Syntax of AWT Canvas:
public class Canvas extends Component implements Accessible
Canvas Class Constructors
1. Canvas():
Creates new Canvas.
2. Canvas(GraphicConfiguration config):
It creates a new Canvas with the given Graphic configuration.
Java AWT MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu. The MenuItem class allows you to create
individual items that can be added to menus. And Menu is a component used to create a dropdown menu
that can contain a list of MenuItem components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Accessible
Syntax of Java AWT Menu
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT PopupMenu is a component that is used for dynamically popping up a menu that appears when
the user right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible

Java AWT Panel


Java AWT Panel is a container class used to hold and organize graphical components in a Java
Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible
Java AWT Toolkit
Java AWT Toolkit class provides us with a platform-independent way to access various system resources
and functionalities. Subclasses of Toolkit are used to bind various components.
Syntax of Java AWT Toolkit
public abstract class Toolkit extends Object
AWT Controls – Frames, Panels, Layout Managers & Other Controls

Java AWT (Abstract Window Toolkit) provides a set of GUI components for building graphical user
interfaces. Frames are top-level windows that act as the main container for AWT components. Panels are
generic containers used to group components inside frames. Layout Managers control how components are
arranged in a container (e.g., FlowLayout, BorderLayout). AWT also includes various controls like Buttons,
Labels, TextFields, and Checkboxes, allowing user interaction. These components are added to Frames or
Panels and arranged using Layout Managers to create complete GUI applications.

1 Frame Example

A Frame in AWT is a top-level window with a title bar and borders, much like any standalone application
window. It acts as the main container for all other components like buttons, labels, and panels. A frame can
be resized, minimized, maximized, and closed. It is created using the Frame class and must be made visible
using setVisible(true).

Key Methods:

• setTitle(String): Sets the title.

• setSize(int, int): Sets window dimensions.

• add(Component): Adds GUI components.

• setLayout(LayoutManager): Defines how components are arranged.

Example

import [Link].*;
public class FrameExample {
public static void main(String[] args) {
Frame f = new Frame("AWT Frame Example");
[Link](300, 200);
[Link](true);
}
}
2. Panel
A Panel is a lightweight container that cannot exist on its own. It must be added to another container (usually
a Frame). Panels are used to organize and group components. They are helpful when you want to apply a
layout to part of the window independently from the rest.

Key Use Case: If your window has multiple sections (like top for title, center for form, bottom for buttons),
each section could be a panel.

import [Link].*;
public class PanelExample {
public static void main(String[] args) {
Frame f = new Frame("AWT Panel Example");
Panel p = new Panel();
[Link]([Link]);

Button b = new Button("Click Me");


[Link](b); // add button to panel

[Link](p); // add panel to frame


[Link](300, 200);
[Link](true);
}
}.

3. Layout Manager
Layout Managers are used to control the placement and sizing of components inside containers. They save
developers from calculating exact coordinates for each control, making the GUI more flexible across
screen sizes.

Types of Layout Managers:

• FlowLayout: Places components in a row, wraps to next line as needed.


• BorderLayout: Divides the container into 5 regions (N, S, E, W, Center).

• GridLayout: Arranges components in a grid (rows × columns).

• GridBagLayout: Complex layout allowing flexible positioning.

Without a layout manager, components must be positioned manually, which is error-prone and not
recommended.

Example (FlowLayout)
import [Link].*;
public class LayoutExample {
public static void main(String[] args) {
Frame f = new Frame("AWT Layout Example");
[Link](new FlowLayout()); // Set FlowLayout

[Link](new Button("Button 1"));


[Link](new Button("Button 2"));
[Link](new Button("Button 3"));

[Link](300, 200);
[Link](true);
}
}
Layout Manager Example (FlowLayout)

import [Link].*;

public class LayoutExample {

public static void main(String[] args) {

Frame f = new Frame("AWT Layout Example");

[Link](new FlowLayout()); // Set FlowLayout

[Link](new Button("Button 1"));


[Link](new Button("Button 2"));

[Link](new Button("Button 3"));

[Link](300, 200);

[Link](true);

4. Other Controls Example (Button, Label, TextField)

AWT offers several ready-made GUI controls:

Control Description
Button Triggers an action when clicked.
Label Displays a non-editable text string.
TextField Single-line editable text input.
TextArea Multi-line text area for larger input.
Checkbox Selectable on/off box.
Choice Drop-down menu for selecting one item.
List List box that allows single/multiple selections.

Example

import [Link].*;

public class ControlsExample {

public static void main(String[] args) {

Frame f = new Frame("AWT Controls Example");

Label l = new Label("Name:");

TextField tf = new TextField(20);

Button b = new Button("Submit");

[Link](new FlowLayout());
[Link](l);

[Link](tf);

[Link](b);

[Link](300, 200);

[Link](true);

Common questions

Powered by AI

Java uses synchronization to prevent race conditions by allowing only one thread at a time to access critical code sections. Methods or code blocks can be synchronized using the "synchronized" keyword, ensuring mutually exclusive access. This avoids concurrent modifications leading to data corruption or inconsistency .

Java ensures uniqueness and functionality through attributes (state), methods (behavior), and constructors (identity). Attributes define properties like "name" or "age", methods describe behaviors like "display", and constructors initialize objects uniquely. This is crucial in OOP as it allows objects to represent real-world entities accurately and interact meaningfully .

Thread priority in Java allows developers to suggest the urgency or importance of a task. However, its impact depends on the system's thread scheduler. Higher priority suggests more CPU time but doesn't guarantee execution order, helping in applications where resource allocation hints can optimize performance .

Constructor overloading involves having multiple constructors with different parameters for initializing objects in various ways, allowing flexibility in object creation. Method overloading allows multiple methods with the same name but different parameters, enabling the same method to perform differently based on input. Both enhance flexibility and reusability within a class .

Exception handling increases program stability by allowing the program to manage unexpected events without crashing, using try-catch blocks to handle known and unknown errors gracefully. It streamlines debugging and error management, allowing developers to separate error handling from business logic, promoting cleaner and more maintainable code .

Instance blocks (or initialization blocks) are used to initialize instance variables and execute every time an object is created, supporting repetitive setup tasks. Static blocks initialize static variables and are executed once when the class is loaded, useful for setting constant values or complex initializations .

The "this" keyword resolves naming conflicts by referencing the current object's instance variables, distinguishing them from method parameters or local variables with the same names. This avoids ambiguity and ensures correct variable references within constructors and methods .

Static blocks are executed once when the class is loaded, typically for static initialization, like setting a class-wide value. Static methods can be called without creating class instances, enabling operations that don't depend on instance-specific data. Together, they support initialization and utility functions independent of object instantiation .

Using the "Runnable" interface allows a class to extend another class as well, promoting single inheritance principle, essential for maintaining design flexibility. It also separates thread tasks from the thread management. Extending "Thread" limits inheritance but allows customizing the thread itself. This distinction is critical based on application needs .

The "main()" method is the entry point of any Java application and must be declared as "public static void main(String args[])" because it needs to be accessible from outside its class, must be static so the Java Virtual Machine (JVM) can invoke it without creating an instance of the class, and returns nothing hence void. The arguments array allows for command-line parameters to be passed .

You might also like