Java Object-Oriented Programming Syllabus
Java Object-Oriented Programming 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.
• 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.
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.
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.
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.
• 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.
• 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 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.
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.
“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
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.
Basis
[Link] C C++ Java
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:
• An interpreter/loader (Java),
• A compiler (javac),
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.
• 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
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.
PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.
7) Execution Engine
It contains
1. A virtual processor
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.
JAVA PACKAGES
Packages are Java’s way of grouping a variety of classes and / or interfaces together. The grouping isusually
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
• Packages provide a way to “hide” classes thus preventing other programs or packages from
• 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 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
Package name
Contents
[Link]
and exceptions.
[Link]
Language utility
classes
such
as
vectors,hash
tables,randomnumbers,date, etc.,
[Link]
the input
[Link]
interface(GUI).
andsoon.
[Link]
internet servers.
[Link]
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:
• 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:
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 [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:
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:
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:
int id;
double percentage;
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:
Example:
//statements
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
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
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)
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.
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.
• 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.
MyVariable
MYVARIABLE
myvariable
x
_myvariable
$myvariable
sum_of_array
geeks123
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:
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
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
• 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.
• Semicolon (;): It is the symbol that can be found at end of the statements. It
• 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
// [Link]
if ([Link] == 0)
else
}
}
• 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.
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.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
import [Link].*;
class GFG
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:
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:
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;
[Link](myNum);
Example:
Syntax:
int intVar;
[Link](myNum);
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;
[Link](myNum);
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;
[Link](myNum);
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.
[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;
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.
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.
• 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.
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.
Declaration Syntax:
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;
• 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
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)
boolean A data type that can only store true or false values
byte A data type that can store whole numbers from -128 and 127
double A data type that can store fractional numbers from 1.7e−308 to 1.7e+308
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
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
native Specifies that a method is not implemented in the same Java source file (but
in another language)
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
strictfp Obsolete. Restrict the precision and rounding of floating point calculations
synchronized A non-access modifier, which specifies that methods can only be accessed by
one thread at a time
All the classes, interfaces, packages, methods and fields of Java programming language are given according
to the Java naming convention.
The following table shows the popular conventions used for the different identifiers.
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.
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.
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:
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
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.
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;
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.
• 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.
• 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.
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.
if(condition) {
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
• 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.
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.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
Else {
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: -
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:-
//block of statements
Example
import [Link].*;
class Geeks {
}
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:
// code to be executed
Example
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
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
1. Break statement.
2. Continue statement.
3. Return Statement.
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
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:
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.
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);
UNIT 2
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.
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.
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:
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:
• 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 :-
Accessing object :-
Example:
The main differences between class and object in Java are as follows:
Class Object
No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.
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.
• Access modifiers can be used in constructor declaration to control its access i.e which other class can
call the constructor.
• Copy Constructor
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.
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
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
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]()
Use of constructor
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.
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
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
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 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
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 :-
//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()
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
30
60
31.0
Types of Method
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 :-
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.
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(),
Math Methods :-
The [Link] class contains various methods for performing basic numeric operations
Method Description
sqrt Returns the correct rounded positive square root of a double value
pow Returns(pow(a,b)) the value of ab
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
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).
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
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.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.
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:
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.
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.
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
It is a data structure used to store data in a grid-like format with rows and columns.
• Each element is accessed using two indices – one for the row and one for the column.
// 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];
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];
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.");
}
}
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.
String s="welcome";
By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
Example
// String length
[Link]("Length of name: " + [Link]());
}
}
Output
Hello, John!
Length of name: 4
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
Examples
Method 1: Extending the Thread Class
// File: [Link]
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.
// Set priorities
[Link](Thread.MIN_PRIORITY); // Low priority (1)
[Link](Thread.MAX_PRIORITY); // High priority (10)
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.
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
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.
try {
catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}
}
}
Output
ArithmeticException => / by zero
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
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
class Main {
// declareing the type of exception
public static void findFile() throws IOException {
class Geeks {
// Main method
public static void main(String args[]) {
// Main try block
try {
// Initializing array
int a[] = { 1, 2, 3, 4, 5 };
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 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 {
The File class has many useful methods for creating and getting information about files. For example:
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
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
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
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].*;
[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);
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(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.
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(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.
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");
}
}
}
Examples:
1. Reading from the console using Scanner:
java
CopyEdit
import [Link];
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]();
}
}
}
@Override
public String toString() {
return "MyClass{" +
"id=" + id +
"name='" + name + '\'' +
'}';
}
}
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.
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.
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.
Each listener interface contains specific methods that must be implemented to handle events.
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()
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
• MouseListener Interface:
• mouseClicked(MouseEvent e): Invoked when a mouse button has been clicked (pressed and
released) on 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];
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 300);
[Link](mouseHandler);
[Link](true);
@Override
@Override
public void mousePressed(MouseEvent e) {
@Override
@Override
@Override
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:
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
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:
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]);
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.
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](300, 200);
[Link](true);
}
}
Layout Manager Example (FlowLayout)
import [Link].*;
[Link](300, 200);
[Link](true);
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].*;
[Link](new FlowLayout());
[Link](l);
[Link](tf);
[Link](b);
[Link](300, 200);
[Link](true);
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 .