0% found this document useful (0 votes)
23 views16 pages

Core Java

Uploaded by

Shruti Garg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views16 pages

Core Java

Uploaded by

Shruti Garg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

OOPs (Object-Oriented Programming System)

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);
}
}

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.
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

Compile-time Polymorphism Runtime Polymorphism

Compile-Time Polymorphism (overloading)

This type of polymorphism is achieved by function overloading or operator overloading.

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

public class Main {


public static void main (String args []){
Student student=new Student();
student.read( "Maths Book");
}
}

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);
}
}

//output---- reading Maths Book

Runtime Polymorphism (overriding)

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

public class Main {


public static void main (String args []){
Person person=new Emp();// can change during runtime can be Emp or can be showDetail
person.showDetail( );
}
}

package MyPackage2;// overriding during runtime

public class Person {


public void showDetail(){
System.out.println("Basic Details");
}
}
class Emp extends Person {
public void showDetail() {
System.out.println("details of employee");
}
}

//details of employee or Basic details

Encapsulation(DATA+METHODS)(Data Hiding/ info hiding)

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.

1. Declare the variables of class as private

2. Provide public setter and getter methods to modify & view the variable values.
package MyPackage2;

public class Employee {


private int emp_id;
public void setEmp_id(int eid){
emp_id=eid;
}

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

Inheritance in Java (is- a relationship)(codereusability)(can achieve polymorphism method overriding)

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)

Constructor and private classes are not inherited.

Inheritance Types

⦁ Single Inheritance - subclasses inherit the features of one superclass


package MyPackage2;
public class Animal {
void eat(){
System.out.println("hey ");
}
}
class Dog extends Animal{
public static void main(String args[]){
Dog dog= new Dog();
dog.eat();
}

⦁ 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 (){

System.out.println("b class method");


}
}
class C extends B{
static void showC(){
System.out.println("C class method");
}
}

public static void main(String[] args) {


A a = new A();
a.showA();
System.out.println("----------------");
B b = new B();
b.showA();
b.showB();
System.out.println("----------------");
C c = new C();
c.showA();
c.showB();
C.showC();

3
System.out.println("----------------");
}

⦁ Hierarchical Inheritance - one class serves as a superclass (base class) for more than one sub class.
package MyPackage2;

public class A { //multilevel inheritance


public void showA() {

System.out.println("a class method ");


}

public static void main(String[] args) {


A a = new A();
a.showA();
System.out.println("----------------");
B b = new B();
b.showA();
b.showB();
System.out.println("----------------");
C c = new C();
c.showA();
C.showC();
System.out.println("----------------");
}
}
class B extends A{
void showB (){

System.out.println("b class method");


}
}
class C extends A{
static void showC(){
System.out.println("C class method");
}
}

⦁ 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)

package MyPackage2; //multiple inheritance using interface


public interface I1 {
abstract void show();
}
interface I2{
void display();
}
class Test implements I1,I2 {
@Override
public void show() {
System.out.println("hi");
}
@Override
public void display() {
System.out.println("hello");
}
public static void main(String args[]) {
Test test = new Test();
test.show();
test.display();
}
}

⦁ 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

Encapsulation is data hiding(information hiding) Abstraction is detailed hiding(implementation hiding).

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.

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.

o It can be used to achieve loose coupling.

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());
}

}
}

exception obj= exception(class name) description(message)stacktrace(location of exception)

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.

the possibilties that disturbs the execution of finally block

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.

Java Custom Exception using throw keyword(unchecked category)


package MyPackage2.ExceptionHandling;

import java.util.Scanner;

