JAVA
JAVA
Object-oriented programming (OOP) offers numerous benefits in Java, primarily revolving around
modularity, reusability, maintainability, and scalability. OOP in Java promotes a more organized
and efficient approach to software development, especially for large and complex projects.
Modularity:
OOP divides programs into smaller, self-contained units called objects, making it easier to
manage and troubleshoot complex systems. Each object can be developed and tested
independently, simplifying the development process.
Reusability:
OOP enables code reusability through inheritance, where new classes can inherit properties and
methods from existing classes. This reduces redundancy and saves development time.
Maintainability:
OOP principles like encapsulation and abstraction make code easier to understand, modify, and
debug. Changes in one part of the system are less likely to affect other parts, simplifying
maintenance.
Productivity:
OOP principles, such as inheritance and code reusability, enhance developer productivity by
allowing them to build applications faster with less code.
Flexibility:
Polymorphism allows for different objects to be treated in the same way through a common
interface, providing flexibility in code design.
2) TYPE-CASTING
Typecasting in Java is the process of converting one data type to another data type using 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 type.
Syntax:
<datatype> variableName = (<datatype>) value;
EX:
// Java program to demonstrate Widening TypeCasting
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 10;
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 every time. It
represents a mutable sequence of characters.
EX:
//Demonstrating String Buffer
public class Geeks {
public static void main(String[] args){
// Creating StringBuffer
StringBuffer s = new StringBuffer();
Java's built-in exception handling classes are organized in a hierarchy, with Throwable at the root.
It has two main subclasses: Error and Exception. Error represents serious problems that
applications usually shouldn't try to handle, while Exception represents conditions that a program
might be able to recover from. Exception has two main categories: checked and unchecked
exceptions.
*Exception handling in Java allows developers to manage runtime errors effectively by using
mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling,
etc.
*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.
*Exception in Java is an error condition that occurs when something wrong happens during the
program execution.
5) WEB-APPLETS,STAND ALONE
Web Applet:
A small Java program that runs in a web browser. It is typically embedded in an HTML page and
executed on the client side.
Stand-Alone Application:
A full-fledged Java program that runs directly on a Java Virtual Machine (JVM) without the need
for a browser.
6) FEATURES OF JAVA
Simple Syntax:
Java syntax is very straight forward and very easy to learn. Java removes complex features like
pointers and multiple inheritance, which makes it more beginner friendly.
Object Oriented:
Java is a pure object-oriented language. It supports core OOP concepts like
*Class
*Objects
*Inheritance
*Encapsulation
*Abstraction
*Polymorphism
Platform Independent:
*Java is platform-independent because of Java Virtual Machine (JVM).
*When we write Java code, it is first compiled by the compiler and then converted into bytecode
(which is platform-independent).
This byte code can run on any platform which has JVM installed.
Interpreted:
*Java code is not directly executed by the computer. It is first compiled into bytecode. This byte
code is then understand by the JVM. This enables Java to run on any platform without rewriting
code.
Scalable:
*Java is able to handle both small and large-scale applications, features like multithreading and
distributed computing allows developers to manage loads more efficiently.
Multithreading:
*Multithreading in Java allows multiple threads to run at the same time.
*It improves CPU utilization and enhancing performance in applications that require concurrent
task execution.
*Multithreading is especially important for interactive and high-performance applications, such as
games and real-time systems.
*Java provides build in support for managing multiple threads. A thread is known as the smallest
unit of execution within a process.
Portable:
*Java Byte code can be executed on any platform with the help of JVM. This means once we
write and compile our code, it can be used on different kind of devices without any changes,
making Java programs portable and easy to use anywhere.
In Java, the String class comes with many built-in methods to manipulate and inspect strings
1. length()
Returns the number of characters in the string.
String str = "Hello";
int len = str.length(); // 5
2. charAt(int index)
Returns the character at the specified index.
char ch = str.charAt(1); // 'e'
4. toLowerCase() / toUpperCase()
Converts the string to lower or upper case.
String lower = str.toLowerCase(); // "hello"
String upper = str.toUpperCase(); // "HELLO"
5. trim()
Removes leading and trailing whitespace.
String csv = "apple,banana,grape";
String[] fruits = csv.split(","); // ["apple", "banana", "grape"]
New:
A thread enters the new state immediately after its creation, using the new keyword, before the
start() method is called. It is not yet active and has not begun executing.
Runnable:
After the start() method is invoked, the thread transitions to the runnable state. In this state, the
thread is eligible to run, but it might not be executing immediately. It is waiting for its turn to be
scheduled by the thread scheduler. The runnable state can be further divided into ready and
running.
Ready: The thread is waiting for the CPU to allocate time for its execution.
Running: The thread is currently being executed by the CPU.
Blocked/Waiting:
A thread enters the blocked or waiting state when it is waiting for a resource, a lock, or another
thread to complete an action.
Blocked: Occurs when a thread tries to acquire a lock on an object that is currently held by
another thread.
Waiting: Occurs when a thread is waiting indefinitely for another thread to perform a specific
action, often using methods like wait() or join().
Timed Waiting: Similar to waiting, but the thread waits for a specified amount of time, using
methods like sleep() or wait(timeout).
Terminated (Dead):
A thread enters the terminated state when it has completed its execution or when an exception or
error occurs that causes it to stop abruptly. Once a thread is terminated, it cannot be restarted.
9) CONTROL STATEMENT
Control statements in Java manage the flow of program execution. They include decision-making
(if-else, switch), looping (for, while, do-while), and branching (break, continue, return)
constructs.Control statements in Java are the backbone of decision-making and flow control
within a program. They enable us to dictate how the program executes, allowing it to respond
dynamically to various conditions. By using control statements, we can direct the program's
execution path, either through decisions, loops, or jumps, making our applications more robust
and versatile.
Control statements in Java programming are the building blocks of any program that dictate the
flow of execution. They enable us to control how, when, and under what conditions different parts
of the program are executed. By utilizing control statements, we can make decisions, repeat
actions, or execute specific parts of the code based on certain conditions.
Java operators are special symbols that perform operations on variables or values. These
operators are essential in programming as they allow you to manipulate data efficiently. They can
be classified into different categories based on their functionality. In this article, we will explore
different types of operators in Java, including arithmetic, unary, relational, logical, and more,
along with practical examples.
EX:
// Java program to show the use of + and - operators
public class Geeks
{
public static void main(String[] args)
{
// Declare and initialize variables
int num1 = 500;
int num2 = 100;
}
}
Event handling in Java is managed through the delegation event model, where events are
generated by sources and processed by listeners. This model promotes a separation of concerns,
allowing user interface logic to be distinct from event processing logic.
Event Source:
An object that generates an event. Examples include buttons, text fields, and windows.
Event Listener:
An object that waits for an event to occur and then responds to it. Listeners implement specific
listener interfaces, such as ActionListener, MouseListener, or KeyListener, depending on the type
of event they handle.
Event Object:
An object that encapsulates information about the event, such as the source of the event and any
relevant data. Examples include ActionEvent, MouseEvent, and KeyEvent.
Event handling is a mechanism that allows programs to control events and define what should
happen when an event occurs. Java uses the Delegation Event Model to handle events. This
model
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.
Java tokens are the basic building blocks of a Java program. They are the smallest unit of a
program, and they include keywords, identifiers, operators, literals, separators, and comments.
Separators are symbols that separate different parts of a program.
Java tokens are the smallest individual units in a Java program that the compiler recognizes and
processes. They form the basic building blocks of the code, similar to how words and punctuation
form sentences in a language. Java tokens are categorized into several types:
Keywords:
These are reserved words with predefined meanings in Java, such as int, class, if, else, while, etc.
They cannot be used as identifiers.
Identifiers:
These are names given to variables, methods, classes, or other program elements, such as
userName, calculateArea, MyClass.
Literals:
These represent constant values of different data types, such as integers (e.g., 10, -5), floating-
point numbers (e.g., 3.14, 2.0e-5), characters (e.g., 'A', '@'), strings (e.g., "Hello, world!"), and
boolean values (true, false).
Operators:
These are symbols that perform specific operations on operands, such as arithmetic operators (+,
-, *, /, %), relational operators (==, !=, >, <, >=, <=), logical operators (&&, ||, !), and assignment
operators (=, +=, -=, etc.).
Java command-line argument is an argument i.e. passed at the time of running the Java program.
In Java, the command line arguments passed from the console can be received in the Java
program and they can be used as input. The users can pass the arguments during the execution
bypassing the command-line arguments inside the main() method.
We need to pass the arguments as space-separated values. We can pass both strings and
primitive data types(int, double, float, char, etc) as command-line arguments. These arguments
convert into a string array and are provided to the main() function as a string array argument.
When command-line arguments are supplied to JVM, JVM wraps these and supplies them to
args[]. It can be confirmed that they are wrapped up in an args array by checking the length of
args using args.length.Internally, JVM wraps up these command-line arguments into the args[ ]
array that we pass into the main() function.
In JavaScript, each value has a data type, defining its nature (e.g., Number, String, Boolean) and
operations. Data types are categorized into Primitive (e.g., String, Number) and Non-Primitive
(e.g., Objects, Arrays).
JavaScript includes primitive and non-primitive data types. The primitive data types in JavaScript
include string, number, boolean, undefined, null, and symbol. The non-primitive data type
includes the object. A variable of primitive data type can contain only a single value.
15) TYPOGRAPHY
Typography in Java involves using the Font class, along with related classes in the java.awt and
java.awt.font packages, to control the appearance of text in graphical applications. The Font class
allows the specification of font name, style (plain, bold, italic, or bold italic), and size.
Key Concepts:
*Font: Represents a specific typeface with a certain style and size.
*Font Metrics: Provides information about the measurements of a font, such as ascent, descent,
and height.
*Graphics Environment: Allows access to the available fonts on the system.
*Text Attributes: Enables advanced typographic features like underlining, strikethrough, and
transformations.
HTML adds Structure to a web page, CSS styles it and JavaScript brings it to life by allowing
users to interact with elements on the page, such as actions on clicking buttons, filling out forms,
and showing animations.
JavaScript on the client side is directly executed in the user's browser. Almost all browsers have
JavaScript Interpreter and do not need to install any software. There is also a browser console
where you can test your JavaScript code.
JavaScript is also used on the Server side (on Web Servers) to access databases, file handling
and security features to send responses, to browsers.
17) JVM
A Java Virtual Machine (JVM) is a virtual machine that allows Java programs to run on different
platforms and operating systems. It interprets Java bytecode, a platform-independent
intermediate language, and provides a runtime environment for executing Java applications.
Essentially, it's the "brain" of a Java program, allowing it to run on any system that has a
compatible JVM.
JVM is a virtual machine that enables the execution of Java bytecode. The JVM acts as an
interpreter between the Java programming language and the underlying hardware. It provides a
runtime environment for Java applications to run on different platforms and operating systems.
Key Concepts:
Platform-Independent:
Java programs can run on various operating systems (Windows, macOS, Linux, etc.) without
modification because the JVM handles the platform-specific details.
Bytecode:
Java source code is compiled into bytecode, an intermediate language that the JVM interprets
and executes.
Runtime Environment:
The JVM provides a complete runtime environment, including memory management, garbage
collection, and security features.