Java_Notes
Java_Notes
History of JAVA
• Java was developed by James Gosling at Sun Microsystems, Inc.
• Java originated at Sun Microsystems, Inc. in 1991.
• Vinod Khosla was the co-founder of Sun Microsystems.
• On January 27, 2010, Sun was acquired by Oracle Corporation for USS7.4 billion ;
Java is Everywhere(slogan)
• JAVA resides in mobiles, client machines, server machines, embedded devices, smart
phones, cloud, etc.
• It shares the same basic features of the language and libraries.
• Principle of Java: Write Once, Run Anywhere (WORA)
What is Library?
• Java Library is a collection of predefined classes.
• You can use these classes either by inheriting them or by instantiating them.
Java flavours
• JAVA SE (core java)
• JAVA EE (Advance Java)
• JAVA ME (Micro Edition for mobiles)
• Many more...
Features of JAVA
1. Simple
2. Object Oriented Language
3. Interpreted
4. Robust
5. Secure
6. Portable
7. Multi-threaded
8. Garbage Collector
Compile and Run
JDK
• Java Developer Kit contains tools needed to develop the Java programs
• These tools could be Compiler (javac.exe), Application Launcher (java.exe), etc
JRE
• Java Runtime Environment.
• It contains JVM (Java Virtual Machine) and Java Package Classes(Java Library)
JVM
• JVM is platform dependent.
• The Java Virtual Machine provides a platform-independent way of executing code
• Java Virtual Machine interprets the byte code into the machine code depending upon the
underlying operating system and hardware combination. ‘
Remember
• Java is a case sensitive language like C and C++
• Java is nearly 100% object oriented language
• In java, it is not possible to make a function which is not a member of any class (as we
can do in C++)
First Program
public class HelloWorld{
public static void main(String [] args){
System.out.printIn(“Hello World”);
}
}
keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a
key to a code. These are predefined words by Java so they cannot be used as a variable or object
name or class name.
Eg : abstract, default, break, Boolean, byte…..etc.
Data Types
• A type identifies a set of values (and their representation in memory) and a set of
operations that transform these values into other values of that set.
• Java is strongly typed language.
Types
Primitive Types: byte, short, int, long, float, double, char and boolean.
User-defined Types: such as String , Arrays and Classes
Comments
• Block style comments begin with /* and terminate with */ that spans multiple lines.
• Line style comments begin with // and terminate at the end of the line.
• Documentation style comments begin with /** and terminate with */ that spans multiple
lines They are generally created using the automatic documentation generation tool, such
as java.
Conversion
Every expression written in the Java programming language has a type that can be deduced from
the structure of the expression and the types of the literals, variables, and methods mentioned in
the expression.
implementation with code
Widening Conversion / Implicit conversion
int y=3.
float x=y; //Widening Conversion, no error
Permitted Conversions
• byte to short, int, long, float, or double
• char to int, long, float, or double
• int to long, float, or double
• long to float or double
• float to double
OOP In JAVA:
• OOP stand for object-oriented programming.
• The main aim of OOP is to bind together the data & the function that operate on them so
that no other part of the code can access this data except this function.
Advantage of OOP
• OOP is faster & easier to execute.
• Provide a clear structure for the program.
• OOP helps to keep the JAVA code DRY (Don’t Repeat Yourself) & make the code easier
to maintain, modify & debug.
Class
•
Creating class is as good as creating data type
•
Class is defining a category of data.
•
It is user define data types which holds its own data members & member function which
can be accessed & used by creating an instance of that class.
SYNTAX
public class ClassName {
//Data member variable
//member function
}
Eg:
Public Class Person {
Private String name.
Private int age.
}
Object
• Object is a real-world entity.
• Object is an instance of a class.
• When a class is defined no memory is allocated but when it is instantiated (an object is
created) memory is allocated.
SYNTAX
Class Name objectName = new className();
E.g.:
Person obj = new Person();
Static variables
1. Static variables are declared in the class using static keyword.
2. Static variables are by default initialized to its default value.
3. Static variable has a single copy for the whole class and does not depend on the object.
Static functions
• Static functions defined inside the class are qualified with the keyword static
• Static function can only access static members of the same class
• Static function can be invoked using class name and dot operator.
Implementation With Code
Static class
We can have a class inside a class which is known as inner class
Inner class can be qualified with the keyword static
Wrapper classes also provide methods to convert between primitive types and their wrapped
object counterparts. Additionally, wrapper classes offer utility methods for working with the
wrapped values, such as parsing strings into primitive values, comparing values, and more.
Here's an example of parsing an integer from a string using Integer wrapper class:
String numberStr = "123";
int parsedInt = Integer.parseInt(numberStr);
With the introduction of autoboxing and unboxing in Java, the conversion between
primitive types and their corresponding wrapper classes can happen implicitly in most
cases:
Integer autoWrappedInt = 42; // Autoboxing
int autoUnwrappedInt = autoWrappedInt; // Unboxing
Wrapper classes are especially useful when working with Java collections that require objects or
when dealing with generic types that don't support primitive types. However, it's important to
note that using wrapper classes adds a slight overhead in terms of memory and performance
compared to using primitive types directly.
NOTE: Keep in mind that the command-line arguments are always passed as strings. If you need
to convert them to other data types (e.g., integers, booleans), you'll need to perform appropriate
parsing or conversion operations within your program.
Java Packages
• Packages are nothing more than the way we organize files into different directories
according to their functionality, usability as well as category they should belong to
• Files in one directory (or package) would have different functionality from those of
another directory.
Name Collision
• Packaging also helps us to avoid class name collision when we use the same class name
as that of others.
• The benefits of using package reflect the ease of maintenance, organization, and increase
collaboration among developers
Remember
• We can have only one public class in a single java file.
• Name of the file should be same as the name of public class
• In absence of public class, any class name can be given to the file name
Use of import
• import is a keyword in Java
• It is used to import classes of other packages
access modifiers
In Java, access modifiers are keywords used to control the visibility and accessibility of classes,
methods, fields, and other members within a program. There are four main access modifiers in
Java
1. public: Members with this modifier are accessible from anywhere, both within the same
package and from other packages.
2. protected: Members with this modifier are accessible within the same package and by
subclasses (even if they are in different packages).
3. default (no modifier): Also known as package-private, members with no explicit access
modifier are accessible only within the same package.
4. private: Members with this modifier are accessible only within the same class.
Here's a breakdown of how these access modifiers can be applied to various elements in Java:
Class Access Modifiers:
public: The class is accessible from anywhere.
default: The class is accessible only within the same package.
Field and Method Access Modifiers:
public: The field or method is accessible from anywhere.
protected: The field or method is accessible within the same package and by subclasses (even in
different packages).
default: The field or method is accessible only within the same package.
private: The field or method is accessible only within the same class.
Constructors In Java
• Constructor is a member function of a class
• The name of constructor is same as the name of the class.
• Constructor has no return type.
Implementation With Code
Constructor is special
• A constructor is a special method that is used to initialize a newly created object and is
called implicitly, just after the memory is allocated for the object
• It is not mandatory for the coder to write a constructor for the class
• When there is no constructor defined in the class by programmer, compiler implicitly
provide a default constructor for the class
Constructor Overloading
• Constructors can be parameterized
• Constructors can be overloaded
Inheritance In java
Inheritance is an important pillar of OOP(Object-Oriented Programming). 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.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you
are derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Implentation With Code
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Java determines the correct method to call based on the provided arguments' types and numbers.
Keep in mind that while overloading can make your code more readable and intuitive, excessive
overloading can lead to confusion. Use method overloading judiciously and ensure that the
methods' behavior is logically consistent to avoid unexpected results.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
final keyword
In Java, the final keyword is used to indicate that a particular entity (class, method, or variable)
cannot be changed or further extended, depending on where it's applied. It enforces various
forms of immutability and restrictions in the Java programming language.
Here's how the final keyword is used in different contexts:
Final Instance Variables: When applied to a variable, it means that the variable's value cannot
be changed after it's assigned a value. This is often used for constants.
final int myConstant = 42;
// myConstant = 100; // This would result in a compilation error
Final Methods: When applied to a method, it means that the method cannot be overridden by
subclasses. This is often used to ensure that the behavior of a method remains consistent across
subclasses.
class Parent {
final void doSomething() {
// ...
}
}
class Child extends Parent {
// Cannot override doSomething() here
}
Final Classes: When applied to a class, it means that the class cannot be extended. This is used
to prevent further inheritance from that class.
final class MyFinalClass {
// ...
}
// Cannot create subclasses of MyFinalClass
Final Arguments: When applied to method arguments, it means that the value of the argument
cannot be modified within the method.
void process(final int value) {
this keyword
• The this object reference is a local variable in instance member methods referring the
caller object
• this keyword is used as a reference to the current object which is an instance of the
current class
• The this reference to the current object is useful in situations where a local variable hides,
or shadows, a field with the same name.
Implementation With Code
super keyword
In Java, the super keyword is used to refer to the immediate parent class of a subclass. It's
primarily used to access members (fields, methods, constructors) of the superclass when there is
a name conflict between the subclass and superclass or to explicitly call the superclass's
constructor from the subclass's constructor.
Here are the main ways the super keyword is used:
Accessing Superclass Members: If a subclass has a member (field or method) with the same
name as a member in its superclass, the super keyword can be used to refer to the superclass's
member.
class Parent {
int value = 10;
void display() {
System.out.println("Value in parent: " + value);
}
}
class Child extends Parent {
int value = 20;
void display() {
System.out.println("Value in child: " + value); // Child's value
System.out.println("Value in parent: " + super.value); // Parent's value
}
}
Invoking Superclass Constructors: In the constructor of a subclass, you can use super() to
explicitly call a constructor from the superclass. This is used for constructor chaining.
class Parent {
Parent(int value) {
Child(int value) {
The super keyword is essential for maintaining proper class hierarchy, resolving ambiguity, and
enabling interactions between a subclass and its superclass. It helps in accessing and interacting
with superclass elements while providing the flexibility to customize behavior in the subclass.
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. We can store only a fixed set of elements in a Java array.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Catching Exceptions: To handle exceptions, you use the try-catch block. Code that might throw
exceptions is placed inside the try block, and you catch and handle these exceptions in the catch
blocks. You can have multiple catch blocks to handle different types of exceptions.
try {
// Code that may throw exceptions
} catch (SomeException e) {
// Handle SomeException
} catch (AnotherException e) {
// Handle AnotherException
} finally {
// Optional: Code that always executes, whether an exception occurs or not
}
The finally Block: The finally block is used to specify code that should always be executed,
regardless of whether an exception is thrown or not. It is optional but commonly used for
cleanup tasks like closing resources (e.g., files, database connections).
Exception Types: Java has a hierarchy of exception classes. The base class for all exceptions is
java.lang.Throwable. It has two main subclasses: java.lang.Exception (for recoverable
exceptions) and java.lang.Error (for unrecoverable errors). You can create your own custom
exception classes by extending java.lang.Exception or its subclasses.
Checked vs. Unchecked Exceptions:
Checked Exceptions: These are exceptions that the compiler forces you to handle explicitly by
either catching them or declaring that your method throws them. Examples include IOException,
SQLException.
Unchecked Exceptions (Runtime Exceptions): These are exceptions that you're not required to
catch or declare explicitly. They usually represent programming errors and extend
java.lang.RuntimeException. Examples include NullPointerException,
ArrayIndexOutOfBoundsException.
Here's an example of catching and handling a checked exception:
javaCopy code
import java.io.IOException;
Proper exception handling is crucial for writing robust and reliable Java applications, as it helps
you anticipate and gracefully handle errors that may occur during runtime.
abstract in java
In Java, the abstract keyword is used to define abstract classes and methods. An abstract class is
a class that cannot be instantiated (i.e., you cannot create objects of an abstract class), and it
often serves as a blueprint for other classes. Abstract methods are methods declared in an
abstract class that do not have a body and are meant to be implemented by concrete (non-
abstract) subclasses of the abstract class.
Here are the key points related to abstract in Java:
Abstract Class:
• An abstract class is declared using the abstract keyword.
• An abstract class can contain both abstract methods and concrete methods (methods with
implementations).
• You cannot create an instance of an abstract class using the new keyword. It's meant to be
subclassed.
• Abstract classes can have constructors, and they are typically used to initialize fields or
perform common tasks in subclasses.
• Subclasses of an abstract class must provide implementations for all abstract methods
unless they are also declared as abstract.
Interfaces in Java
An interface can contain method signatures (methods without implementations) and constants
(final fields). Classes that implement an interface are required to provide concrete
implementations for all the methods declared in the interface. Interfaces are a key part of
achieving abstraction and enabling multiple inheritance of type in Java. Here are the key points
about interfaces in Java:
Declaring an Interface:
You declare an interface using the interface keyword.
An interface can include method declarations (without implementations) and constants.
interface MyInterface {
void someMethod(); // Method declaration without implementation
int CONSTANT_VALUE = 42; // Constant (implicitly public, static, and final)
}
Implementing an Interface:
• To use an interface, a class must implement it using the implements keyword.
• A class can implement multiple interfaces (Java supports multiple interface inheritance).
•
class MyClass implements MyInterface {
public void someMethod() {
System.out.println("Implemented someMethod");
}
}
string buffer
In Java, StringBuffer is a class that is part of the java.lang package and is used for creating and
manipulating mutable (modifiable) strings. Unlike the String class, which represents immutable
strings (strings that cannot be changed after they are created), StringBuffer allows you to modify
the content of the string without creating a new object. This can be more efficient when you need
to perform multiple string manipulations.
Here are some key points about the StringBuffer class in Java:
Mutable Strings: A StringBuffer object represents a sequence of characters that can be
modified. You can append, insert, delete, and replace characters within a StringBuffer instance
without creating a new string each time.
Thread-Safe: StringBuffer is designed to be thread-safe, which means it is synchronized to
ensure that multiple threads can safely manipulate the same StringBuffer object without causing
data corruption or race conditions. This makes it suitable for use in multithreaded environments.
Performance: While StringBuffer provides the advantage of mutability, it can be less efficient
than the String class in some cases, especially when used in single-threaded applications. If you
don't need thread safety and are working in a single-threaded environment, you may prefer to use
StringBuilder, which is similar to StringBuffer but is not synchronized and can be faster in some
situations.
Here's an example of how to use StringBuffer in Java:
// Delete characters
stringBuffer.delete(3, 5);
In this example, we create a StringBuffer object and use various methods like append, insert,
replace, and delete to modify the content of the string. Finally, we convert the StringBuffer back
to a regular String using the toString() method.