0% found this document useful (0 votes)
1K views169 pages

Understanding OOP and Java Basics

The document discusses object-oriented programming concepts like classes, objects, inheritance, polymorphism, and encapsulation. It then provides examples and explanations of these concepts in Java, including features of Java, the Java Virtual Machine, variables, arrays, constructors, inheritance, polymorphism through method overloading and overriding, and the use of this() and super() in constructors.

Uploaded by

SHARE IT TIPS
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views169 pages

Understanding OOP and Java Basics

The document discusses object-oriented programming concepts like classes, objects, inheritance, polymorphism, and encapsulation. It then provides examples and explanations of these concepts in Java, including features of Java, the Java Virtual Machine, variables, arrays, constructors, inheritance, polymorphism through method overloading and overriding, and the use of this() and super() in constructors.

Uploaded by

SHARE IT TIPS
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

OOPS

• Object Oriented Programming Structure


• Features of OOPS
 Objects / Instance
 Classes
 Inheritance
 Polymorphism
• Overloading / Static Polymorphism / Compile-
time polymorphism
• Overriding / Dynamic polymorphism / Run-time
polymorphism
 Encapsulation
 Abstraction

[Link]
OOPS
• Objects – Real time entity
• Classes – Blueprint of an object. It gives
structure to the objects
• Inheritance – Deriving base class properties
and behaviour to the child class
• Polymorphism - One object in different forms
• Encapsulation - Hiding the irrelevant details to
the irrelevant entity
• Abstraction – Revealing the relevant details to
the relevant entity.

[Link]
History of Java
• The original name of Java was Oak, and it was
developed as a part of the Green project at Sun
Microsystems.
• Java was conceived by James Gosling, Patrick
Naughton, Chris Warth, Ed Frank, and Mike
Sheridon at Sun Microsystems in 1991.
• Sun formally announced the Java SunWorld in
1995.

[Link]
Features of JAVA
• Object Oriented Programming language
• Platform Independent
• Robust
• Portable
• Scalable
• Multithreaded
• Architecturally neutral
• Secured

[Link]
Components of Java

• JDK – Java Development Kit


• JRE – Java Run-time Environment
• JVM - Java Virtual Machine

[Link]
Java Virtual Machine

 The Java Virtual Machine provides a platform-


independent way of executing code, by abstracting the
differences between operating systems and CPU
architectures.

 JVM is Write Once-Run Anywhere (WORA) software.

 JVM forms part of large system JRE.

 JVM's main job is interpreting java byte code and


translating this into actions or OS calls.

 JVM is OS dependent which makes java source code as


machine independent.

[Link]
JRE and JVM

[Link]
Purpose of Features of OOPS
• Classes - Classification
• Encapsulation - maintainability, flexibility and
extensibility.
• Polymorphism – one method will behave
differently.
• Inheritance – Reusability, Easier updates, Do
not break what is already working.

[Link]
Structure of JAVA Program
• Package declaration;
• Import statements
• Class declaration
{
Variable declaration/ definition;
method declaration / definition;
}

[Link]
Main method
• class <classname>
{
public static void main(String[] args)
{
// Object instantiation
<classname> m = new <classname>();
}
}

[Link]
CamelCase Convention
• Variables - myVariable
• Method - myMethod()
• Class - MyClass
• Package - mypackage
• Constants - MYCONSTANT

[Link]
Types of Variable

• Local variable (variable inside method or block)


• Class Variable (Static Variable)
• Instance Variable ( variable inside the class)

Note:
• Local variables require explicit initialization.
• Instance variables are initialized automatically.

[Link]
Variable Initialization
Variable Value
• byte 0
• short 0
• int 0
• long 0L
• float 0.0F
• double 0.0D
• char '\u0000'
• boolean false
• All reference types null
[Link]
Constructor
• It is a Spl. Method
• Purpose: To initialize the class members
• Features:
 Same name as that of the class name
 No return type including VOID
 Can have access specifier
 Can be overloaded
 Constructors are NOT inherited
 Invoked automatically whenever the object is
created.
 The no. of time of invocation depends on no. of
object created
[Link]
Arrays
• Group data objects of the same type, in a
contiguous block of memory.
• An array is an object; it is created with new.
• Can be declared as a primitive type or Class
type.
• Array index starts with 0.
• You cannot resize an array.
• You can use the same reference variable to
refer to an entirely new array.

[Link]
Array Declaration and
Instantiation
• Array declaration
<element type>[] <array name>;

int[] myArray;
• Constructing an array
<array name> =
new <element type> [<array size>];

myArray = new int[5];

[Link]
Initializing an Array
• Explicit initialization in one line.
<element type>[] <array name> =
{ <array initialize list> };

Primitive array:
*****************
int[] myArray = { 1 , 2 , 3 , 4 , 5 } ;

Reference Array:
********************
Object[] objArr = { new Pizza(), new Pizza(), null };

[Link]
Initializing an Array
• Explicit initialization can also be done using
array subscripts.
int[] myArray = new int[3];
myArray [0] = 10;
myArray [1] = 20;
myArray [2] = 30;

[Link]
Inheritance
• Deriving the parent class properties and
methods to the child class.
• Types of inheritance:
 Single level inheritance
- one super and one sub class
 Multilevel inheritance
- The sub class of one level forms the super
class of another level
 Multiple inheritance [ not supported by java]
- many super and one sub class
 Hierarchical inheritance
- one super and many sub classes
 Hybrid inheritance
- multiple and multi level combined.
[Link]
Inheritance
• Two important concepts
 Generalization - Up the hierarchy
 Specialization - Down the hierarchy
• Purpose : Reusability (without changing its
identity)
• Syntax:
<modifier> class <name> extends <superclass>
{
<declaration>*
}

[Link]
IS-A & HAS-A relationship
• When you want to know if one thing should
extend another, use the IS-A test.
Eg : Triangle IS-A Shape
• Do not apply inheritance if the subclass and
super class do not pass the IS-A test.
• Is-a relationship can be described in Java
keyword extends.
• The IS-A relationship – Unidirectional

[Link]
IS-A & HAS-A relationship
• When two classes are related, but not through
inheritance, (for example, one class has a
reference to another class) then you say that
the two classes are joined by HAS-A
relationship.
• Has-a relationship can be described in Java
code as member fields.
Note:
• Code reuse is also best achieved by
aggregation when there is no is-a relationship

[Link]
IS-A & HAS-A relationship
• class Car
{
}
class BMW extends Car => IS-A R/S
{
boolean auto_gear = “true” => Has-A R/S
}