public class Throw extends RuntimeException {


Throw(String msg){
super(msg);
}

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;

public class Example {


public static void main(String[] args) throws ArithmeticException {
System.out.println(method());
}

public static int method() throws ArithmeticException {


int sum = 5/0;
return sum;
}
}
OR

package MyPackage2.ExceptionHandling;
import java.io.IOException;

public class Example {


public static void main(String[] args) throws IOException {
method();
}

public static void method() throws IOException {


throw new IOException("exception occurs");
}
}

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;

public class CustomCheckedException extends Exception{


CustomCheckedException(){
super ("underage");}
CustomCheckedException(String msg){
super(msg);
}
}
class Voting {
public static void main(String[]args) throws CustomCheckedException {
int age = 15;
if (age <18){
throw new CustomCheckedException();
}}}

Custom Checked Exception using try catch


package MyPackage2.ExceptionHandling;

public class CustomCheckedExceptionTry extends Exception{


CustomCheckedExceptionTry(){
super ("underage");}
CustomCheckedExceptionTry(String msg){
super(msg);
}
}
class Vote {
public static void main(String[] args) {
try {
int age = 15;
if (age < 18) {
throw new CustomCheckedExceptionTry("not eligible");
} else {
System.out.println("eligible");
}

} catch (CustomCheckedExceptionTry e) {
e.printStackTrace();
}
}
}

Customized unchecked Exception


package MyPackage2.ExceptionHandling;
public class CustomizedUnchcekedException extends RuntimeException{
CustomizedUnchcekedException(){
super ("underage");}
CustomizedUnchcekedException(String msg){
super(msg);
}
}
class Vot {
public static void main(String[] args) {
try{
int age = 15;
if (age < 18) {
throw new CustomizedUnchcekedException("not eligible");
} else {
System.out.println("eligible");
}}
catch (CustomizedUnchcekedException 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)

Packages can be considered as data encapsulation (or data-hiding).

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)

Multi threading executing multiple threads (sub processes)at single time

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.

thread life cycle

2 ways to create thread

thread (class) Runnable(interface)(better way)

extend thread class only one method run()it implements runnable

package MyPackage2;

class Mythread1 extends Thread{


public void run(){
System.out.println("hihdihed");
}
}
class Mythread2 extends Thread{
public void run(){
System.out.println("dnjendk");
}
}
public class Multithreading1{
public static void main(String args[]){
Mythread1 mythread1 = new Mythread1();
Mythread2 mythread2 = new Mythread2();
mythread2.start();
mythread1.start();
}
}

11
using Runnable interface

package MyPackage2.Multithreading;

class Runnable1 implements Runnable {


@Override
public void run() {
System.out.println("dtcfyvgbhkj");
}
}

public class MultiRunnable{


public static void main(String args[]){
Runnable1 runnable1 = new Runnable1();
Thread t = new Thread(runnable1);
t.start();

}
}
-------------------------------------------------------------------------------------------------

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-

Queue = fifo (priority)

stack - lifo
package MyPackage2.Collection;

import java.util.ArrayList;
import java.util.Iterator;

public class Arraylist {


public static void main (String args[]){
ArrayList<String> studentName = new ArrayList<>();
System.out.println(studentName);
studentName.add("rakesh");
studentName.add("honey");
studentName.add("A");
studentName.add("B");
studentName.add("C");
studentName.add("D");
studentName.add("E");
studentName.add("F");
studentName.add("G");
studentName.add(1,"ramesh");
studentName.remove(1);
studentName.set(1,"GH");
System.out.println(studentName.contains(60));
System.out.println(studentName);
System.out.println(studentName.get(1));
for (int i = 0;i<studentName.size();i++){ // array iterate
System.out.println("element is "+ studentName.get(i));
}
for (String element: studentName){
System.out.println(" using for each element is "+ element );// array iterate
}
Iterator<String> it = studentName.iterator();// array iterate
while (it.hasNext()){
System.out.println("iterator "+ it.next());
}

13
}
}

Stack(lifo)
package MyPackage2.Collection;

import java.util.Stack;

public class LearnStack {


public static void main (String args[]){
Stack<String> animal = new Stack<>();
animal.push("lion");
animal.push("cat");
animal.push("dog");
animal.push("Goat");
animal.push("Horse");
animal.push("rabbit");
animal.push("peacock");
System.out.println(animal);
System.out.println(animal.peek()); // sabse top vala element i.e peacock
animal.pop(); // sabse top vala element i.e peacock
System.out.println(animal);
System.out.println(animal.peek());
}
}
Queue = fifo (priority) we can implement queue using linked list as well as arraylist.

queue using linked list


package MyPackage2.Collection;

import java.util.LinkedList;
import java.util.Queue;

public class LearnQueue {


public static void main (String[]args){

Queue<Integer>queue= new LinkedList<>();


queue.offer(12);
queue.offer(2);
queue.offer(13);
queue.offer(124);
queue.offer(128);
System.out.println(queue);
queue.poll();
System.out.println(queue);
queue.peek();
System.out.println(queue.peek());
}
}

priority queue

package MyPackage2.Collection;

import java.util.PriorityQueue;
import java.util.Queue;

public class LearnPriorityQueue {


public static void main(String args[]){
Queue<Integer>pq = new PriorityQueue<>();
pq.offer(40);
pq.offer(30);
pq.offer(2);
pq.offer(5);
System.out.println(pq);
pq.poll();
System.out.println(pq);
System.out.println(pq.peek());
}
}

if we want to reverse the priority

package MyPackage2.Collection;

14
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class LearnPriorityQueue {


public static void main(String args[]){
Queue<Integer>pq = new PriorityQueue<>(Comparator.reverseOrder());
pq.offer(40);
pq.offer(30);
pq.offer(2);
pq.offer(5);
System.out.println(pq);
pq.poll();
System.out.println(pq);
System.out.println(pq.peek());
}
}
arraydeque
package MyPackage2.Collection;

import java.util.ArrayDeque;

public class LearnArraydeque {


public static void main(String args[]){
ArrayDeque<Integer> adq= new ArrayDeque<>();
adq.offer(1);
adq.offer(89);
adq.offerFirst(45);
adq.offerLast(87);
System.out.println(adq);
System.out.println(adq.peek());
System.out.println(adq.peekFirst());
System.out.println(adq.peekLast());
System.out.println(adq.poll());
System.out.println(adq);
System.out.println(adq.pollFirst());
System.out.println(adq);
System.out.println(adq.pollLast());
System.out.println(adq);
}
}

Set
package MyPackage2.Collection;

import java.util.HashSet;
import java.util.Set;

public class LearnSet {


public static void main (String args[]){
Set<Integer> set = new HashSet<>(); // random order

// Set<Integer> set = new LinkedHashSet<>(); if we want same order

// Set<Integer> set = new TreeSet<>(); if we want in sorted order


set.add(76);
set.add(98);
set.add(7);
set.add(6);
set.add(676);
set.add(6);
set.add(736);
System.out.println(set);
set.remove(6);
System.out.println(set);
System.out.println(set.contains(7));
System.out.println(set.isEmpty());
System.out.println(set.size());
set.clear();
System.out.println(set);
}
}

HashMap (key, value) pair

15
package MyPackage2.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class LearnMap {


public static void main(String args[]){
// Map<Integer , String> name = new HashMap<>();
Map<Integer , String> name = new TreeMap<>(); // if we want in sorted order
name.put(1, "Ram");
name.put(7, "am");
name.put(3, "Ream");
name.put(8, "Rarm");
name.put(5, "Ramr");
name.putIfAbsent(2, "shyam");
System.out.println(name);
System.out.println(name.containsKey(3));
System.out.println(name.containsValue("hj"));
System.out.println(name.isEmpty());
for (Map.Entry<Integer , String>e:name.entrySet())
System.out.println(e);
}
}

16

You might also like