Core Java
Core Java
Object means a real-world entity such as a pen, chair, An Object can be defined as an instance of a class
public class ObjEx {
int x = 5;
public static void main(String[] args) {
ObjEx myObj = new ObjEx();
System.out.println(myObj.x);
}
}
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
public class ClassEx {
int x = 5;
}
Method/functions
it is a block of code which only runs when it is called.& used to perform certain actions.
public class MethodEx {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
Polymorphism(Code Reusability)
If one task is performed in different ways, it is known as polymorphism.ex: to convince the customer
differently, to draw some shape. we use method overloading and method overriding to achieve
polymorphism.it is the ability of a message to be displayed in more than one form.
Types of Polymorphism
When there are multiple functions with the same name but different parameters, then the functions are
1
said to be overloaded Obj is bound with their functionality at compile time
package MyPackage2;// main class
package MyPackage2;//overloading
public class Student {
public void read(){
System.out.println("reading xyz book");
}
public void read(String bookName ){
System.out.println("reading "+bookName);
}
}
This type of polymorphism is achieved by Function OverridingThe function call is resolved at runtime in
runtime polymorphism. Obj is bound with thier functionality at run time.
package MyPackage2;// main class
Binding (or wrapping) code and data together into a single unit.A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are private here.in
this a class's variables are hidden from other classes and can only be accessed by the methods of the class
in which they are found.
2. Provide public setter and getter methods to modify & view the variable values.
package MyPackage2;
2
public int getEmp_id()
{
return emp_id;
}
}
class Company{
public static void main(String args[]){
Employee employee=new Employee();
employee.setEmp_id(102);
System.out.println(employee.getEmp_id());
}
}
//output 102
It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class.
In Java, Inheritance means creating new classes based on existing ones. A class that inherits from another class can
reuse the methods and fields of that class. (using extends keyword)
Inheritance Types
⦁ Multilevel Inheritance- a derived class will be inheriting a base class, and as well as the derived class also
acts as the base class for other classes
package MyPackage2;
class A {
void showA() {
System.out.println("a class method ");
}
}
class B extends A{
void showB (){
3
System.out.println("----------------");
}
⦁ Hierarchical Inheritance - one class serves as a superclass (base class) for more than one sub class.
package MyPackage2;
⦁ Multiple Inheritance one class can have more than one superclass and inherit features from all parent
classes. Java does not support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces.(ambiguity)
⦁ Hybrid Inheritance mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, hybrid inheritance is also not possible with classes. In Java, we can
achieve hybrid inheritance only through Interfaces.
4
Encapsulation vs Data Abstraction
While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing
the interface to the user and hiding the details of implementation.
Encapsulated classes are Java classes that follow data hiding and abstraction We can implement abstraction by using
abstract classes and interfaces.
Encapsulation is a procedure that takes place at the implementation level, while abstraction is a design-level process
Abstraction
(detail hiding/implementation hiding) 2 ways to achive abstraction = using abstract class (between
0-100%) and interface (purely 100)% it is a process which displays only the information needed and hides
the unnecessary information.(Data hiding)
An abstract class is a type of class that declares one or more abstract methods. An abstract method is a
method that has a method definition but not implementation.
Abstract methods are used when two or more subclasses do the same task in different ways and through
different implementations. An abstract class can have both methods, i.e., abstract methods and regular
methods.
If a regular class extends an abtract class then the class must have to implement all the abstract methods
of abstract parent class or it has to be declared abstract as well.
package MyPackage2;//abstraction
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle{
@Override
void start() {
System.out.println("car starts with key");
}
}
class Scooter extends Vehicle{
@Override
void start() {
System.out.println("Scooter starts with kick");
}
public static void main(String [] args){
Car car= new Car();
car.start();
Scooter scooter= new Scooter();
scooter.start();
}
Interface in Java (class ko krna kya h)(used to achieve abstraction)(loose coupling)(supports multiple inheritance)
5
An interface in java is a blueprint of a class. It has static constants and abstract methods.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 Interface also represents
IS-A relationship. It cannot be instantiated just like abstract class. There are mainly three reasons to use
interface.
package MyPackage2;
public interface I1 {
abstract void show();
}
class Test implements I1{
@Override
public void show() {
System.out.println("hi");
}
public static void main(String args[]){
Test test =new Test();
test.show();
}
}
Coupling in Java
Coupling refers to the relationship between two classes. It indicates the knowledge one object or class has
of another. That means that if one class changes its properties or behaviour, it will affect the dependent
changes in the other class
Tight coupling: If one class is strongly interrelated to another class, it is said to have a tight coupling with
that class.
Loose coupling: If one class is weakly interrelated to another class, it is said to have loose coupling with
that class. Loose coupling is preferred over tight coupling.
Exception Handling used to handle the runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.so that the regular flow of the application can be preserved. Error:
An Error indicates a serious problem that a reasonable application should not try to catch.Exception: any
unexpected/ unwanted event that occurs during execution of program at runtime that disturbs the
normal flow of program.
6
obj class is the parent class of all class in java and throwable is the parent class of exception
Types of Exceptions
package MyPackage2.ExceptionHandling;
public class a {
public static void main(String args []) {
System.out.println("start");
int result = 0;
try {
int n1 = 100;
int n2 = 0;
System.out.println("2no.");
result = n1 / n2;
} catch (Exception e) {
System.out.println("n2=!0");
System.out.println(e.getMessage());
}
finally {
System.out.println("hey finally");
}
System.out.println(result);
System.out.println("terminate");
}
}
7
OR
package MyPackage2.ExceptionHandling;
public class Test {
public static void main (String args []){
try {
System.out.println(100 / 0);
} catch (Exception e) {
System.out.println("exception");
System.out.println(e.getMessage());
}
}
}
we can handle the exception using 5 keywords i.e. try , catch, finally,throw,throws.
e.printStackTrace,e,e.toString,e.getMessage
finally block- it always executed wheather exception is handled or not jo resources try me open kiye vo yha close
honge/clean up
we can use multiple catch blocks with one try but we can use single finally block with one try.
i.e using system.exit .// causing a fatal error that causes the process to abort
throw and throws -throw used for custom exception / user defined exception user will make the
exception obj.
import java.util.Scanner;
8
}
class voting {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter ur age");
try {
int age = s.nextInt();
if (age < 18) {
throw new Throw("u r not eligible for vote ");
} else {
System.out.println("u can vote");
}
}
catch (Throw e) {
System.out.println("exception"); }
}
}
Throws keyword- it is used to declare an exception it gives an indication to the caller method
that there may occur an exception so its better for caller method to provide the exception
handling code so that normal flow can be maintained.
-> it is used to declare exceptions in code and it is used along with calling methods.
package MyPackage2.ExceptionHandling;
import java.io.IOException;
package MyPackage2.ExceptionHandling;
import java.io.IOException;
Custom Exception can be checked or unchecked exception super keyword is used to make description available to
the default exception handler we can use try catch or throws in case of (customized) checked exception.
9
Custom Checked Exception using throws
package MyPackage2.ExceptionHandling;
} catch (CustomCheckedExceptionTry e) {
e.printStackTrace();
}
}
}
System.out.println("hu");
}
}`
Packages are used to grp related classes packages helps in avoiding name conflicts 2 types of packages built in
packages(java api /scanner ) & User defined package (Custom packages)
10
Multi threading
Multitasking performing multiple task at a time increases performance of CPU we can acheive Multitasking by 2 ways i.e
process based (multiprocessing) & thread based (multi threading)
Multiprocessing when 1 system is connected to multiple processors(CPU) in order to complete the task.it is suitable at system
level(os level)
Process(an executing program)(heavyweight)takes more time in context switching & inter Process communication,
each process has diff address space ,process are independent & don't require synchronization
& thread (Sub part of process)(lightweight)takes less time in context switching and in inter thread communication
threads share comman add space, threads are dependent on each other. & require synchronisation.
package MyPackage2;
11
using Runnable interface
package MyPackage2.Multithreading;
}
}
-------------------------------------------------------------------------------------------------
package MyPackage2.Multithreading;
class Th extends Thread{
public Th(String name){
super(name);
}
public void run(){
System.out.println("esrdtrfuj");
}
}
public class MyThr {
public static void main(String args[]){
Th th= new Th("Shruti");
th.start();
System.out.println(th.getId());
System.out.println(th.getPriority());
System.out.println(th.getName());
System.out.println(th.getState());
}
}
---------------------------------------------------------------------------------------------------
Thread Priority
package MyPackage2.Multithreading;
class Th extends Thread{
public Th(String name){
super(name);
}
public void run(){
System.out.println("esrdtrfuj");
}
}
public class MyThr {
public static void main(String args[]){
Th th= new Th("Shruti1");
Th th1= new Th("Shruti2");
Th th2= new Th("Shruti3");
Th th3= new Th("Shruti4");
Th th4= new Th("Shruti5");
th4.setPriority(Thread.MAX_PRIORITY);
th.start();
th2.start();
th1.start();
th3.start();
th4.start();
System.out.println(th.getId());
System.out.println(th.getPriority());
System.out.println(th.getName());
System.out.println(th.getState());
System.out.println(th1.getPriority());
System.out.println(th2.getPriority());
System.out.println(th3.getPriority());
System.out.println(th4.getPriority());
}
}
12
Collection Framework
Collection - grp of obj which represented as single unit.Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.framework = set of classes & interface which provide ready made architecture. ex. collection framwork
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Collection hierarchy-
stack - lifo
package MyPackage2.Collection;
import java.util.ArrayList;
import java.util.Iterator;
13
}
}
Stack(lifo)
package MyPackage2.Collection;
import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;
priority queue
package MyPackage2.Collection;
import java.util.PriorityQueue;
import java.util.Queue;
package MyPackage2.Collection;
14
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.ArrayDeque;
Set
package MyPackage2.Collection;
import java.util.HashSet;
import java.util.Set;
15
package MyPackage2.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
16