Core Java(Part-9)

Access modifier

For classes, there are only two access modifiers: public and default (no modifier). private is not allowed for top-level classes.

Access modifiers control how much access you give to your variables, methods, or classes from other parts of the program.

Method:

Access moodier return type Methodname(){

}

default

Default: If you don’t use any access modifier for a class, method, or variable, then the JVM applies the default access modifier.

Accessibility: restricted with the same package.

package modifiers;
class ModifierDefault{
     String name="Khelendra";

     void display(){
         System.out.println("Hello"+ name);
     }
}

public class Test {
    public static void main(String args[]){
        ModifierDefault modifierDefault=new ModifierDefault();
        modifierDefault.display();
        System.out.println(modifierDefault.name);

    }
}

You can access within the same package

package modifiers;

public class DefaultTest {
    public static void main(String[] args) {
        ModifierDefault modifierDefault=new ModifierDefault();
        System.out.println(modifierDefault.name);
    }
}

private

Private: most restricted

Accessibility: Its accessibility is limited to within the class, and it cannot be accessed from outside the class directly.
To access a private variable, you need to create getter and setter methods.

package modifiers;

class PrivateModifier{
    private String name="Khelendra";
    private void display(){
        System.out.println("Hello "+ name);
    }


    public static void main(String[] args) {
      PrivateModifier privateModifier=new PrivateModifier();
      privateModifier.display();
      System.out.println(privateModifier.name);

    }

}

Here in next program we use getter method to access private variable

package modifiers;

class PrivateModifier{
    private String name="Khelendra";
    private void display(){
        System.out.println("Hello "+ name);
    }
    private String getName(){
        return name;
    }
}

public class ModifierPrivate{
    public static void main(String[] args) {
      PrivateModifier privateModifier=new PrivateModifier();
      System.out.println(privateModifier.getName());
      System.out.println(privateModifier.getName());

    }
}

protected

The protected access modifier is used within the same package and also in subclasses, even if they are in a different package.

The protected keyword can be applied to variables and methods, but not to top-level classes.

Write a program protected method access inside same package.

package mypackage;

class A {
    protected void show() {
        System.out.println("Hello from A");
    }
}

public class Test2 {
    public static void main(String[] args) {
        A a = new A();
        a.show(); // Calling protected method
    }
}

Write a program protected constructor example

package mypackage;

class A {
    protected A() {
        System.out.println("Protected constructor called");
    }
}

public class Test5 extends A {
    public static void main(String[] args) {
        Test5 t = new Test5(); // Accessing protected constructor
    }
}

Write a program protected method access from child class different package

package1

package mypackage1;

public class A {
    protected void display() {
        System.out.println("Display from A");
    }
}

package2

package mypackage2;
import mypackage1.A;

class B extends A {
    void callDisplay() {
        display(); // Can call protected method from parent
    }
}

public class Test6 {
    public static void main(String[] args) {
        B b = new B();
        b.callDisplay();
    }
}

Summary

  • Visible inside same package normally.

  • Visible outside package only in child classes.

  • Can't access protected members by creating a normal object outside package.

public

Accessibility: You can access your methods, variables, and classes within the same package or from a different package.
To access a class from a different package, you need to import that package or class using the import keyword.

package modifiers;

public class ModifierPublic{
  public String name="Thakur";
  public void display(){
     System.out.println("Hello "+name);
  }
}


 class PublicTest {
  public static void main(String[] args) {
   ModifierPublic modifierPublic=new ModifierPublic();
     modifierPublic.display();
  }
}

Output

Hello Thakur
Thakur

In the program above, you can see that we can access public methods and variables from a different class by creating an object of that class.

In the program below, you can see that we can access variables and methods from a different package by importing that package and class.

package protectedTest;
import modifiers.ModifierPublic;
public class ProtectedTest extends ModifierPublic{
    public static void main(String[] args) {
        ProtectedTest protectedTest= new ProtectedTest();
        protectedTest.display();
        System.out.println(protectedTest.name);

    }
}

Output