[Link]
Polymorphism
• Polymorphism (from Greek, meaning “many
forms”) is a feature that allows one interface to
be used for a general class of actions that is
one interface with multiple methods.
• Types:
 Overloading => Ad-Hoc Polymorphism
- Same method name with different set of
parameters.
- Early Binding
 Overriding => True polymorphism
- Same method name with same set of
parameters.
- Late Binding
[Link]
Types of Overloading

• Function Overloading
• Constructor Overloading
• NO operator Overloading in Java

• Rules :
 No. of parameter should change
 Datatype of the parameter should change
 Sequence of passing the paramter should
change.

[Link]
Overriding
• The overridden method in the superclass is NOT inherited by
the subclass, and the new method in the subclass must
uphold the following rules of method overriding:
 The new method definition must have the same method
signature (i.e., method name and parameters) and the
same return type.
 Overridden Methods Cannot Be Less Accessible.
• A subclass cannot override fields of the superclass, but it can
hide them.
• Works only with inheritance.
• Constructors cant be Overridden.
• Super keyword is used to invoke an overridden method in the
superclass.

[Link]
this() and super() call for
constructor
• this() construct is used to implement local chaining of
constructors in the class when an instance of the class is
created.
• The this() call invokes the constructor with the
corresponding parameter list.
• super() method is used to invoke the IMMEDIATE base
class constructor. This allows the subclass to influence
the initialization of its inherited state when an object of
the subclass is created.
• this() and super() call must occur as the first statement
in a constructor.

[Link]
Example : this() and super()
class GParent
{
int a,b,c;
GParent() {
[Link]("From gparent");
}

GParent(int a,int b) {
//this(a,b,100);
this();
[Link]("a= "+a+" b = "+ b);
}

GParent(int a,int b,int c) {


this.a=a;
this.b=b;
this.c=c;
[Link]("a= "+a+" b = "+ b + " c= " +c);
}
}

[Link]
Example : this() and super()

class Parent extends GParent


