JAVA - Copy
JAVA - Copy
Secure, Portable and Robust: Java programs are safe and secure to
download from internet.
At the core of the problem is the fact that malicious code can cause its
damage due to unauthorized access gained to system resources. Java
achieved this protection by confining a program to the Java execution
environment and not allowing it access to other parts of the computer.
Package Section: It must be the first line of a java program or can be omitted if the class is
to be kept only in the default package.
The package statement defines a namespace in which classes are stored, based on
functionality.
If omitted, the classes are put into the default package, which has no name.
Import Section: Specifies the location to use a class or package into a program.
Class / Interface section: A java program may contain several classes or interface.
Class with Main Method: Every Java stand-alone program requires the main method as
the starting point of the program. This is an essential part of a Java program. There may be
many classes in a Java program code file, and only one class defines the main method.
Example:
// ----- Package Section -------
Package mypack;
// -------- Import Section -------
import java.util.Date; // This line will import only one class from the util package
import java.awt.*; // This line will import all classes available in awt package
// ----------- Class / Interface Section ----------
class A {
// Class Body
}
interface B {
// Interface Body
}
// ----------- Main Method Section ----------
public class Test{
public static void main(String[] args){
// body of main method
}
}
Java Tokens
Tokens are the basic building blocks of the java programming language that are used in
constructing expressions, statements and blocks.
Keywords: these words are already been defined by the language and have a predefined
meaning and use. Key words cannot be used as a variable, method, class or interface
[] Brackets Used to declare array types. Also used when dereferencing array
values.
if
The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths.
General Syntax:
if (condition)
statement1 / { if Block }; else
statement2 / { else Block};
Example:
class ifelsetest{
public static void main(String[] args)
{
int num=10;
if(num%2 == 0)
{
System.out.println(“Number is EVEN”);
}
else {
System.out.println(“Number is ODD”);
}
}
}
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-else-
if ladder.
General Syntax:
if(condition)
statement;
else
if(condition)
statement;
else if(condition)
Statement;
.
.
.
.
else statement;
Example:
class ladderifelsetest
{
public static void main(String[] args)
{
int num=10;
if(num> 0)
{
System.out.println(“Number is +VE”);
}
else if(num<0)
{
System.out.println(“Number is -VE”);
}
else {
System.out.println(“Number is ODD”);
}
}
}
byte, short, int, and long, which are for whole-valued signed numbers.
byte 8 1 byte –128 to 127
short 16 2 byte –32,768 to 32,767
int 32 4 byte –2,147,483,648 to
2,147,483,647
long 64 6 byte –9,223,372,036,854,775,808 to
9,223,372,036,854,775,80
7
float and double, which represent numbers with fractional precision.
float 32 4 byte 1.4e–045 to 3.4e+038
double 64 8 byte 4.9e–324 to 1.8e+308
OOPS
1) Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code.
2) Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
3) Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
Why use inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
1) Single Inheritance Example
When a class inherits another class, it is known as a single inheritance.
Example
Dog class inherits the Animal class
class Animal
{
Public void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
Public void bark()
{
System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
}
}
4) Polymorphism
Advantages of Polymorphism
Code Reusability
Methods in subclasses to override methods in their superclass, enabling code reuse
Flexibility and Extensibility
Allows subclasses to provide their own implementations of methods defined in the
superclass, making it easier to extend and customize behavior without modifying existing
code.
Reduced Code Complexity
Helps reduce code complexity by promoting a modular and hierarchical class structure,
making it easier to understand, maintain, and extend large-scale software systems.
Types of Polymorphism
1. Compile-time polymorphism
2. Runtime polymorphism.
In this process, an overridden method is called through the reference variable of a superclass.
Example
We are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method.
We are calling the run method by the reference variable of Parent class.
class Bike
{
void run(){System.out.println("running");}
}
class Splendor extends Bike
{
void run(){System.out.println("running safely with 60km");}
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
Method overloading increases the readability of the program.
Different ways to overload the method
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
OR
If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
5) Encapsulation in Java
class Account
{
private long acc_no;
private String name, email;
private float amount;
public long getAcc_no()
{
return acc_no;
}
public void setAcc_no(long acc_no)
{
this.acc_no = acc_no;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public float getAmount()
{ return amount;
}
public void setAmount(float amount)
{
this.amount = amount;
}
}
System.out.println(
acc.getAcc_no() + " " + acc.getName() + " "
+ acc.getEmail() + " " + acc.getAmount());
}
}
Advantages of Encapsulation
Data Hiding: it is a way of restricting the access of our data members by hiding the
implementation details.
Increased Flexibility: We can make the variables of the class read-only or write-only
depending on our requirements.
Reusability
6) Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. It shows only essential things to the user and hides the internal
details
Ways to achieve Abstraction
Using Abstract Class (0 to 100%)
Abstract classes can have implementations with abstract methods. Abstract methods are
declared to have no body, leaving their implementation to subclasses.
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Interface in Java
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
Interfaces can have abstract methods and variables. It cannot have a method body.
Syntax:
interface <interface_name>{
Examples:
1)
interface printable
{
void print();
}
class Example1 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
Example1 obj = new Example1();
obj.print();
}
}
2)
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Multiple Inheritance in Java by Interface
Multiple inheritance is not supported in the case of class because of ambiguity. However, it
is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class.
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example:
Example:
public abstract class Shape{
public interface Drawable{
public abstract void draw();
void draw();
}
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Usage of Java super Keyword
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor.
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
class Student extends Person {
Student()
{
super();
System.out.println("Student class Constructor");
}
}
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor
1. variable
2. method
3. class
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
When to use a final variable?
Final variables must be used only for the values that we want to remain constant
throughout the execution of the program.
public class ConstantExample
{
public static void main(String[] args)
{
final double PI = 3.14159;
System.out.println("Value of PI: " + PI);
}
}
2) Java Final Method
When a method is declared with final keyword, it is called a final method in Java. A final
method cannot be overridden.
We must declare methods with the final keyword for which we are required to follow the
same implementation throughout all the derived classes.
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Bike11
{
int cube(final int n)
{
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
class Test {
int a;
int b;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test(10, 20);
object.display();
}
}
Output
a = 10 b = 20
class Test {
void display()
{
// calling function show()
this.show();
System.out.println("Inside display function");
}
void show()
{
System.out.println("Inside show function");
}
public static void main(String args[])
{
Test t1 = new Test();
t1.display();
}
}
Output
Inside show function
Inside display function
Types of Exceptions
1. Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means that the
compiler verifies that the code handles these exceptions either by catching them or declaring
them in the method signature using the throws keyword.
2. Unchecked Exceptions
Unchecked exceptions, also known as runtime exceptions, are not checked at compile-
time. These exceptions usually occur due to programming errors, such as logic errors or
incorrect assumptions in the code.
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
o Finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code does not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("Finally block is always executed");
}
System.out.println("Rest of the code...");
}
}
Output:
5
Finally block is always executed
Rest of the code…
Case 2: When an exception occurr but not handled by the catch block
try {
System.out.println("Inside the try block");
try {
System.out.println("Inside try block");
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow..
.
In the above example exception occurs in the m() method where it is not handled, so it is
propagated to the previous n() method where it is not handled, again it is propagated to the
p() method where exception is handled.
Output:
Java throws keyword
throws is a keyword in Java that is used in the signature of a method to indicate that this
method might throw one of the listed type exceptions.
In a program, if there is a chance of raising an exception then the compiler always warns us
about it and compulsorily we should handle that checked exception, Otherwise, we will get
compile time error saying unreported exception XXX must be caught or declared to be
thrown. To prevent this compile time error we can handle the exception in two ways:
We can use the throws keyword to delegate the responsibility of exception handling to the
caller (It may be a method or JVM) then the caller method is responsible to handle that
exception.
class tst {
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output
error: unreported exception InterruptedException; must be caught or declared to be thrown
In the above program, we are getting compile time error because there is a chance of
exception if the main thread is going to sleep, other threads get the chance to execute the
main() method which will cause InterruptedException.
class tst {
public static void main(String[] args)
throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output
Hello Geeks
Using throws
Type of exception
keyword, we can
Using throw keyword,
declare both checked
we can only
and unchecked
propagate unchecked
2. Uses exceptions. However,
exception i.e., the
the throws keyword
checked exception
can be used to
cannot be propagated
propagate checked
using throw only.
exceptions only.
The keyword throw is The keyword throws
3. Declaration used within the is used with the
method. method signature.
We can declare
multiple exceptions
We are allowed to using throws keyword
throw only one that can be thrown by
Internal
4. exception at a time the method.
Implementation
i.e. we cannot throw
multiple exceptions. For example, main()
throws IOException,
SQLException.
In Java, Exception, and Error both are subclasses of the Java Throwable class that belongs
to java.lang package. But there exist some significant differences between them.
Multithreading
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
It is a static method that puts the thread to sleep for a certain time been
sleep()
passed as an argument to it
notifyAll() It gives out a notification to all the thread in the waiting state
o Runnable: A thread that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant
of time. It is the duty of the thread scheduler to provide the thread time to run.
o A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and when that
allocated time slice is over, the thread voluntarily gives up the CPU to the other
thread, so that the other threads can also run for their slice of time. Whenever such a
scenario occurs, all those threads that are willing to run, waiting for their turn to run,
lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen
thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name
is A) has entered the critical section of a code and is not willing to leave that critical section.
In such a scenario, another thread (its name is B) has to wait forever, which leads to
starvation.
To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the
waiting state for a specific span of time, and not forever.
Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.
In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent the
state of a thread.