Hello Thakur
Thakur
ModifierScope
publicEverywhere (full world
privateOnly inside same class (secret
protectedSame package + child classes (family
defaultSame package only (neighbors
class Example { 
       public int a; // Everyone can use private int b; 
                    // Only inside this class protected int c; 
                   //Same package + child classes int d; 
                  //Default (same package)
 }
Access ModifierWho can see it?Lame Example
publicEveryone everywhereOpen ground — anyone can come!
privateOnly inside the same classSecret diary — only you can read!
protectedOnly in same package + child classesFamily members and close relatives can come.
Default (no keyword)Only in same packageNeighbors only (not outsiders)!

Exceptional Handling

An unwanted event that disturb normal flow of the execution.

"If something goes wrong, don't crash — handle it nicely!"

Real Life Example

Imagine you're giving someone a glass of juice.
But what if the glass is broken?

Instead of spilling juice everywhere, you:

Check the glass
Catch the problem
Handle it: "Oops! Get another glass."

That’s exception handling!

try {
        // risky code here
    } 
catch(Exception e) {
        // handle the error here
        } 
finally {
        // optional: always runs
        }

Type of exception

1.Checked Exception

a. exception which force complier to handle it explicitly

i. IOException

ii. SQLException

2.Unchecked Exception

a. not checked by compiler at compile at compile-time but thrown at runtime

i. 10/0—→Arithmetic exception

ii. NullPointerException

iii. index out of bound Exception

Note:- Whether exception is checked or unchecked compulsory it should occur at runtime only and there is no chance of occurring any exception at compile time

Handling are abnormal termination of program is called exception handling.

package exception;
class ExceptionTest{
    void print1(){
        print2();

    }
    void print2(){
        print3();
    }
    void print3(){
        print4();
    }
    void print4(){
        print5();
    }
    void print5(){
        System.out.println(10/0);
    }
}
public class ExceptionWorking {
    public static void main(String[] args) {


        ExceptionTest exceptionTest = new ExceptionTest();
        exceptionTest.print1();
    }
}

Explanation

In the above program in main() method you create the reference of ExceptionTest class with the name of exceptionTest then call the print1() method with that reference

Step1:-exceptionTest.print1();

Step2:-then inside print1() body you calls print2()

Step3:-and inside print2() body you calls print3()

Step4:-and again inside print3() body you calls print4()

Step5:-and in print4() body you calls print5()

Step6:-in print5() body you print the value of 10/0 here it throws exception

Step7:-then it goes back to the method who call the print5() means print4() and ask him that do have exception handler it says no.

Step8:-it’s goes to caller of print4(), means to print3() there also he ask the same question do you have exception handler it says no.

Step9:-after then it’s goes to caller of print3(), means to print2() there also he ask the same question do you have exception handler it says no.

Step10:-then it’s goes to caller of print2(), means to print1() there also he ask the same question do you have exception handler it says no.

Step11:-it’s goes to caller of print1(), means to main() there also he ask the same question do you have exception handler it says no.

*Step12:-\*In final when no one is handling that exception then JVM component default exception handler is handle that exception

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero at
exception.ExceptionTest.print5(ExceptionWorking.java:17) at
    exception.ExceptionTest.print4(ExceptionWorking.java:14) at
    exception.ExceptionTest.print3(ExceptionWorking.java:11) at
    exception.ExceptionTest.print2(ExceptionWorking.java:8) at
    exception.ExceptionTest.print1(ExceptionWorking.java:4) at
    exception.ExceptionWorking.main(ExceptionWorking.java:25)

**Note:-**If you write something in try block and in one of the line one exception is come in try block then JVM create an object for that exception and throw it at the catch block (Exception e) reference variable.

Difference between throw and throws

KeywordMeaning in Simple Words
throw"I’m throwing an exception right now!" (used inside method)
throws"Hey, this method might throw an exception!" (written in method signature)
  • throw → "Oops! This plate is too hot — I’m throwing it right now!"

  • throws → "Warning: This dish might be too hot!" ☠️ (just a warning on the menu)

Using throw

public class ThrowExample {
    public static void main(String[] args) {
        int age = 10;

        if (age < 18) {
            throw new ArithmeticException("You are not eligible to vote");
        }

        System.out.println("You can vote!");
    }
}

throw is used to throw the exception manually.

Using throws

public class ThrowsExample {

    // method says: "I might throw an exception"
    static void check() throws InterruptedException {
        Thread.sleep(1000);  // may throw InterruptedException
        System.out.println("Checked!");
    }

    public static void main(String[] args) throws InterruptedException {
        check();  // calling the method
    }
}

throws is used to declare that a method might throw an exception.

finally

"The finally block is used in exception handling along with try and catch. The finally block always executes, whether or not the try block throws an exception. It will run regardless, and any code written inside the finally block will be executed and printed to the command prompt."

The finally block always runs, whether:

  • there's an exception,

  • no exception,

  • or even if you return from the method.

It’s mostly used for clean-up work like:

  • closing files

  • releasing database connections

  • freeing up memory

prog:-

package exception;

public class FinallyDemo {
    public static void main(String[] args) {
        try{
            System.out.println(10/0);
        }
        catch (Exception e){
            System.out.println("I am in catch");
            e.printStackTrace();

        }
        finally{
            System.out.println("Finally block");
            System.out.println("Best class in india");
            System.out.println("Spark 2.0");
        }

    }
}

Output

I am in catch
Finally block
Best class in india
        Spark 2.0
java.lang.ArithmeticException: / by zero
at exception.FinallyDemo.main(FinallyDemo.java:6)

In finally block we always write clean up code. Cleanup code means Whenever we build a connection with an Database then i open the connection then always in finally block i close that Database connection in finally block.

Program using exit() methods

package exception;
class FinallyTest{
    int m1(){
        try{
            System.out.println(10/0);
            System.out.println("try block execution ");
            return 999;
        }
        catch(Exception e){
            System.out.println("catch block execution");
            System.exit(0);
             return 222;
        }

        finally{

            System.out.println("finally block executed");
            return 888;
        }


    }
}
public class FinallyDemo2 {
    public static void main(String[] args) {
        FinallyTest finallyTest=new FinallyTest();
       int i= finallyTest.m1();
       System.out.println(i);

    }

}

Output

catch block execution

In above program finally why didn’t execute because we use System.exit(0); in catch block. What did System.exit(0) do? System.exit(0); shutdown the JVM so after printing catch block first statement it shutdown the JVM so the finally block didn’t execute.

Difference between Final, Finally and Finalize?

Final

.final is a keyword which we use with variable, methods and class. .In variable when we write final with datatype and variable name then we can’t reinitialize the value it behave like a constant. .In method we can’t override the inherit method of Parent class in Child class. .In class when we use final keyword it restrict the inheritance you can’t extends the Parent class in Child class.

Finally

finally is a block which is used in exception handling. It’s main advantage is finally block code always execute even after throwing the exception or not. You can only stop finally block code execution only by using System.exit(0); it stop the JVM, so after System.exit(0); whatever the code you written they didn’t execute.

Finalize

It is used in garbage collector. Garbage collector collect that object which doesn’t have any reference variable means (without reference variable).Before destroying the object garbage collector call the finalize method before cleanup activity.

0
Subscribe to my newsletter

Read articles from Khelendra Kumar Thakur directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Khelendra Kumar Thakur
Khelendra Kumar Thakur