{
int x,y;
Parent()
{
[Link]("From parent");
}

Parent(int x,int y)
{
super(x,y);
this.x=x;
this.y = y;
[Link]("x= "+x+" y = "+ y);
}

[Link]
Example : this() and super()
class Child extends Parent
{
Child()
{
super(23,343);
[Link]("From child");
}

}
class SuperEx
{
public static void main(String[] a)
{
//Parent p = new Parent(12,23);
Child d = new Child();

[Link]
instanceof operator
• Use instanceof to test the type of an object.
• Restore full functionality of an object by casting.
• Example:
public void doSomething(Employee e) {
if ( e instanceof Manager )
{
Manager m = (Manager) e;
}
// rest of operation
}

[Link]
Static Keyword
• It’s a Access Modifier
• The static keyword is used as a modifier on
variables, methods, and nested classes.
• The static keyword declares the attribute or
method is associated with the class as a whole
rather than any particular instance of that class.
• Thus static members are often called class
members, such as class attributes or class
methods.

[Link]
Static Keyword
• A static method can access only the static
variable. But the normal variable can access
both static and normal variable.
• Static members will get loaded into the memory
only once.
• Static members are subjected to change
common for all the instance.
• NO NEED FOR OBJECT to access the static
member.

[Link]
Static Variable Example
class StatEx
{
int i=10;
static int j = 20;

public void normalMethod()


{
[Link]("Instance var = " + i++);
[Link]("Static var = " + j++);
}

public static void main(String arg[])


{
StatEx s1 = new StatEx();
StatEx s2 = new StatEx();
[Link]();
[Link]();
}
} [Link]
Static Method Example
class StatEx
{
int i=10;
static int j = 20;

public static void staticMethod()


{
//[Link]("Instance var = " + i++); //illegal
[Link]("Static var = " + j++);
}

public static void main(String arg[])


{
staticMethod();
staticMethod();
}
}

[Link]
Static Initializer Example
class StatEx1
{
static int counter;

//static initializer
static
{
counter=10;
[Link]("Static block invoked "+counter);
}
public static void sMethod()
{
[Link]("Static method" + counter++);
}

[Link]
Static Initializer Example

class StatEx
{
public static void main(String arg[])
{
[Link]("from main");
[Link]();
[Link]();
}
}

[Link]
Final Keyword
• Variable become Constant
• Method cant be Overridden
• Class cant be inherited

• Note:
 All final variable need Explicit initialization

[Link]
Wrapper Class
• Conversion of primitive types to the object
equivalent done through wrapper classes.
• Allow objects to be created from primitive types.
• Wrapped values are immutable (Cant modify) .
To wrap another value, you need to create
another object.
• Wrapper class are present in [Link] package
• All the wrapper classes are declared final.

[Link]
Primitive Data Types and
Corresponding Wrapper Classes
Primitive Data Type Wrapper Class Constructor Arguments
boolean Boolean boolean or String

byte Byte byte or String

char Character char

short Short short or String

int Integer int or String

long Long long or String

float Float double or float or String

double Double double or String

All the wrapper classes except Boolean and Character are


subclasses of an abstract class called Number, whereas
Boolean and Character are derived directly from the Object
class.
[Link]
Boxing and Unboxing
• Converting a value type to a reference type is
known as Boxing.
• Converting a reference type to a value type is
known as UnBoxing.

int x=10;
Integer n = new Integer(x); //Boxing
int y = [Link](); //UnBoxing

[Link]
AutoBoxing and AutoUnboxing

Example:

int x=10;
Integer n = x; //AutoBoxing
int y = n; //AutoUnBoxing

[Link]
Methods to Extract the Wrapped
Values
Method Class
public boolean booleanValue() Boolean
public char charValue() Character
public byte byteValue() Byte, Short, Integer, Long, Float,
Double
public short shortValue() Byte, Short, Integer, Long, Float,
Double
public int intValue() Byte, Short, Integer, Long, Float,
Double
public long longValue() Byte, Short, Integer, Long, Float,
Double
public float floatValue() Byte, Short, Integer, Long, Float,
Double
public double doubleValue() Byte, Short, Integer, Long, Float,
Double

[Link]
Methods to Convert Strings to
Primitive Types
Wrapper Method Signature Method Arguments
Class

Boolean static boolean parseBoolean(…) String


Character Not available
Byte static byte parseByte(…) String, or String and radix
Short static short parseShort(..) String, or String and radix
Integer static int parseInt(…) String, or String and radix
Long static long parseLong(…) String, or String and radix
Float static float parseFloat(…) String
Double static double parseDouble(…) double or String

[Link]
Wrapper Conversion methods
• Primitive xxxValue()
 To convert Wrapper to primitive

• Primitive parseXxx(String)
 To convert a String to a primitive

• Wrapper valueOf(String)
 To convert a String to a Wrapper

[Link]
Object Class
• Root class of Java => Object
• equals() method = > Check only values
• toString() method =>Check value & reference
• hashCode() => return the address of the object

• Object Class is in [Link] package.

[Link]
Abstract Class
• Class which have a abstract method (method
without definition) is abstract class.
• Can have normal method and variable
• Cant be instantiated
• Methods may or may not be implemented by
the child class.
• Use abstract keyword to declare a class as
abstract.
• Abstract method cannot be private or final
• A class can inherit only one abstract class.
• NEED RELATIONSHIP between classes
[Link]
Interface
• Interface is to support multiple inheritance in
Java.
• Interfaces should be implemented by the child
class
• Can have only abstract method.
• Interface contain only [Link] Variables.
• All the fields are public static final in nature.
• Interfaces cant be instantiated
• A class can implement many interfaces.
• All the methods should be implemented by the
child class.
• NO NEED FOR RELATIONSHIP
[Link]
enum
• Assigning a integral constant to a symbolic
name => enum
• Use enum when you want a variable to hold
only a predetermined set of values.
• You use the keyword enum and not class to
declare an enum.
• Just like a class, an enum can have
constructors, methods, and fields.
• An enum cannot be declared within a method.
• You cannot instantiate an enum with the new
operator.
[Link]
enum
• The enums do not participate in class hierarchy:
they cannot extend and they cannot be
extended.
• You cannot directly call an enum constructor.
• An enum may have a main() method and
therefore can be executed by name from the
command line like an application.

[Link]
Enum Example1

enum Edge
{
TOP,BOTTOM,LEFT,RIGHT
};

class MyClass
{
public static void main(String[] a)
{
Edge e = [Link];
int i = [Link]();
[Link](e);
[Link](i);
}
}

[Link]
Enum Example2

enum Edge
{
TOP,BOTTOM,LEFT,RIGHT;

public static void main(String[] a)


{
Edge e = [Link];
int i = [Link]();
[Link](e);
[Link](i);
}
}

[Link]
Enum Example3
public enum Day
{

MONDAY(8,true),
TUESDAY(8,true),
WEDNESDAY(8,true),
THURSDAY(8,true),
FRIDAY(8,true),
SATURDAY(4,false),
SUNDAY(0,false);

private int hours;


private boolean weekday;

[Link]
Enum Example3

Day(int whours,boolean wday)


{
hours=whours;
wday=weekday;
}

public int getHours()


{
return hours;
}

public boolean isWeekDay()


{
return weekday;
}
[Link]
Enum Example3

public static void showDay(Day d)


{
if([Link]())
{
[Link](d +" is a weekday and has "+
[Link]() +" hours working hours");
}
else
{
[Link](d +" is a not weekday and has
"+ [Link]() +" hours working hours");
}
}

[Link]
Enum Example3

public static void main(String[] ar)


{
Day day;
day = [Link];
showDay(day);
}

[Link]
Inner Class
• A class that is declared within another class or
interface, is called a nested class.
• There are four categories of nested classes
 Regular class - class within the class
 Method-local class – class within the method of
the outer class
 Static nested class - inner classes marked with
the static modifier (top-level nested class)
 Anonymous class - part of a method argument.
• All inner classes are nested classes, but not all
nested classes are inner classes.

[Link]
Example for Regular InnerClass
class MyOuter
{
int x =7;
class MyInner
{
public void InnerMethod()
{
[Link]("x == " + x);
}
}
public void OuterMethod()
{
MyInner inn = new MyInner();
[Link]();
}
[Link]
Example for Regular InnerClass

public static void main(String[] a)


{
MyOuter mo = new MyOuter();
[Link] mi = [Link] MyInner();
[Link]();
[Link]();
//[Link](); illegal
//[Link](); illegal

[Link]
Method-local inner class
• A method-local inner class can be instantiated
only within the method where the inner class is
defined.
• Can access the outer class level variable.
• CANT access the variable inside the method in
which the inner class is created except a final
variable.
• Method-local inner class can be declared
abstract and final.
• method-local inner class can't use any access
specifiers.

[Link]
Method-local inner class
class MouterClass
{
int x =10;
public void OuterMethod()
{
final int j=90;
class MinnerClass
{
public void minnerMethod()
{
[Link]("Hello ..." + x + j);
}
}
MinnerClass mic = new MinnerClass();
[Link]();
}
public static void main(String[] a)
{
MouterClass moc = new MouterClass();
[Link]();
}
}
[Link]
Static nested class
• Static nested classes are inner classes marked
with the static modifier.
• A static nested class is not an inner class, it's a
top-level nested class.
• A static nested class cannot access non-static
members of the outer class.

[Link]
Static nested class
class OuterClass
{
static int i =10;
public void method()
{
[Link]("i == " + ++i);
}
static class InnerClass
{
public void display()
{
[Link]("i == " + i);
}
}
[Link]
Static nested class

public static void main(String[] a)


{
[Link] ic = new
[Link]();
[Link]();

OuterClass oc = new OuterClass();


[Link]();
}
}

[Link]
Anonymous Inner Classes
• Anonymous inner classes have no name.
• Anonymous inner classes cannot have
constructor.

[Link]
Anonymous Inner Classes
import [Link].*;
import [Link].*;
class FrameExample
{
private Frame f;
public FrameExample()
{
f = new Frame("Hello .....!");
}
public void launchFrame()
{
[Link](170,170);
[Link]([Link]);
[Link](true);

[Link]
Anonymous Inner Classes
// Add a window listener
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent evt)
{
[Link](0);
}
}); //Anonymous Inner Classes

public static void main(String args[])


{
FrameExample f = new FrameExample();
[Link]();
}
}

[Link]
Exception Handling
• An exception in Java is a signal that indicates
the occurrence of some important or
unexpected condition during execution.
• Error Types:
 happens due to problems originating from the
execution environment. (Error Class)
 happens due to problems originating inside the
application itself. (Exception Class)

• Exception Should be Handled or Thrown to the


exception handler.

[Link]
Exceptions
• Errors (represented by subclasses of Error)
occur in the Java virtual machine (JVM) and not
in the application itself.
• The exceptions (represented by subclasses of
Exception), on the other hand, generally
originate from within the application.
• Types:
 Checked Exception
 Unchecked Exception

[Link]
Checked Exception
• Checked exceptions are generally related to
how the program interacts with its environment.
• This is the category of exceptions for which the
compiler checks (hence the name checked
exceptions) to ensure that your code is
prepared for them.
• The programmer is required to write code to
deal with checked exceptions. The compiler
checks that such code exists.
• It MUST be thrown programmatically or
Handled.

[Link]
Unchecked Exception
• Occur due to program bugs.
• Runtime exceptions are not checked by the
compiler.
• Write the correct code to avoid the runtime
exceptions than write the code to catch them
but it is not illegal to catch them.
• Runtime exceptions and errors combined are
also called unchecked exceptions and they are
mostly thrown by the JVM.

[Link]
The Exception Class Hierarchy
Object

Throwable

Exception Error

Others… RuntimeException Others…

Others…

[Link]
Exception-handling mechanism
• Contains five keywords:
 try - catch – throw - throws – finally
Method throws ExceptionName{
try{
--risky code goes here
}catch(ExceptionClassName ObjectName){
-- Exception handler block code
throw Exception_Instance //Ducking it
}
finally{
-- cleanup your code goes here
}
}
[Link]
About try-catch-finally
• A try block should be followed by at least one catch
block.
• The code inside try block is called as protected code.
• Can have one or more catch block.
• If you have multiple catch block, make sure that the last
catch block contain the super most class in the hierarchy.
• You may also write an optional “finally” block. This block
contains code that is ALWAYS executed, either after the
“try” block code, or after the “catch” block code.
• The catch block may or may not contain throw keyword.
• The try block can also be nested.

[Link]
Example 1
class PrintStack
{
public static void main(String args[])
{
int Num1= 30 , Num2 = 0;
try
{
int Num3=Num1/Num2;
}
catch(ArithmeticException obj)
{
[Link]("Exception"+obj);
[Link]();
}
}
}

[Link]
Rules in Exception
• The Declare or Handle Rule
 Handle the exception by using the
try-catch-finally block.
• Declare that the code causes an exception by
using the throws clause.
• You do not need to declare runtime exceptions
or errors.
• You can choose to handle runtime exceptions.

[Link]
Passing the exception
 In any method that might throw an exception,
you may declare the method as “throws” that
exception, and thus avoid handling the exception
yourself
 Example
• public void myMethod throws IOException {
… normal code with some I/O
}

[Link]
Throws clause
class UncheckedThrows
{
public void show() throws ArithmeticException
{
[Link]("Hai I am not handled");
}

public static void main(String[] arg)


{
new UncheckedThrows().show();
}
}

[Link]
Method Overriding and
Exceptions
The overriding method can throw:
 No exceptions
 One or more of the exceptions thrown by the
overridden method.
 One or more subclasses of the exceptions
thrown by the overridden method.

 The overriding method cannot throw:


 Additional exceptions not thrown by the
overridden method.
 Super classes of the exceptions thrown by
the overridden method

[Link]
User Defined Exception
• Create User-Defined Exception as a Class that
EXTENDS Exception Class.
• Instantiate the created Exception and use it in
the catch block as a handler.

[Link]
Example 2
import [Link].*;

class MyException extends Exception


{
MyException()
{
[Link]("UserDefined Error occured");
}

public String toString()


{
return "MyException thrown";
}
}

[Link]
Example 2 cont…
class UserExceptions
{
public void valid()
{
try
{
String str1,str2;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter Login id");
str1=[Link]();
[Link]("Enter password");
str2=[Link]();
if([Link](str2))
[Link]("Hai welcome");
else
throw new MyException();
} [Link]
Example 2 cont …
catch(MyException e)
{
[Link]("Sorry U r not a valid user" + e);
valid();
}
catch(IOException ioe){}
}

public static void main(String[] arg) throws IOException


{
UserExceptions e1=new UserExceptions();
[Link]();
}

[Link]
String Class Facts
• An object of the String class represents a string
of characters.
• The String class belongs to the [Link]
package, which does not require an import
statement.
• Like other classes, String has constructors and
methods.
• Unlike other classes, String has two operators,
+ and += (used for concatenation).
• String class is declare final , therefore
immutable.

[Link]
Literal Strings
• are anonymous objects of the String class
• are defined by enclosing text in double quotes.
“This is a literal String”
• don’t have to be constructed.
• can be assigned to String variables.
• can be passed to methods and constructors as
parameters.
• have methods you can call.

[Link]
Literal String Example
//assign a literal to a String variable
String name = “Priya”;

//calling a method on a literal String


char Initial = “Priya”.charAt(0);

//calling a method on a String variable


char Initial = [Link](0);

[Link]
Immutability
• Once created, a string cannot be changed:
none of its methods changes the string.
• Such objects are called immutable.
• Immutable objects are convenient because
several references can point to the same object
safely: there is no danger of changing an object
through one reference without the others being
aware of the change.

[Link]
Advantages Of Immutability
• Uses less memory
String word1 = "Java"; String word1 = “Java";
String word2 = word1; String word2 = new String(word1);

word1 word1 “Java"

“Java" word2 “Java"


word2
Less efficient:
OK wastes memory

[Link]
Disadvantages of Immutability
• Less efficient — you need to create a new
string and throw away the old one even for
small changes.
String word = “Java”;
char ch = [Link]([Link] (0));
word = ch + [Link] (1);

word “java"

“Java"

[Link]
Empty Strings

• An empty String has no characters. It’s


length is 0.
String word1 = ""; Empty strings
String word2 = new String();

• Not the same as an uninitialized String.

private String errorMsg; errorMsg


is null

[Link]
Copy Constructors
• Copy constructor creates a copy of an existing
String. Also rarely used.
• Not the same as an assignment.
Copy Constructor: Each variable points to a different copy of the String.

String word1 = new String(“Java”); word1 “Java"


String word2 = new String(word);
word2 “Java"
Assignment: Both variables point to the same String.

String word1 = “Java”; word1


String word2 = word; “Java"
word2

[Link]
Other Constructors
• Most other constructors take an array as a
parameter to create a String.

char[] letters = {‘J’, ‘a’, ‘v’, ‘a’};


String word = new String(letters);//”Java”

• String index starts with 0 like arrays.

[Link]
Methods in String Class
• char charAt(i) => Returns the char at position i.
• int length(); => Returns the number of
characters in the string.
• String substring() => Returns a substring object
• substring(i,k) substring(i)
“television".substring (2,5); “television".substring (2);
television television
i k i

[Link]
Methods in String Clas
• indexOf() => returns the index position of the
character.
• equals()
• equalsIgnoreCase()
• compareTo()
• compareToIgnoreCase()
• trim()
• replace()
• toUpperCase()
• toLowerCase()

[Link]
StringBuffer Class
• String Buffers are mutable strings.
• StringBuffer is a final class.
• They can be created empty, from a string or
with a capacity. An empty StringBuffer is
created with 16-character capacity.
• Can grow dynamically in size without bounds.

[Link]
Methods in String Buffer
• length()
• capacity()
• ensureCapacity()
• setLength()
• charAt()
• Append()
• setCharAt()
• Insert()
• deleteCharAt()
• replace()
• reverse()
[Link]
StringBuilder Class
• Same like StringBuffer Class
• StringBuilder’s methods are not synchronized.
• StringBuilder methods should run faster than
StringBuffer methods.

[Link]
Collections
• A collection allows a group of objects to be
treated as a single unit.
• Arbitrary objects can be stored, retrieved, and
manipulated as elements of collections.
• Provided in the [Link] package.
• The collections framework comprises three
main parts.
 Interfaces => Collection
 Classes => Collections
 Algorithms

[Link]
The Collections Interfaces
The root of the hierarchy of the collections interfaces
is the Collection interface.
 There is another kind of collections called maps,
which are represented by the super interface Map.

Both a Map object and a Set collection cannot contain


duplicates data items.
while a List collection can contain duplicates.

[Link]
The Collections Interfaces
 A collection has no special order and does not
reject duplicates. ([Link])
 A list is ordered and accept duplicates.
([Link]).
 A set has no special order but rejects duplicates.
([Link])
 A map supports searching on a key field, values
of which must be unique. ([Link])

[Link]
Collection Classes
• ArrayList, LinkedList, and Vector are the
classes that implement the List interface.
• HashMap and HashTable are examples of
classes that implement the Map interface.
• HashSet and LinkedHashSet are examples of
classes that implement the Set interface.

[Link]
[Link]
List
import [Link].*;
class ListExample {
public static void main(String[] args) {
List list = new ArrayList();
[Link]("one");
[Link]("second");
[Link]("3rd");
[Link](new Integer(4));
[Link](new Float(5.0F));
[Link]("second"); // duplicate, is added
[Link](new Integer(4)); // duplicate, is added
[Link](list);
}
}

[Link]
Set

import [Link].*;
class SetExample {
public static void main(String[] args) {
Set set = new HashSet();
[Link]("one");
[Link]("second");
[Link]("3rd");
[Link](new Integer(4));
[Link](new Float(5.0F));
[Link]("second"); // duplicate, not added
[Link](new Integer(4)); // duplicate, not added
[Link](set);
}
}

[Link]
Collection API - Storage
• The storage associated with any one collection can be
implemented in many ways, but the Collections API
implements the four methods that are most widely used:
 Array: supports insertion, deletion, but growing the
store is more difficult.
 ArrayList: grow in number of elements. Search is
faster. But not insertion and deletion. Vector(provides
synchronization)
 Linked list: supports insertion, deletion, and growing
the store, but makes indexed access slower. Use
when insertions and deletions happen frequently.
 Tree: supports insertion, deletion, and growing the
list. Indexed access is slow, but searching is faster.
 Hash table: supports insertion, deletion, and growing
the store. Indexed access is slow, but searching is
particularly fast. However, hashing requires the use of
unique keys for storing data elements.
[Link]
Set Classes
• HashSet :
 provides the faster access to a data item.
 no guarantee that the items will be ordered.
 does not offer synchronization.
• Tree Set:
 presents sorted data items.
 performance is not as good as HashSet.
 does not offer synchronization.
• LinkedHashSet:
 Similar to HashSet that maintains a doubly linked
list.
 It is an ordered collection, ordered by insertion,
but not sorted.
 does not offer synchronization
[Link]
Map Classes
• HashTable:
 implementation is based on the hashtable data
structure.
 No ordering.
 implementation is synchronized
• HashMap:
 based on the hashtable data structure.
 No ordering
 allows null and is unsynchronized
• LinkedHashMap:
 maintains a doubly linked list.
• TreeMap:
 implements the SortedMap interface
 Sorted and unsynchronized.
[Link]
Class Interface Duplicates Ordered/ Synchronized
Allowed? Sorted
ArrayList List Yes Ordered by index No
Not sorted
LinkedList List Yes Ordered by index No
Not sorted
Vector List Yes Ordered by index Yes
Not sorted
HashSet Set No Not ordered No
Not sorted
LinkedHashSet Set No Ordered by No
insertion
Not sorted
TreeSet Set No Sorted either by No
natural order or by
your comparison
rules

[Link]
Class Interface Duplicates Ordered/ Synchronized
Allowed? Sorted

HashMap Map No Not ordered No


Not sorted

LinkedHashMap Map No Ordered No

Hashtable Map No Not ordered Yes


Not sorted

TreeMap Map No Sorted either by No


natural order or by
your comparison
rules

[Link]
Collection Advantages and
Disadvantages
• Advantages
 Can hold different types of objects.
 Resizable
• Disadvantages
 Must cast to correct type
 Cannot do compile-time type checking.

[Link]
Generics
• For checking the type of object during the
compilation time.
• Enclose the type within angular brackets <>.

[Link]
Date Class
• The [Link] class provides
several methods for formatting the date/time for
a default or a specific location, and yet you can
keep your code completely independent of the
locale conventions for months, days of the
week, days of the months, and so on.
• You create a locale object by using the Locale
class

[Link]
Process and Thread
• A process is a program that is currently
executing. Every process has at least one
thread running within it.
• Threads are referred to as lightweight
processes.
• A thread is a path of code execution through a
program, and each thread has its own local
variables, program counter (pointer to the
current instruction being executed), and
lifetime.

[Link]
Threads
• A thread is not an object
• A thread is a flow of control
• A thread is a series of executed statements
• A thread is a nested sequence of method calls

[Link]
MultiThreading and MultiTasking
• Multitasking is a mechanism to run many
Heavyweight processes simultaneously in a
different address space so context switch or
intercommunication between processes is
much expensive.
• Multithreading is a mechanism of running
various lightweight processes under single
process within its own space
• Multiprocessing there will be more than one
processor and each thread will be handled by a
different processor.

[Link]
Creation of a Thread
• By extending Thread class
• By implementing Runnable interface.
• Even a non-multithreaded program has one
thread of execution, called the main thread.
• Call the start() method to start the thread.
• When a thread is started, it calls the run()
method to make our thread to perform useful
work.

[Link]
1st Method: Extending the
Thread class
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
• Creating thread:
MyThread thr1 = new MyThread();
• Start Execution:
[Link]();

[Link]
2nd method: Threads by
implementing Runnable
interface
class ClassName implements Runnable{
public void run()
{
// thread body of execution
}
}
• Creating Object:
ClassName myObject = new ClassName();
• Creating Thread Object:
Thread thr1 = new Thread( myObject );
• Start Execution:
[Link]();
[Link]
Thread scheduling
• Thread scheduling is implementation dependent
and cannot be relied on to
act in the same way on every JVM
• The two approaches to scheduling are
 Preemptive - will be applied for thread with
highest and lowest priority
 Time-Sliced (Round-Robin) Scheduling – will be
applied when more than one thread has the
same priority.

[Link]
Threads within a process

THREAD
THREAD
STACK
STACK

SHARED
SHARED
MEMORY
MEMORY

THREAD
THREAD
DATA
DATA
THREAD
THREAD
TEXT
TEXT

 All threads are parts of a process hence communication


easier and simpler.
 Independent executables
[Link]
Thread States
A thread can in one of several possible states:
[Link]
Currently running
In control of CPU
[Link] to run
Can run but not yet given the chance
[Link]
Ready to run after being suspended or block
[Link]
Voluntarily allowed other threads to run
[Link]
Waiting for some resource or event to occur

[Link]
Thread Priorities
Why priorities?
Determine which thread receives CPU control
and gets to be executed first
Definition:
– Integer value ranging from 1 to 10
– Higher the thread priority → larger chance of
being executed first

– Example:
● Two threads are ready to run
● First thread: priority of 5, already running
● Second thread = priority of 10, comes in while first
thread is running

[Link]
Thread Synchronization
• Done in two ways
 To method
public synchronized void method()
{ }
 To block
synchronized(this)
{

[Link]
Wait() and notify()
• Wait() and notify should be used to restrict the
thread before doing an operation without a
notification from the other thread.
• Should be used along with the synchronized
block

[Link]
wait()
• When a thread enters a wait state, it does
nothing until it is notified by another thread.
• It also gives up it’s lock on the object when wait
is called.
public synchronized blah() {
wait();
… // do something
}

[Link]
notify()
• To awaken a thread, a different thread which
has a lock on the same object must call notify.
• When notify is called, the block that had the
lock on the object continues to have it’s lock it
releases it.
 Then a thread is awakened from its wait() and
can grab the lock and continue processing.
• There are two versions - notify() and notifyAll().
• Notify is safe only under 2 conditions:
 When only 1 thread is waiting, and thus
guaranteed to be awakened.
 When multiple threads are waiting on the same
condition, and it doesn’t matter which one
awakens.
• In general, use notifyAll()
[Link]
Thread Group
• You can include thread in a set of threads by
adding it to an instance of ThreadGroup
• ThreadGroups can contain not only threads but
also other ThreadGroups.

[Link]
Semaphore
• Semaphore is a synchronization mechanism,
which implements mutual exclusion among
processes to avoid race condition to access any
shared resource.
• Semaphore maintains a counter to implement
locking and unlocking. It avoids busy waiting. If
a critical section is in use, the calling process
will be removed from a run queue and put into a
sleep state.
• Java 5 comes with semaphore implementations
in the [Link] package so you don't
have to implement your own semaphores.
• A mutex is really a semaphore with value 1.
[Link]
Semaphores
• Semaphores have two purposes
 Mutex: Ensure threads don’t access critical
section at same time
 Scheduling constraints: Ensure threads
execute in specific order
• A semaphore is an IPC mechanism that is
implemented conceptually with at least these
two components
– a counter (int) variable
– a wait queue of processes
• And has at least these two operation
– wait for the semaphore to be free (p)
– signal that the semaphore is now free (v)
[Link]
Semaphore
• The semaphore has at least these possible
states:
 Free, or available, or not in use
 Not free, or unavailable, or in use
• Interpretation of the counter variable:
 If the counter is positive, then the semaphore is
free.
 If the counter is zero (or negative), then the
semaphore is in use (not free).

[Link]
Semaphore
• Cases using a semaphore S
1. If a process does a wait (p) on S, and if the
semaphore is free, then S is decremented
([Link] = [Link] – 1;)
2. If a process does a wait (p) on S and if S is not
free, then the process is blocked and put in S’s
wait queue.
3. If a process does a signal (v) on S and if there
is no process in the wait queue for S, then the
semaphore is set to free by incrementing its
counter (to positive).
4. If a signal (v) on S and there is a process in the
S queue, then the process at the head of the
queue is removed and unblocked (and can
continue to execute)
[Link]
IOStreams
• Usual Purpose: storing data to ‘nonvolatile‘
devices, e.g. harddisk
• Classes provided by package [Link]
• Data is transferred to devices by ‘streams‘

output - stream
Program Device

input - stream
Program Device

[Link]
keyboard
standard
input stream
CPU

standard
output MEM
stream
monitor
terminal
console

HDD
How does information
travel across?
Streams
[Link]
keyboard
standard
input stream
CPU

standard
output MEM
stream
monitor
terminal
console file
input
stream
LOAD HDD
How does information READ
travel across? file
files output
Streams stream
SAVE
[Link]
WRITE
IOStreams
• JAVA distinguishes between 2 types of
streams:
• Text – streams, containing ‘characters‘

Program I ‘ M A S T R I N G \n Device

• Binary Streams, containing 8 – bit information

Program 01101001 11101101 00000000 Device

[Link]
IOStreams
• Streams in JAVA are Objects, having
 2 types of streams (text / binary) and
 2 directions (input / output)

• Results in 4 base-classes dealing with I/O:


1. Reader: text-input
2. Writer: text-output
3. InputStream: byte-input
4. OutputStream: byte-output

[Link]
[Link]
Binary vs. TextFiles

pro con
Binary Efficient in terms Preinformation
of time and space about data needed
(input to understand
content
&output
stream)
Text(reader Human readable, Not efficient
contains
and writer) redundant
information

[Link]
Binary vs. TextFiles
• When use Text- / BinaryFiles ?
• ALWAYS use TextFiles for final results
• Binary Files might be used for non-final
interchange between programs
• Binary Files are always used for large amount
of data (images, videos etc.)

[Link]
Serialization
• Serialization: process of saving objects to a
stream i.e. in-memory object to a byte stream.
 Each object is assigned a serial number on the
stream
 If the same object is saved twice, only serial
number is written out the second time
 When reading, duplicate serial numbers are
restored as references to the same object
• The objects must be read from the stream in
the same order in which they were written.

[Link]
Serialization
• Why isn’t everything serializable?

 Security reasons – may not want contents of


objects printed out to disk, then anyone can print
out internal structure and analyze it
 Could also have temporary variables that are
useless once the program is done running.

[Link]
Serialization basics
• The requirements for serialization are
straightforward:
 Only class instances rather than primitive types
can be serialized.
 For an object to be serializable, its class or some
ancestor must implement the empty
Serializable interface.
 An empty interface is called a marker interface.
• The syntax for serialization is straightforward:
 An object is serialized by writing it to an
ObjectOutputStream.
 An object is deserialized by reading it from an
ObjectInputStream.

[Link]
Serialization code

=> Writing objects to a file


FileOutputStream out =
new FileOutputStream( “[Link]” );
ObjectOutputStream oos =
new ObjectOutputStream( out );
[Link]( new Date() );
[Link]();

[Link]
Deserialization code

=> Reading objects from a file


FileInputStream in =
new FileInputStream( “[Link]” );
ObjectInputStream ois =
new ObjectInputStream( in );
myObject d = (myObject_type) [Link]();
[Link]();

[Link]
Conditions for serializability
• If an object is to be serialized:
 The class must be declared as public
 The class must implement Serializable
 The class must have a no-argument constructor
 All fields of the class must be serializable: either
primitive types or serializable objects
• The Serializable interface does not define any methods!
 Question: What possible use is there for an interface
that does not declare any methods?
 Answer: Serializable is used as flag to tell Java it
needs to do extra work with this class

[Link]
Object Serialization (cont’d)
• writeObject() will throw an Error if the object
passed to it is not Serializable.
• You can control serialization by implementing
the Externalizable interface.
• readObject() returns something of type Object,
so it needs to be cast.

[Link]
Serialization and primitive types
• Technically, primitive types cannot be serialized
or deserialized. However, the
ObjectOutputStream implements the
DataOutput interface, which declares
methods such as writeInt to write primitive
types to streams.
• ObjectInputStream implements DataInput
for reading primitive types

[Link]
transient and static fields
• A field marked as transient is not impacted
by serialization.
 During deserialization, transient fields are
restored to their default values (e.g., transient
numeric fields are restored to zero).
• static fields are not impacted by serialization.

[Link]
JDBC
• Java DataBase Connectivity
• The JDBC ( Java Database Connectivity) API
defines interfaces and classes for writing
database applications in Java by making
database connections.
• JDBC provides RDBMS access by allowing you
to embed SQL inside Java code

[Link]
JDBC Architecture
Java application calls the JDBC library. JDBC
loads a driver which talks to the database. We
can change database engines without changing
database code.

import the [Link] package.

[Link]
Steps in JDBC
• To register the Driver:
 [Link]("[Link]");
• To Get the connecttion:
 Connection con = DriverManager.
getConnection("jdbc:odbc:Deepi","sa","pass@123");
• To create a SQL statement:
 Statement st=[Link]();
• To execute it:
 [Link](“DDL Query”);
 [Link](“DML Query”);
 [Link](“select query”);

[Link]
Garbage Collector (GC)
• Provides automated memory management.
• Deletes the unused objects in the memory.
• Only the JVM decides when to run the GC, you
can only suggest it.
• An object becomes eligible for Garbage
Collection when its last live reference
disappears.

[Link]
Garbage collection and
Performance
How Memory is allocated:
 Object creation
Object is constructed either on a memory heap or on
a stack.

 Memory heap
When new keyword is called memory is allocated in
the heap and returned when the reference is made
null
 Stack
During method calls, objects are created for method
arguments and method variables. These objects are
created on stack.
Such objects are eligible for garbage-collection when
they go out of scope.

[Link]
Garbage Collection
• Advantages of Garbage Collection :
 More productivity
 Program Integrity

• Disadvantages of Garbage Collection :


 program performance

[Link]
Finalize() method

• Finalize()
 Class Object has a finalize() method.
 Before gc happens the finalize() method is called
 It is called only once
 Finalize method can be overridden by the user.
 Finalize can be used to make an object not to be
garbage collected

[Link]
Classical Algorithms
• Three classical algorithms
 Mark-sweep
 Reference counting
 Semispace
• Tweaks
 Generational garbage collection (JAVA
DEFAULT)
• Out of scope
 Parallel –perform GC in parallel
 Concurrent –run GC at same time as app
 Real-time–ensure bounded pause times

[Link]
Mark-Sweep
• Start with roots
 Global variables, variables on stack& in
registers
• Recursively visit every object through pointers
 Markevery object we find (set mark bit)
• Everything not marked = garbage
 Can then sweep heap for unmarked
objectsand free them

[Link]
Annotations
• Annotations in Java is all about adding meta-
data facility to the Java Elements like
 package declarations,
 class,
 constructors,
 methods,
 fields,
 variables and etc
• An annotation indicates that the declared
element should be processed in some special
way by a compiler, development tool,
deployment tool, or during runtime.
• Annotations are defined using an @ syntax

[Link]
Structure of Java Compiler

Type Class File


Parser Checker Writer
Source File
class C {
@NonNull
Class
Object field; File
C(@NonNull
Object p) {
field = p;
}

@NonNull
Object get() {
return field;
} Comments
}

Error

[Link]
Structure of Java5 Compiler
Type Annotation Class File
Parser Checker Checker Writer
Source File
class C { Class
@NonNull
Object field; File
C(@NonNull
Object p) {
field = p;
}

@NonNull
Object get() {
return field;
}
}

Program
with
annotations Error Error

Annotation
Checker
Plugins
[Link]
Annotation Types
• Marker
• Single-Element
• Full-value or multi-value

[Link]
Marker
• Marker annotations take no parameters. They
are used to mark a Java element to be
processed in a particular way.
• Example:
public @interface MyAnnotation {
}

• Usage:
@MyAnnotation
public void mymethod() {
....
}

[Link]
Single-Element
• Single-element, or single-value type, annotations
provide a single piece of data only. This can be
represented with a data=value pair or, simply with the
value (a shortcut syntax) only, within parenthesis.

• Example:
public @interface MyAnnotation {
String doSomething();
}
• Usage:
@MyAnnotation ("What to do")
public void mymethod() {
....
}

[Link]
Full-value or multi-value
• Full-value type annotations have multiple data members.
• Example:
public @interface MyAnnotation {
String doSomething();
int count;
String date();
}
• Usage:
@MyAnnotation (doSomething=
"What to do",
count=1,
date="09-09-2005")
public void mymethod() {
....
}
[Link]
The Built-In Annotations
• Java defines seven built-in annotations.
• Four are imported from [Link]
• @Retention,
• @Documented,
• @Target,
• and @Inherited.
• Three are included in [Link].
 @Override,
 @Deprecated,
 and @SuppressWarnings.

[Link]
The Target annotation
• @Target([Link])
 can be applied to any element of a class
• @Target([Link])
 can be applied to a field or property
• @Target([Link])
 can be applied to a method level annotation
• @Target([Link])
 can be applied to the parameters of a method
• @Target([Link])
 can be applied to constructors
• @Target(ElementType.LOCAL_VARIABLE)
 can be applied to local variables
• @Target(ElementType.ANNOTATION_TYPE)
 indicates that the declared type itself is a

[Link]
Reflection
• When we have some Annotations defined in the
source code and have a mechanism through
which we can say that to what extent the
Annotations should be retained. The three
possible ways of telling this are,
 Retain the Annotation in the Source Code only
 Retain the Annotation in the Class file also.
 Retain the Annotation Definition during the Run-
time so that JVM can make use of it.
• The Annotation that is used to achieve this is
@Retention and it takes a possible values of
SOURCE, CLASS and RUNTIME defined in
RetentionPolicy Enumeration.
[Link]
Need of Annotation
• Less coding
• Easier to change
• Smarter development.
• Providing information to the Compiler.
• Providing information to the tools.
• Providing information to the Runtime System

[Link]
[Link]

[Link]

[Link]

Common questions

Powered by AI

Using the 'final' keyword in Java has significant implications for variables, methods, and classes regarding inheritance and polymorphism. Declaring a variable final makes it a constant, and its value cannot change once initialized, supporting data integrity. A final method cannot be overridden by any subclass, ensuring critical functionality remains untouched during inheritance and enhancing security by preventing subclass-induced behavior changes. Declaring a class as final prevents it from being subclassed, effectively sealing the class's structure and prohibiting polymorphic use of its instances via subclassing . While these constraints support application reliability and consistency, they also limit flexibility in polymorphically adapting and extending behaviors within inheritance hierarchies.

Static nested classes differ from other inner classes as they are not associated with an instance of their outer class. As a result, they can only access static members of the outer class and do not have a reference to its instance members. This distinct behavior implies that static nested classes act more like top-level classes nested within the class purely for organizational purposes, not relying on or affecting the state of their enclosing class instance directly . In contrast, non-static inner classes can access all fields and methods of the outer class, including instance members, through a reference to the outer class object.

Method-local inner classes in Java are restricted from accessing non-final variables of the enclosing method because these classes influence the lifetime of the variables they capture. A method-local inner class can outlive the invocation of its enclosing method if the instance of the class is returned or passed elsewhere, leading to dependencies on variables that are no longer in scope. Access to non-final variables would require capturing their changing state, which could cause memory inconsistencies or data instability once the method execution completes. By allowing access only to final variables, Java ensures thread safety and lifecycle consistency .

Immutable objects in Java, such as Strings, offer several advantages including thread safety, as their immutable state means that different threads can access them without concern for data corruption . They also allow for memory savings since the same immutable object can be referenced multiple times instead of creating new objects. However, they can be less efficient when frequent modifications are needed, as every modification creates a new object, increasing memory footprint due to more objects being created and discarded . This can lead to inefficiencies where multiple transformations are required, thereby wasting memory and consuming more time for operations .

Thread synchronization is critical in Java multithreading to prevent race conditions and ensure thread safety when multiple threads try to access shared resources concurrently. Without synchronization, threads may interfere with each other, leading to inconsistent data or unpredictable behavior. Synchronization can be achieved via 'synchronized' methods or blocks. Methods can be synchronized by adding the 'synchronized' keyword to the method signature, ensuring that only one thread can execute a method at a time . A synchronized block is used to lock an object for mutual exclusion. While a thread is active within the synchronized block, all other threads that want to execute instructions on the object wait . Additionally, Java provides wait(), notify(), and notifyAll() methods to manage the communication between threads when accessing synchronized blocks .

Semaphores in Java concurrency play the role of controlling access to shared resources by multiple processes, thereby implementing mutual exclusion and avoiding race conditions. A semaphore can either restrict threads from entering a critical section simultaneously by maintaining a count of permits available or ensure the orderly execution of threads. To implement mutual exclusion, a semaphore with a single permit, commonly referred to as a mutex, can be used. Threads call `acquire()` to enter the critical section, decrementing the permit count, and `release()` to leave, incrementing the permit count. If the permit count is zero (locked), threads attempting an acquire operation are blocked until a release occurs .

The 'instanceof' operator in Java enhances type safety by allowing programmers to check if an object is an instance of a specific class or subclass before performing operations on it. This avoids ClassCastException at runtime by ensuring that type conversions are safe. For example, it can be used before casting an object to its proper subclass to ensure the cast is valid: `if (e instanceof Manager) { Manager m = (Manager) e; }`. Casting is used to restore the full functionality of the object by allowing it to be referenced with all methods and properties available in its specific class .

Java distinguishes between checked and unchecked exceptions based on their origin and how they are enforced during compile-time. Checked exceptions are exceptions that are checked at compile time, and they are typically related to external factors that a program interacts with, such as I/O operations. Developers must write code to handle these exceptions or declare them in the method signature with throws keyword . Unchecked exceptions, on the other hand, are runtime exceptions that occur due to programming errors and are not checked at compile time, allowing developers to focus on correcting the code instead of catching them . This distinction compels developers to handle environmental errors proactively, ensuring robustness in application-fault-prone areas while allowing runtime errors to be fixed during development at the programmer's discretion.

Anonymous inner classes in Java work by allowing the creation of a subclass without explicitly naming it. They are typically used to instantiate objects with specific methods implementations or overriding existing ones on-the-fly. An anonymous inner class is defined within an expression at the point in the code where the object is needed, often used to provide concise event handler implementations. They cannot have constructors because they do not have a named class definition, which constructors require. Instead, instance initializer blocks can be used to perform any necessary initialization . This constraint simplifies their use, focuses on brevity of code, and enhances readability in applications where full class definitions would incur verbosity.

The primary advantage of using the static keyword is that it allows variables and methods to be associated with the class itself rather than any particular instance of the class. This means that static members are shared across all instances of the class and only one copy exists in memory, which improves memory usage efficiency as those members are loaded into the memory only once . Static methods can only access static variables, but normal methods can access both static and instance variables .

You might also like