java notes2
java notes2
. Narrow Type Casting:- The process of downsizing a bigger data type into a smaller one is known as
compiler. They are also known as the fundamental building blocks of the program. Tokens can be narrowing type casting. Casting up or explicit type casting are other names for it. It doesn’t just happen
classified as follows: 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.
Keywords:- Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program
Identifiers :- Identifiers are used as the general terminology for naming of variables, functions and arrays 4 Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of
the same type in a single variable. They are useful for storing and managing collections of data. Arrays in
Constants :- Constants are also like normal variables. But the only difference is, their values cannot be
Java are objects, which makes them work differently from arrays in C/C++ in terms of memory
modified by the program once they are defined
management. For primitive arrays, elements are stored in a contiguous memory location, For non-
Operators:- Java provides many types of operators which can be used according to the need. They are primitive arrays, references are stored at contiguous locations, but the actual objects may be at different
classified based on the functionality they provide. locations in memory.
Separators:- Separators are used to separate different parts of the codes. It tells the compiler about Key features of Arrays:
completion of a statement in the program. The most commonly and frequently used separator in java is
. Contiguous Memory Allocation (for Primitives): Java array elements are stored in continuous memory
semicolon (;)
locations, which means that the elements are placed next to each other in memory.
Instance Scope: Variables declared within a class but outside any method, constructor, or block are 5. strings :- In Java, a String is the type of object that can store a sequence of characters enclosed by
instance variables. Each object has its own copy of instance variables. double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the
same as an array of characters. Java provides a robust and flexible API for handling strings, allowing for
Class (Static) Scope: Variables declared with the static keyword within a class but outside any method,
various operations such as concatenation, comparison, and manipulation.
constructor, or block are class variables (static variables
string buffer classes:- The StringBuffer class in Java represents a sequence of characters that can be
modified, which means we can change the content of the StringBuffer without creating a new object
3. typecasting:- Typecasting in Java is the process of converting one data type to another data type using every time. It represents a mutable sequence of characters.
the casting operator. When you assign a value 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 6. vectors :- The Vector class in Java implements a growable array of objects. Vectors were legacy classes,
type. but now it is fully compatible with collections. It comes under java.util package and implement the List
interface.
Syntax:- <datatype> variableName = (<datatype>) value;
Key Features of Vector:
There are two types of Type Casting in java:
. It expands as elements are added.
. Widening Type Casting:- A lower data type is transformed into a higher one by a process known as
widening type casting. Implicit type casting and casting down are some names for it. It occurs naturally. . Vector class is synchronized in nature means it is thread-safe by default.
Since there is no chance of data loss, it is secure. Widening Type casting occurs when:
. Like an ArrayList, it maintains insertion order.
import java.io.*;
8. Constructors:- In Java, constructors play an important role in object creation. A constructor is a special
class Geeks{
block of code that is called when an object is created. Its main job is to initialize the object, to set up its
internal state, or to assign default values to its attributes. This process happens automatically when we Geeks() {
use the “new” keyword to create an object.
System.out.println("Default constructor");
Characteristics of Constructors:
}
. Same Name as the Class: A constructor has the same name as the class in which it is defined.
public static void main(String[] args)
. No Return Type: Constructors do not have any return type, not even void. The main purpose of a
{
constructor is to initialize the object, not to return a value.
Geeks hello = new Geeks();
. Automatically Called on Object Creation: When an object of a class is created, the constructor is called
automatically to initialize the object’s attributes. }
E.g }
import java.io.*;
class Geeks {
}
TYPES OF CONSTRUCTOR:-
}
class GFG . Compile-time polymorphism in Java: Constructor overloading is an example of compile-time
polymorphism. The appropriate constructor is selected depending on the arguments provided during
{
object instantiation.
public static void main(String[] args)
. Improved code readability and reusability: By providing different constructors, developers can offer
{ multiple ways of initializing an object, making the code easier to read and more reusable.
} int year;
} Car() {
model = "Unknown";
3. Copy Constructor:- Unlike other constructors copy constructor is passed with another object year = 0;
which copies the data available from the passed object to the newly created object.
}
e.g
Car(String model, int year) {
this.model = model;
4.Java Methods:- Java Methods are blocks of code that perform a specific task. A method allows us to
this.year = year;
reuse code, improving both efficiency and organization. All methods in Java must belong to a class.
Methods are similar to functions and expose the behavior of object. }
}
7.garbage collection:- Garbage collection in Java is an automatic memory management process that
helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual }
Machine (JVM). When Java programs run on the JVM, objects in the heap are created, which is a portion
of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage Protected – The protected access modifier is specified using the keyword protected. The methods or
collector finds these unused objects and deletes them to free up memory. data members declared as protected are accessible within the same package or subclasses in different
packages.
Two types of garbage collection activities usually happen in Java. These are:
public class A {
. Minor or incremental Garbage Collection (GC): This occurs when unreachable objects in the Young
Generation heap memory are removed. protected void display() {
. Major or Full Garbage Collection (GC): This happens when objects that survived minor garbage System.out.println("GeeksforGeeks");
collection are removed from the Old Generation heap memory. It occurs less frequently than minor }
garbage collection.
}
Public – The public access modifier is specified using the keyword public.
8. visibility control: public, private, protected, default, private protected :- In Java, access modifiers are
essential tools that define how the members of a class, like variables, methods, and even the class itself The public access modifier has the widest scope among all other access modifiers.
can be accessed from other parts of our program. They are an important part of building secure and Classes, methods, or data members that are declared as public are accessible from everywhere in the
modular code when designing large applications. Understanding default, private, protected, and public program. There is no restriction on the scope of public data members.
access modifiers is essential for writing efficient and structured Java programs
package p1;
There are 4 types of access modifiers available in Java:
public class A {
Default – When no access modifier is specified for a class, method, or data member, it is said to have the
default access modifier by default. This means only classes within the same package can access it. public void display() {
{ }
void display() }
System.out.println("Hello World!"); 9. Inheritance: concept of inheritance , types of Inheritance: single inheritance, multilevel inheritance,
hierarchical inheritance:– It is the mechanism in Java by which one class is allowed to inherit the
} features(fields and methods) of another class. In Java, Inheritance means creating new classes based on
} existing ones. A class that inherits from another class can reuse the methods and fields of that class. In
addition, you can add new fields and methods to your current class as well
Inheritance promotes code reusability, method overriding, and polymorphism, which makes the Java
Private – The private access modifier is specified using the keyword private. The methods or data program more modular and efficient.
members declared as private are accessible only within the class in which they are declared.
1. Single Inheritance – In single inheritance, a sub-class is derived from only one super class. It class One {
inherits the properties and behavior of a single-parent class. Sometimes, it is also known as
2.Multilevel Inheritance:–– In Multilevel public void print_geek() {
simple inheritance
Inheritance, a derived class will be inheriting a
base class, and as well as the derived class also System.out.println("Geeks");
class One {
acts as the base class for other classes. In the }
public void print_geek() below image, class A serves as a base class for
the derived class B, which in turn serves as a }
{
base class for the derived class C. In Java, a class
class Two extends One {
System.out.println("Geeks"); cannot directly access the grandparent’s
members if they are private. public void print_for() {
}
System.out.println("for");
}
}
class Two extends One {
}
public void print_for() { System.out.println("for"); }
class Three extends Two {
}
public void print_lastgeek() {
public class Main {
System.out.println("Geeks");
public static void main(String[] args)
}
{
}
Two g = new Two();
public class Main {
g.print_geek();
public static void main(String[] args) {
g.print_for();
Geeks Three
g.print_geek();
for Three g = new Three();
}
Geeks g.print_geek();
}
g.print_for();
Three Geeks
g.print_lastgeek(); for
} Geeks
}
3.Hierarchical Inheritance :–– In Hierarchical class A { 4.Multiple Inheritance:–– In
Inheritance, one class serves as a superclass Multiple inheritances, one class interface Coder {
(base class) for more than one subclass. In the public void print_A() { System.out.println("Class A"); } can have more than one
below image, class A serves as a base class for superclass and inherit features void writeCode();
}
the derived classes B, C, and D. from all parent classes. Please }
class B extends A { note that Java does not support
multiple inheritances with interface Tester { void testCode();
public void print_B() { System.out.println("Class B"); }
classes. In Java, we can achieve
}
} multiple inheritances only
through Interfaces. In the image class DevOpsEngineer implements Coder, Tester {
class C extends A {
below, Class C is derived from
@Override
public void print_C() { System.out.println("Class C"); } interfaces A and B.
public void writeCode() {
}
System.out.println("DevOps Engineer writes automation scripts.");
class D extends A {
}
public void print_D() { System.out.println("Class D"); }
@Override
}
public void testCode() {
public class Test {
System.out.println("DevOps Engineer tests deployment pipelines.");
public static void main(String[] args)
}
{
DevOpsEngineer
B obj_B = new B();
public void deploy() {
obj_B.print_A();
System.out.println("DevOps Engineer deploys code to cloud.");
obj_B.print_B();
}
C obj_C = new C();
}
obj_C.print_A();
public class Main {
obj_C.print_C(); Class A
public static void main(String[] args) {
Class B
DevOpsEngineer devOps = new DevOpsEngineer();
D obj_D = new D(); Class A
obj_D.print_A(); Class C
devOps.writeCode();
obj_D.print_D(); Class A
devOps.testCode();
} Class D
devOps.deploy();
}
}
}
4.Hybrid Inheritance:–– It is a mix of two or more of the above types of inheritance. Since Java doesn’t 10.method overriding:–– Overriding in Java occurs when class Animal {
support multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also not a subclass or child class implements a method that is
possible with classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to already defined in the superclass or base class. When a void move() { System.out.println(
involve multiple inheritance to implement Hybrid inheritance. subclass provides its own version of a method that is "Animal is moving."); }
already defined in its superclass, we call it method
class SolarSystem { overriding. The subclass method must match the parent void eat() { System.out.println(
class method’s name, parameters, and return type.
} "Animal is eating."); }
Rules for Overriding:
class Earth extends SolarSystem { }
. Name, parameters, and return type must match the
} class Dog extends Animal {
parent method.
class Mars extends SolarSystem { @Override void move()
. Java picks which method to run, based on the actual
} object type, not just the variable type. {
public class Moon extends Earth { . Static methods cannot be overridden. System.out.println("Dog is running.");
public static void main(String args[]) . The @Override annotation catches mistakes like typos }
in method names.
{ void bark() { System.out.println("Dog is barking."); }
SolarSystem s = new SolarSystem(); }
Earth e = new Earth(); public class Geeks {
11. final Keyword in Java:–– The final Keyword in Java is
Mars m = new Mars(); public static void main(String[] args)
used as a non-access modifier applicable to a variable, a
System.out.println(s instanceof SolarSystem); method, or a class. It is used to restrict a user in Java. We {
cannot use the final keyword in a block. It restricts the
System.out.println(e instanceof Earth); user from accessing that particular part of the program, Dog d = new Dog();
System.out.println(m instanceof SolarSystem); such as restricting the modification and inheriting the d.move(); // Output: Dog is running.
properties from the parent class or overloading.
} d.eat(); // Output: Animal is eating.
} d.bark(); // Output: Dog is barking.
}
12. Super Keyword in Java:–– The super keyword in Java is a reference variable that is used to refer to 15.Package: Define package, types of package, naming and creating package, accessing package:––
the parent class when we are working with objects. You need to know the basics of Inheritance and
In Java, a package serves as a namespace that organizes related classes and interfaces. It provides a way
Polymorphism to understand the Java super keyword.
to group related classes, interfaces, and sub-packages, similar to folders in a file system. Packages help to
13. What is Abstract Class in Java:–– Java abstract class is a class that can not be instantiated by itself, it prevent naming conflicts, control access to classes, and organize code.
needs to be subclassed by another class to use its properties. An abstract class is declared using the
Types of Packages
“abstract” keyword in its class definition.
a) Built-in Packages (Predefined Packages):- These packages consist of a large number of classes
abstract class Shape
which are a part of Java API. Java comes with many built-in packages. Some commonly used
{ ones include:
14. Define interface, implementing interface, accessing interface variables and methods, extending
interfaces:––
In Java, an interface is a blueprint of a class, specifying a set of abstract methods that a class must b)User-defined Packages:- These are the packages that are defined
implement. It defines a contract for classes to adhere to, ensuring they provide specific functionalities. by the user.user can define their own packages. Creating a package
A class implements an interface using the implements keyword, providing concrete implementations for 16.import Statement in Java:- The import statement allows you to public class MyClass {
all the abstract methods declared in the interface. If a class does not implement all methods, it must be use classes and interfaces from other packages without needing to
public void display() {
declared abstract. use their fully qualified names.
interface Drawable {
System.out.println("Hello from MyClass in
Accessing Interface Variables and Methods import package_name.ClassName;
void draw(); mypackage!");
Variables: import package_name.*;
} }
Interface variables are implicitly public, static, and final (constants). They are class Circle implements Drawable { static import in Java:- The static import feature allows you to
}
accessed using the interface name. import static members (fields and methods) of a class so you can
@Override
use them without class qualification.
Methods: public void draw() {
Interface methods are implicitly public and abstract (prior to Java 8). They are System.out.println("Drawing circle");
accessed through objects of the class that implements the interface. }
Extending Interfaces: }
Compile Time Errors are those errors which prevent the code from running because of an incorrect // Code to handle the exception
syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. }
These errors are detected by the java compiler and an error message is displayed on the screen while
compiling. Compile Time Errors are sometimes also referred to as Syntax errors. 20. throws and finally statement:-
18.what is exception:- An exception in Java is an event that occurs during the execution of a program The throws keyword is used in a method declaration to indicate that the method might throw one or
that disrupts the normal flow of instructions. It typically occurs due to runtime errors such as dividing by more exceptions. This informs the caller that it must handle (or further declare) the exception.
zero, accessing an invalid index in an array, or trying to open a file that doesn’t exist. When such events returnType methodName() throws ExceptionType1, ExceptionType2 {
happen, Java creates an object of the exception class and throws it, which can then be caught and
handled by the program. // code that may throw exception
Exception handling in Java is an effective mechanism for managing runtime errors to ensure the }
application’s regular flow is maintained. Some Common examples of exceptions include
2. finally Block in Java
ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these
exceptions, Java enables developers to create robust and fault-tolerant applications. The finally block is used to execute important code such as resource cleanup, regardless of whether an
exception was thrown or caught. It always executes after the try and catch blocks.
Types of Exceptions
try {
Checked Exceptions
// code that may throw an exception
These are checked at compile-time.
} catch (Exception e) {
The compiler forces the programmer to handle them using try-catch or by declaring them with
throws. // code to handle the exception
These typically occur due to external factors like file I/O, database access, etc. } finally {
Built-in exceptions are part of Java’s standard library and cover most common programming and runtime
errors. These exceptions are defined in the java.lang.
Checked Exceptions:- These are checked at compile time, and the programmer is forced to handle them.
Unchecked Exceptions (Runtime Exceptions):- These are not checked at compile time, and occur due to
programming errors.
In a multithreaded environment, multiple threads may access and modify shared data simultaneously,
22. Multithreaded Programming in Java:-
leading to race conditions. To avoid this, synchronization is used to ensure that only one thread can
Multithreading is the ability of a CPU to execute multiple tasks (threads) concurrently. In Java, access the critical section of code at a time.
multithreading allows a program to perform multiple operations at once, such as handling user input
Synchronized Methods: You can use the synchronized keyword to prevent multiple threads from
while processing data in the background.
accessing a method at the same time.
java provides two main ways to create threads: by extending the Thread class and by implementing the
Runnable interface. Let's break down the concepts into simpler steps.
23. Component: The superclass for all AWT components (e.g., Button, Label).
Life Cycle of a Thread
Container: A subclass of Component that can hold other components (e.g., Panel, Frame).
A thread in Java goes through several states during its life cycle:
Window: A top-level window with no borders or menu bar.
1. New: A thread is in this state when it is created but not yet started.
Frame: A top-level window with borders, title, and buttons (minimize, maximize, close).
2. Runnable: When the start() method is called, the thread enters the runnable state, ready for
execution. Panel: A generic container for organizing components, often used inside Frames.
4. Waiting: A thread enters the waiting state when it is waiting indefinitely for another thread to AWT Controls:-
perform a specific action.
Label
5. Timed Waiting: When a thread is waiting for a specified period (using methods like sleep()).
Used to display a single line of read-only text.
6. Terminated: A thread reaches this state when it has completed its execution.
Button
Checkbox
Default for Panel. . Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and Applets
Places components in a row, wraps to next line if needed. . It Employs model/view design architecture.
b. BorderLayout . Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.
c. GridLayout
d. GridBagLayout
b. FileDialog
Introduction to swing:-
Swing is a part of Java's Java Foundation Classes (JFC) and provides a rich set of GUI components for
building platform-independent desktop applications. It is built on top of the older Abstract Window
Toolkit (AWT) but offers more sophisticated components like tables, trees, sliders, tabbed panes, and
more. Unlike AWT, which relies on native system components, Swing components are written entirely in
24.Basic Swing Components
JLabel is used to display a short string or an image icon. An event is a change in the state of an object triggered by some action such as Clicking a button, Moving
the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java, the java.awt.event package
2. TextField
provides various event classes to handle these actions.
JTextField allows single-line text input.
Events in Java can be broadly classified into two categories based on how they are generated:-
3. ComboBox
Foreground Events: Foreground events are the events that require user interaction to generate.
JComboBox lets users choose from a drop-down list. Examples of these events include Button clicks, Scrolling the scrollbar, Moving the cursor, etc.
4. Button Background Events: Events that don’t require interactions of users to generate are known as background
events. Examples of these events are operating system failures/interrupts, operation completion, etc.
JButton is a push button used to trigger an action.
Event Handling Mechanism
5. Checkbox
Event handling is a mechanism that allows programs to control events and define what should happen
JCheckBox allows the user to make multiple selections. when an event occurs. Java uses the Delegation Event Model to handle events. This model consists of
6. RadioButton two main components:
JRadioButton allows a single selection within a group. Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
Advanced Swing Components
1. Tabbed Panes 25.event classes are part of the Event Delegation Model, which allows GUI components to communicate
JTabbedPane lets you switch between tabs. user actions (like clicks, typing, or selection) to the program. Each type of user interaction is represented
by a specific event class in the java.awt.event package
2. Scroll Panes
1. ActionEvent Class
JScrollPane adds scrollbars to components like text areas, panels, or tables.
Triggered by: Buttons, menu items, and other components like JButton, JMenuItem.
3. Trees
Listener interface: ActionListener
JTree displays a hierarchical tree structure.
public void actionPerformed(ActionEvent e)
4. Tables
2. ItemEvent Class
JTable is used for displaying tabular data.
Triggered by: Checkbox, radio buttons, combo boxes when an item is selected or deselected.
5. Progress Bar
Listener interface: ItemListener
JProgressBar visually shows the progress of a task.
public void itemStateChanged(ItemEvent e)
6. Tool Tips
3. KeyEvent Class
Tool tips provide helpful text when the user hovers over a component.
Triggered by: Keyboard actions like typing or pressing keys.
Listener interface: KeyListener 3. KeyListener
Triggered by: Mouse actions (click, press, release, move, drag). void keyTyped(KeyEvent e);
public void mouseClicked(MouseEvent e) Used for: Mouse actions like clicking, entering, or exiting a component.
Triggered by: Text components like TextField, TextArea when text changes. void mouseExited(MouseEvent e);
public void textValueChanged(TextEvent e) Used for: Detecting mouse movement and dragging.
26.event listener interfaces are used to handle different types of user interactions in GUI applications. void mouseMoved(MouseEvent e);
These interfaces belong to the java.awt.event package and are implemented to listen for specific events
void mouseDragged(MouseEvent e);
like button clicks, key presses, mouse movements, etc.
6. TextListener
1. ActionListener
Used for: Detecting changes in text components like TextField or TextArea.
Used for: Handling actions like button clicks, menu item selections, etc.
Event Class: TextEvent
Event Class: ActionEvent
void textValueChanged(TextEvent e);
void actionPerformed(ActionEvent e);
2. ItemListener
Used for: Item state changes in components like checkboxes, radio buttons, or combo boxes.