├── Abstraction.java ├── Classes and objects ├── Constructor.java ├── Creatingobjects1.java ├── Creatingobjects2.java ├── GuessingGame.java ├── Object_Storage.txt ├── OrderOfExecution.java ├── RulesAndPropertiesOfConstructor.txt ├── SwapObjects.java ├── SwapObjects2Problem.java └── SwapObjects2Solution.java ├── Constructors ├── ConstructorOverloading.java ├── CopyConstructor.java ├── DefaultConstructor.java └── PrivateConstructor.java ├── Encapsulation.java ├── Exception Handling ├── ControlFlow1.java ├── ControlFlow2.java └── ExceptionHandling1.java ├── FirstProgramme.java ├── Inheritence ├── HierarchicalInheritance.java ├── MultilevelInheritence.java ├── ObjectCreation.java └── SingleInheritence.java ├── Interface ├── AbstractClass1.java ├── Abstractclass2.java ├── Interface1.java ├── Interface2.java ├── Interface3.java ├── MoreAboutInterface.txt ├── NestedInterface1.java ├── NestedInterface2.java ├── NestedInterface3.java └── NestedInterface4.java ├── Methods ├── AmbiguousVarargsMethodOverloading.java ├── DynamicMethodDispatch1.java ├── EqualsOverriding.java ├── MainOverloading.java ├── MethodOverloading1.java ├── MethodOverloading2.java ├── MethodOverriding1.java ├── MethodOverriding2.java ├── MethodOverriding3.java ├── NullError.java ├── NullErrorSolution.java ├── PassByValue1.java ├── PassingObjects1.java ├── PassingObjects2.java ├── PassingObjects3.java ├── ReturningObjects.java ├── ReturningValues1.java ├── ReturningValues2.java ├── ReturningValues3.java ├── Varargs.java └── VarargsMethodOverloading.java ├── Misc Programmes ├── Bubble_sort.java ├── DivideByZero.java ├── Java Star Pattern ├── NoMatchFoundException.java ├── Palindrome.java ├── PrimeAndFiboThread.java ├── SortStringAlpha.java └── ThreeThread.java ├── Multithreading ├── MultiThreading6.java ├── Multithreading1.java ├── Multithreading2.java ├── Multithreading3.java ├── Multithreading4.java └── Multithreading5.java ├── NestedClass ├── NestedClass1.java ├── NestedClass2.java ├── NestedClass3.java ├── NestedClass4.java └── NestedClass5.java ├── README.md ├── Simple-Banking-System └── banking.java ├── StaticImport.java ├── Super keyword ├── superWithConstructor.java ├── superWithMethods.java └── superWithVariables.java ├── snapshots ├── Exception_Hierarchy.jpg └── Thread_life_cycle.jpg ├── synchronization.java └── this keyword ├── this1.java ├── this2.java ├── this3.java ├── this4.java ├── this5.java └── this6.java /Abstraction.java: -------------------------------------------------------------------------------- 1 | abstract class Car{ 2 | String color; 3 | abstract double speed(); 4 | abstract public String toString(); 5 | public Car(String color) 6 | { 7 | System.out.println("Car constructor called"); 8 | this.color=color; 9 | } 10 | //concrete method 11 | public String getColor() 12 | { 13 | return color; 14 | } 15 | } 16 | class Audi extends Car{ 17 | double speed; 18 | public Audi(String color,double speed) 19 | { 20 | super(color); 21 | System.out.println("Audi constructor called"); 22 | this.speed=speed; 23 | } 24 | double speed() 25 | { 26 | return speed; 27 | } 28 | public String toString() 29 | { 30 | return "Audi Color:"+super.color+" speed:"+speed(); 31 | } 32 | 33 | } 34 | 35 | class Mercedes extends Car { 36 | 37 | double distance; 38 | double time; 39 | 40 | public Mercedes(String color, double distance, double time) { 41 | // calling Shape constructor 42 | super(color); 43 | System.out.println("Mercedes constructor called"); 44 | this.distance = distance; 45 | this.time = time; 46 | } 47 | 48 | @Override 49 | double speed() { 50 | return distance/time; 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | return "Mercedes color is " + super.color + "and speed is : " + speed(); 56 | } 57 | 58 | } 59 | 60 | public class Abstraction { 61 | public static void main(String[] args) { 62 | Car s1 = new Audi("Red", 2.2); 63 | Car s2 = new Mercedes("Yellow", 2, 4); 64 | 65 | System.out.println(s1.toString()); 66 | System.out.println(s2.toString()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Classes and objects/Constructor.java: -------------------------------------------------------------------------------- 1 | class Box { 2 | double width; 3 | double height; 4 | double depth; 5 | 6 | //Constructor declaration 7 | Box(double w, double h, double d) { 8 | width = w; 9 | height = h; 10 | depth = d; 11 | } 12 | 13 | // Method1 14 | double volume() { 15 | return width * height * depth; 16 | } 17 | 18 | } 19 | 20 | class Constructor { 21 | public static void main(String args[]) { 22 | // invoking constructor 23 | Box obj1 = new Box(3,5,10); 24 | // invoking constructor 25 | Box obj2 = new Box(10,15,20); 26 | System.out.println("Vol of Box1:" + obj1.volume()); 27 | System.out.println("Vol of Box2:" + obj2.volume()); 28 | } 29 | } -------------------------------------------------------------------------------- /Classes and objects/Creatingobjects1.java: -------------------------------------------------------------------------------- 1 | class Box{ 2 | double width; 3 | double height; 4 | double depth; 5 | 6 | //Method1 7 | double volume(){ 8 | return width*height*depth; 9 | } 10 | //Method2 11 | void setDim(double w,double h,double d){ 12 | width=w; 13 | height=h; 14 | depth=d; 15 | } 16 | } 17 | class Creatingobjects1{ 18 | public static void main(String args[]){ 19 | //creating object1 of Class Box 20 | Box obj1=new Box(); 21 | //creating object2 of Class Box 22 | Box obj2=new Box(); 23 | obj1.setDim(3,5,10); 24 | obj2.setDim(10,15,20); 25 | System.out.println("Vol of Box1:"+obj1.volume()); 26 | System.out.println("Vol of Box2:"+obj2.volume()); 27 | } 28 | } -------------------------------------------------------------------------------- /Classes and objects/Creatingobjects2.java: -------------------------------------------------------------------------------- 1 | class Box{ 2 | double width; 3 | double height; 4 | double depth; 5 | } 6 | class Creatingobjects2{ 7 | public static void main(String args[]) { 8 | 9 | //Creating object of class Box 10 | Box mybox=new Box(); 11 | mybox.width=5; 12 | mybox.height=10; 13 | mybox.depth=20; 14 | double vol=mybox.width*mybox.height*mybox.depth; 15 | System.out.println("Volume is:"+vol); 16 | } 17 | } -------------------------------------------------------------------------------- /Classes and objects/GuessingGame.java: -------------------------------------------------------------------------------- 1 | class Player{ 2 | int number;//where the guess goes 3 | public void guess(){ 4 | number=(int)(Math.random()*10); 5 | System.out.println(); 6 | } 7 | } 8 | 9 | class Game{ 10 | //class Game has three instance variables for three Player objects 11 | Player p1; 12 | Player p2; 13 | Player p3; 14 | public void startGame() 15 | { 16 | 17 | //Three player objects are created and assign them to the three Player instance variables 18 | p1=new Player(); 19 | p2=new Player(); 20 | p3=new Player(); 21 | 22 | // 23 | int guessp1; 24 | int guessp2; 25 | int guessp3; 26 | 27 | boolean p1isRight=false; 28 | boolean p2isRight=false; 29 | boolean p3isRight=false; 30 | 31 | int target=(int)(Math.random()*10); 32 | System.out.println("I'm thinking of a number between 0 and 9..."); 33 | 34 | while(true) 35 | { 36 | System.out.println("Number to be guessed:"+target); 37 | 38 | //calling each player's guess() method 39 | p1.guess(); 40 | p2.guess(); 41 | p3.guess(); 42 | 43 | //get each player's guess() method result by accessing number variable of each player 44 | guessp1=p1.number; 45 | System.out.println("Player one guessed:"+guessp1); 46 | guessp2=p2.number; 47 | System.out.println("Player two guessed:" + guessp2); 48 | guessp3=p3.number; 49 | System.out.println("Player three guessed:" + guessp3); 50 | 51 | if (guessp1==target) 52 | { 53 | p1isRight=true; 54 | } 55 | if (guessp2 == target) { 56 | p2isRight = true; 57 | } 58 | if (guessp3 == target) { 59 | p3isRight = true; 60 | } 61 | 62 | if(p1isRight||p2isRight||p3isRight) 63 | { 64 | System.out.println("We have a winner!!!:)"); 65 | System.out.println("Player one got it right?" + p1isRight); 66 | System.out.println("Player two got it right?" + p2isRight); 67 | System.out.println("Player three got it right?" + p3isRight); 68 | System.out.println("Game over!"); 69 | break; 70 | } 71 | else{ 72 | System.out.println("Players will have to try again"); 73 | } 74 | } 75 | } 76 | } 77 | 78 | class GuessingGame{ 79 | public static void main(String args[]) 80 | { 81 | Game game=new Game(); 82 | game.startGame(); 83 | } 84 | } -------------------------------------------------------------------------------- /Classes and objects/Object_Storage.txt: -------------------------------------------------------------------------------- 1 | In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static. 2 | 3 | In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on heap. 4 | 5 | for example: 6 | 7 | 8 | class Test { 9 | 10 | // class contents 11 | void show() 12 | { 13 | System.out.println("Test::show() called"); 14 | } 15 | } 16 | 17 | public class Main { 18 | 19 | // Driver Code 20 | public static void main(String[] args) 21 | { 22 | Test t; 23 | 24 | // Error here because t 25 | // is not initialzed 26 | t.show(); 27 | } 28 | } 29 | 30 | Correct Code: 31 | 32 | 33 | class Test { 34 | 35 | // class contents 36 | void show() 37 | { 38 | System.out.println("Test::show() called"); 39 | } 40 | } 41 | 42 | public class Main { 43 | 44 | // Driver Code 45 | public static void main(String[] args) 46 | { 47 | 48 | // all objects are dynamically 49 | // allocated 50 | Test t = new Test(); 51 | t.show(); // No error 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Classes and objects/OrderOfExecution.java: -------------------------------------------------------------------------------- 1 | class Blocks{ 2 | //creating an anonymous blocks 3 | { 4 | System.out.println("Inside Anonymous Block"); 5 | } 6 | //creating a static block 7 | static{ 8 | System.out.println("Inside Static Block"); 9 | } 10 | 11 | //creating constructor of class 12 | Blocks(){ 13 | System.out.println("Inside Constructor"); 14 | } 15 | } 16 | class OrderOfExecution{ 17 | //creating an object of class blocks 18 | public static void main(String args[]){ 19 | Blocks obj=new Blocks(); 20 | System.out.println("**************"); 21 | //creating another object of class Blocks 22 | Blocks obj1=new Blocks(); 23 | } 24 | } -------------------------------------------------------------------------------- /Classes and objects/RulesAndPropertiesOfConstructor.txt: -------------------------------------------------------------------------------- 1 | RULES: 2 | 3 | 4 | 1.A Constructor cannot have a return type. 5 | 6 | 2.A constructor must have the same name as that of the Class. 7 | 8 | 3.Constructors cannot be marked static 9 | 10 | 4.A constructor cannot be marked abstract 11 | 12 | 5.A Constructor cannot be overridden. 13 | 14 | 6.A Constructor cannot be Final. 15 | 16 | PROPERTIES: 17 | 18 | 1.A constructor is invoked when a new object is created. 19 | 20 | 2.Constructors can also be overloaded but it can not be overridden. 21 | 22 | 3.Every class has at least one constructor. If a user doesn’t provide any, JVM will provide a default no-arg constructor. 23 | 24 | 4.Abstract class also has a constructor. 25 | 26 | 5.A constructor must have the same name as the class. 27 | 28 | 6.A constructor can’t have a return type. 29 | 30 | 7.If a method with the same name as a class has return type will be treated as a normal member method and not constructor. 31 | 32 | 8.A constructor can have any access modifier(All). 33 | 34 | 9.A default constructor is a no-arg constructor which calls the no-arg constructor of the superclass. In case superclass doesn’t have any no-arg constructor then it will throw a runtime exception. 35 | 36 | 10.In a case where a class has the default constructor, its superclass needs to have a no-arg constructor. 37 | 38 | 11.The first statement of a constructor can be either this or super but cannot be both at the same time. 39 | 40 | 12.If the coder doesn’t write any this or super call then the compiler will add a call to super. 41 | 42 | 13.Instance member can be accessible only after the super constructor runs. 43 | 44 | 14.Interfaces do not have constructors. 45 | 46 | 15.A constructor is not inherited. Hence cannot be overridden. 47 | 48 | 16.A constructor cannot be directly invoked. It will be invoked(Implicitly) when a new object is created or a call by other constructors. 49 | -------------------------------------------------------------------------------- /Classes and objects/SwapObjects.java: -------------------------------------------------------------------------------- 1 | class Box 2 | { 3 | int box_no; 4 | Box(int no) 5 | { 6 | box_no=no; 7 | } 8 | } 9 | class SwapObjects 10 | { 11 | public static void swap(Box mybox1,Box mybox2) 12 | { 13 | int temp=mybox1.box_no; 14 | mybox1.box_no=mybox2.box_no; 15 | mybox2.box_no=temp; 16 | } 17 | public static void main(String[] args) { 18 | Box box1=new Box(1); 19 | Box box2=new Box(2); 20 | swap(box1,box2); 21 | System.out.println("Box 1 number:"+box1.box_no); 22 | System.out.println("Box 2 number:" + box2.box_no); 23 | 24 | } 25 | } -------------------------------------------------------------------------------- /Classes and objects/SwapObjects2Problem.java: -------------------------------------------------------------------------------- 1 | class Box 2 | { 3 | int length,box_no; 4 | Box(int l,int no) 5 | { 6 | length=l; 7 | box_no=no; 8 | } 9 | void characteristics() 10 | { 11 | System.out.println("Box no.:"+box_no+" ; length of box:"+length); 12 | } 13 | } 14 | 15 | class SwapObjects2Problem 16 | { 17 | public static void swap(Box mybox1,Box mybox2) { 18 | Box temp=mybox1; 19 | mybox1=mybox2; 20 | mybox2=temp; 21 | } 22 | public static void main(String[] args) { 23 | Box box1=new Box(34, 1); 24 | Box box2= new Box(84, 2); 25 | swap(box1,box2); 26 | box1.characteristics(); 27 | box2.characteristics(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Classes and objects/SwapObjects2Solution.java: -------------------------------------------------------------------------------- 1 | //A java Program to demostrate wrapper class to swap objects of a car 2 | class Box 3 | { 4 | int no; 5 | float length; 6 | float depth; 7 | float width; 8 | Box(int n,float l,float d,float w) 9 | { 10 | no=n; 11 | length=l; 12 | depth=d; 13 | width=w; 14 | } 15 | void characteristics() 16 | { 17 | System.out.println("Box Number:"+no+" Length:"+length+" Depth:"+depth+" Width:"+width); 18 | } 19 | } 20 | 21 | //Wrapper class 22 | class BoxWrapper 23 | { 24 | Box myBox; 25 | BoxWrapper(Box obj) 26 | { 27 | myBox=obj; 28 | } 29 | } 30 | 31 | /** 32 | * SwapObjects2Solution 33 | */ 34 | public class SwapObjects2Solution { 35 | 36 | public static void swap(BoxWrapper mybox1,BoxWrapper mybox2) { 37 | Box temp=mybox1.myBox; 38 | mybox1.myBox=mybox2.myBox; 39 | mybox2.myBox=temp; 40 | } 41 | public static void main(String[] args) { 42 | Box box1=new Box(1,30f,45.5f,67.8f); 43 | Box box2=new Box(2,57f,90f,10f); 44 | BoxWrapper boxw1=new BoxWrapper(box1); 45 | BoxWrapper boxw2=new BoxWrapper(box2); 46 | swap(boxw1,boxw2); 47 | boxw1.myBox.characteristics(); 48 | boxw2.myBox.characteristics(); 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /Constructors/ConstructorOverloading.java: -------------------------------------------------------------------------------- 1 | class person 2 | { 3 | int age; 4 | double height; 5 | double weight; 6 | person() 7 | { 8 | System.out.println("No parameterized constructor"); 9 | age=0; 10 | height=0.0; 11 | weight=0.0; 12 | } 13 | person(int age) 14 | { 15 | System.out.println("One Parameter Constructor"); 16 | this.age=age; 17 | height=0.0; 18 | weight=0.0; 19 | } 20 | person(int age,double height) 21 | { 22 | System.out.println("Two parameter Constructor"); 23 | this.age=age; 24 | this.height=height; 25 | weight=0.0; 26 | } 27 | 28 | person(int age, double height,double weight) { 29 | System.out.println("Three parameter Constructor"); 30 | this.age = age; 31 | this.height = height; 32 | this.weight = weight; 33 | } 34 | public String toString(){ 35 | return "Age:"+age+"\tHeight"+height+"\tWeight"+weight; 36 | } 37 | 38 | } 39 | public class ConstructorOverloading { 40 | public static void main(String[] args) { 41 | person p1=new person(); 42 | System.out.println(p1); 43 | person p2=new person(22); 44 | System.out.println(p2); 45 | 46 | person p3=new person(22,5); 47 | System.out.println(p3); 48 | 49 | person p4=new person(22,5,65); 50 | System.out.println(p4); 51 | 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Constructors/CopyConstructor.java: -------------------------------------------------------------------------------- 1 | class Person { 2 | String name; 3 | int age; 4 | 5 | Person(String name, int age) { 6 | System.out.println("This is the original constructor"); 7 | this.name = name; 8 | this.age = age; 9 | } 10 | 11 | Person(Person p) 12 | { 13 | System.out.println("This is a copy of the constructor"); 14 | name=p.name; 15 | age=p.age; 16 | } 17 | 18 | // Overriding the toString of Object class 19 | public String toString() { 20 | return "Name:" + name + "\tAge:" + age; 21 | } 22 | 23 | } 24 | class CopyConstructor { 25 | public static void main(String[] args) { 26 | Person p1=new Person("Disha",22);// original 27 | System.out.println(p1); 28 | Person p2=new Person(p1);//copy 29 | System.out.println(p2); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Constructors/DefaultConstructor.java: -------------------------------------------------------------------------------- 1 | class A 2 | { 3 | int i; 4 | float f; 5 | boolean b; 6 | double d; 7 | long l; 8 | char c; 9 | String s; 10 | short st; 11 | byte bt; 12 | } 13 | class DefaultConstructor { 14 | public static void main(String[] args) { 15 | A obj=new A(); 16 | System.out.println(obj.i); 17 | System.out.println(obj.f); 18 | System.out.println(obj.b); 19 | System.out.println(obj.d); 20 | System.out.println(obj.l); 21 | System.out.println(obj.c); 22 | System.out.println(obj.s); 23 | System.out.println(obj.st); 24 | System.out.println(obj.bt); 25 | 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /Constructors/PrivateConstructor.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class Person { 4 | static Person name = null; 5 | public int age = 12; 6 | 7 | // private constructor can't be accessed outside the class 8 | private Person() { 9 | } 10 | 11 | // Factory method to provide the users with instances 12 | static public Person getInstance() { 13 | // to ensure only one instance is created 14 | if (name == null) 15 | name = new Person(); 16 | 17 | return name; 18 | } 19 | } 20 | 21 | class PrivateConstructor{ 22 | public static void main(String args[]) { 23 | Person a = Person.getInstance(); 24 | Person b = Person.getInstance(); 25 | a.age = a.age + 10; 26 | System.out.println("Value of a.age = " + a.age); 27 | System.out.println("Value of b.age = " + b.age); 28 | // We changed value of a.age, value of b.age also got updated because both ‘a’ 29 | // and ‘b’ refer to same object, i.e., they are objects of a singleton class. 30 | } 31 | } -------------------------------------------------------------------------------- /Encapsulation.java: -------------------------------------------------------------------------------- 1 | class Employee 2 | { 3 | private int empno; 4 | private String name; 5 | private double salary; 6 | 7 | public int getempno() 8 | { 9 | return empno; 10 | } 11 | 12 | public String getname() { 13 | return name; 14 | } 15 | 16 | public double getsalary() { 17 | return salary; 18 | } 19 | public void setempno(int e) 20 | { 21 | empno=e; 22 | } 23 | 24 | public void setname(String n) { 25 | name = n; 26 | } 27 | 28 | public void setsalary(double s) { 29 | salary = s; 30 | } 31 | } 32 | /** 33 | * Encapsulation 34 | */ 35 | class Encapsulation { 36 | 37 | public static void main(String[] args) { 38 | Employee e1=new Employee(); 39 | e1.setempno(1); 40 | e1.setname("Disha"); 41 | e1.setsalary(100000); 42 | System.out.println("Employee No.:"+e1.getempno()+"\tName:"+e1.getname()+"\tSalary:"+e1.getsalary()); 43 | Employee e2 = new Employee(); 44 | e2.setempno(2); 45 | e2.setname("Argha"); 46 | e2.setsalary(100000); 47 | System.out.println("Employee No.:" + e2.getempno() + "\tName:" + e2.getname() + "\tSalary:" + e2.getsalary()); 48 | 49 | } 50 | } -------------------------------------------------------------------------------- /Exception Handling/ControlFlow1.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * ExceptionHandling1 4 | */ 5 | class ControlFlow1 { 6 | public static void main(String[] args) { 7 | int d; 8 | try{ 9 | d=0; 10 | int a=42/d; 11 | System.out.println("Inside Try block"); 12 | } 13 | catch(ArithmeticException e){ 14 | System.out.println(e); 15 | } 16 | System.out.println("After catch"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Exception Handling/ControlFlow2.java: -------------------------------------------------------------------------------- 1 | class ControlFlow2 { 2 | public static void main(String[] args) { 3 | int d; 4 | try { 5 | d = 0; 6 | int a = 42 / d; 7 | System.out.println("Inside Try block"); 8 | } catch (ArithmeticException e) { 9 | System.out.println(e); 10 | } 11 | finally{ 12 | System.out.println("After catch"); 13 | } 14 | System.out.println("Outside Try-catch-finally block"); 15 | } 16 | } -------------------------------------------------------------------------------- /Exception Handling/ExceptionHandling1.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * ExceptionHandling1 4 | */ 5 | class ExceptionHandling1 { 6 | public static void main(String[] args) { 7 | int d,a; 8 | try{ 9 | d=0; 10 | a=42/d; 11 | } 12 | catch(ArithmeticException e){ 13 | System.out.println("By printStackTrace() method"); 14 | e.printStackTrace();//we will get name(e.g. java.lang.ArithmeticException) and 15 | // description(e.g. / by zero) of an exception separated by colon, and stack 16 | // trace (where in the code, that exception has occurred) in the next line. 17 | System.out.println(e); 18 | System.out.println("by toString() mrthod");//we will only get name and description of an exception. Note that this method is overridden in Throwable class. 19 | 20 | System.out.println(e.toString()); 21 | 22 | System.out.println("By getMessage()");// we will only get description of an exception. 23 | System.out.println(e.getMessage()); 24 | 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /FirstProgramme.java: -------------------------------------------------------------------------------- 1 | public class FirstProgramme{ 2 | public static void main(String args[]){ 3 | int a=100; 4 | System.out.println(a); 5 | } 6 | } -------------------------------------------------------------------------------- /Inheritence/HierarchicalInheritance.java: -------------------------------------------------------------------------------- 1 | class A{ 2 | A() 3 | { 4 | System.out.println("A's Constructor"); 5 | } 6 | void methodA() 7 | { 8 | System.out.println("A's Method"); 9 | } 10 | } 11 | 12 | class B extends A{ 13 | B() 14 | { 15 | System.out.println("B's Constructor"); 16 | } 17 | void methodB() 18 | { 19 | System.out.println("B's Method"); 20 | } 21 | } 22 | 23 | class C extends A{ 24 | C() 25 | { 26 | System.out.println("C's Constructor"); 27 | } 28 | void methodC() 29 | { 30 | System.out.println("C's Method"); 31 | } 32 | 33 | } 34 | /** 35 | * HierarchicalInheritance 36 | */ 37 | class HierarchicalInheritance { 38 | public static void main(String[] args) { 39 | B b=new B(); 40 | b.methodA(); 41 | b.methodB(); 42 | C c=new C(); 43 | c.methodA(); 44 | c.methodC(); 45 | } 46 | } -------------------------------------------------------------------------------- /Inheritence/MultilevelInheritence.java: -------------------------------------------------------------------------------- 1 | class A{ 2 | A(){ 3 | System.out.println("A's Constructor"); 4 | } 5 | void methodA() 6 | { 7 | System.out.println("A's Method"); 8 | } 9 | } 10 | 11 | class B extends A{ 12 | B() 13 | { 14 | System.out.println("B's Constructor"); 15 | } 16 | void methodB() 17 | { 18 | System.out.println("B's Method"); 19 | } 20 | 21 | } 22 | 23 | class C extends B{ 24 | C(){ 25 | System.out.println("C's Constructor"); 26 | } 27 | void methodC() 28 | { 29 | System.out.println("C's Method"); 30 | } 31 | 32 | } 33 | 34 | class MultilevelInheritence{ 35 | public static void main(String[] args) { 36 | C c=new C(); 37 | c.methodA(); 38 | c.methodB(); 39 | c.methodC(); 40 | } 41 | } -------------------------------------------------------------------------------- /Inheritence/ObjectCreation.java: -------------------------------------------------------------------------------- 1 | //A Java program to demonstrate that both super class and subclass constructors refer to same object 2 | class Parent 3 | { 4 | Parent() 5 | { 6 | System.out.println("Super class Constructor"); 7 | System.out.println("Super class object hashcode:"+this.hashCode()); 8 | } 9 | } 10 | class Child extends Parent 11 | { 12 | Child(){ 13 | System.out.println("Sub Class Constructor"); 14 | System.out.println("Sub class object Hashcode:"+this.hashCode()); 15 | } 16 | } 17 | class ObjectCreation 18 | { 19 | public static void main(String[] args) { 20 | Child obj = new Child(); 21 | } 22 | } -------------------------------------------------------------------------------- /Inheritence/SingleInheritence.java: -------------------------------------------------------------------------------- 1 | class A 2 | { 3 | int i,j; 4 | A() 5 | { 6 | 7 | } 8 | A(int a,int b) 9 | { 10 | i=a; 11 | j=b; 12 | } 13 | void Showij() 14 | { 15 | System.out.println("i="+i); 16 | System.out.println("j="+j); 17 | } 18 | } 19 | class B extends A{ 20 | int k; 21 | B(int a,int b,int c) 22 | { 23 | i=a; 24 | j=b; 25 | k=c; 26 | } 27 | void Showk() 28 | { 29 | System.out.println("k=" + k); 30 | } 31 | } 32 | 33 | /** 34 | * SingleInheritence 35 | */ 36 | public class SingleInheritence { 37 | public static void main(String[] args) { 38 | //when an object of B class is created, a copy of the all methods and fields of the superclass acquire memory in this object. That is why, by using the object of the subclass we can also access the members of a superclass. 39 | //During inheritance only object of subclass is created, not the superclass 40 | B subobj=new B(5,10,15); 41 | subobj.Showij(); 42 | subobj.Showk(); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /Interface/AbstractClass1.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | 3 | abstract class Parent { 4 | //optional 5 | Parent() 6 | { 7 | System.out.println("Parent Constructor called"); 8 | } 9 | abstract void meth(); 10 | //Abstract class can also have final methods 11 | final void meth2() 12 | { 13 | System.out.println("final method called"); 14 | } 15 | } 16 | 17 | class child extends Parent{ 18 | child() 19 | { 20 | System.out.println("Child class constructor called"); 21 | } 22 | void meth() 23 | { 24 | System.out.println("abstract method"); 25 | } 26 | } 27 | class AbstractClass1 { 28 | public static void main(String[] args) { 29 | child c =new child(); 30 | c.meth(); 31 | c.meth2(); 32 | Parent p=new child(); 33 | p.meth(); 34 | p.meth2(); 35 | 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /Interface/Abstractclass2.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | abstract class Parent 3 | { 4 | void meth() 5 | { 6 | System.out.println("No abstract method"); 7 | } 8 | } 9 | 10 | class Child extends Parent 11 | { 12 | 13 | } 14 | 15 | class Abstractclass2 { 16 | 17 | public static void main(String[] args) { 18 | Child c=new Child(); 19 | c.meth(); 20 | } 21 | } -------------------------------------------------------------------------------- /Interface/Interface1.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | interface Callback { 3 | void call(int person); 4 | 5 | } 6 | 7 | class Client implements Callback { 8 | public void call(int p) { 9 | System.out.println("Call p:" + p); 10 | } 11 | 12 | void nonInterface() { 13 | System.out.println("NonInterface method"); 14 | } 15 | } 16 | 17 | class AnotherClient implements Callback { 18 | public void call(int p) { 19 | System.out.println("p*p=" + (p * p)); 20 | } 21 | } 22 | 23 | public class Interface1 { 24 | 25 | public static void main(String[] args) { 26 | Callback c = new Client(); 27 | c.call(43); 28 | // c.nonInterface(); will generate error as the reference variable is not class 29 | // type. 30 | Client ob = new Client(); 31 | ob.nonInterface(); 32 | AnotherClient obj = new AnotherClient(); 33 | c = obj; 34 | c.call(9); 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /Interface/Interface2.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | 3 | interface Callback1 { 4 | static void call(int person) 5 | { 6 | System.out.println("Call p:" + person); 7 | } 8 | } 9 | 10 | class Interface2 implements Callback1 { 11 | public static void main(String[] args) { 12 | Callback1.call(3); 13 | } 14 | } -------------------------------------------------------------------------------- /Interface/Interface3.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | 3 | interface A{ 4 | void meth1(); 5 | void meth2(); 6 | } 7 | interface B extends A{ 8 | void meth3(); 9 | } 10 | /** 11 | * Interface3 12 | */ 13 | class Ifaceclass implements B { 14 | public void meth1(){ 15 | System.out.println("Implement meth1()"); 16 | 17 | } 18 | public void meth2() 19 | { 20 | System.out.println("Implement meth2()"); 21 | } 22 | public void meth3() { 23 | System.out.println("Implement meth3()"); 24 | } 25 | } 26 | /** 27 | * Interface3 28 | */ 29 | class Interface3 { 30 | public static void main(String[] args) { 31 | Ifaceclass obj=new Ifaceclass(); 32 | obj.meth1(); 33 | obj.meth2(); 34 | obj.meth3(); 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /Interface/MoreAboutInterface.txt: -------------------------------------------------------------------------------- 1 | 2 | We can’t create instance(interface can’t be instantiated) of interface but we can make reference of it that refers to the Object of its implementing class. 3 | 4 | A class can implement more than one interface. 5 | 6 | An interface can extends another interface or interfaces (more than one interface) . 7 | 8 | A class that implements interface must implements all the methods in interface. 9 | 10 | In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized. 11 | 12 | It is used to achieve multiple inheritance. 13 | 14 | It is used to achieve loose coupling. 15 | -------------------------------------------------------------------------------- /Interface/NestedInterface1.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | class MyClass 3 | { 4 | interface NestedInterface { 5 | String student="Disha";//needs to be initia;ized as its final 6 | void display(int rollno); 7 | } 8 | } 9 | class MyIface implements MyClass.NestedInterface 10 | { 11 | public void display(int rno) 12 | { 13 | System.out.println("Rollno:"+rno); 14 | } 15 | } 16 | /** 17 | * NestedInterface1 18 | */ 19 | class NestedInterface1 { 20 | public static void main(String[] args) { 21 | MyClass.NestedInterface obj=new MyIface(); 22 | System.out.println("Name:"+MyClass.NestedInterface.student); 23 | obj.display(75); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /Interface/NestedInterface2.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | 3 | class MyClass { 4 | protected interface NestedInterface { 5 | String student = "Disha";// needs to be initia;ized as its final 6 | 7 | void display(int rollno); 8 | } 9 | } 10 | 11 | class MyIface implements MyClass.NestedInterface { 12 | public void display(int rno) { 13 | System.out.println("Rollno:" + rno); 14 | } 15 | } 16 | 17 | /** 18 | * NestedInterface1 19 | */ 20 | class NestedInterface2 { 21 | public static void main(String[] args) { 22 | MyClass.NestedInterface obj = new MyIface(); 23 | System.out.println("Name:" + MyClass.NestedInterface.student); 24 | obj.display(75); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Interface/NestedInterface3.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | 3 | interface MyClass { 4 | interface NestedInterface { 5 | String student = "Disha";// needs to be initia;ized as its final 6 | 7 | void display(int rollno); 8 | } 9 | } 10 | 11 | class MyIface implements MyClass.NestedInterface { 12 | public void display(int rno) { 13 | System.out.println("Rollno:" + rno); 14 | } 15 | } 16 | 17 | /** 18 | * NestedInterface1 19 | */ 20 | class NestedInterface3 { 21 | public static void main(String[] args) { 22 | MyClass.NestedInterface obj = new MyIface(); 23 | System.out.println("Name:" + MyClass.NestedInterface.student); 24 | obj.display(75); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Interface/NestedInterface4.java: -------------------------------------------------------------------------------- 1 | package Interface; 2 | 3 | interface MyClass { 4 | protected interface NestedInterface { 5 | String student = "Disha";// needs to be initia;ized as its final 6 | 7 | void display(int rollno); 8 | } 9 | } 10 | 11 | class MyIface implements MyClass.NestedInterface { 12 | public void display(int rno) { 13 | System.out.println("Rollno:" + rno); 14 | } 15 | } 16 | 17 | /** 18 | * NestedInterface1 19 | */ 20 | class NestedInterface4 { 21 | public static void main(String[] args) { 22 | MyClass.NestedInterface obj = new MyIface(); 23 | System.out.println("Name:" + MyClass.NestedInterface.student); 24 | obj.display(75); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Methods/AmbiguousVarargsMethodOverloading.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | void varargs(int...a) 4 | { 5 | System.out.println("METHOD:varargs(int...)\tNUMBER OF ARGUMENTS:"+a.length+"\tITEMS:"); 6 | for(int i:a) 7 | { 8 | System.out.println(i+" "); 9 | } 10 | } 11 | 12 | void varargs(boolean...a) { 13 | System.out.println("METHOD:varargs(boolean...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"); 14 | for(boolean i:a) 15 | { 16 | System.out.println(i+" "); 17 | } 18 | } 19 | 20 | void varargs(String... a) { 21 | System.out.println("METHOD:varargs(String...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"); 22 | for (String i:a) 23 | { 24 | System.out.println(i+" "); 25 | } 26 | } 27 | 28 | void varargs(float... a) { 29 | System.out.println("METHOD:varargs(float...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"); 30 | for(float i:a) 31 | { 32 | System.out.println(i+" "); 33 | } 34 | } 35 | 36 | void varargs(String msg,int... a) { 37 | System.out.println("METHOD:varargs(String,int...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"+msg +"\t"); 38 | for(int i:a) 39 | { 40 | System.out.println(i+" "); 41 | } 42 | } 43 | } 44 | class VarargsMethodOverloading { 45 | public static void main(String[] args) { 46 | Test obj=new Test(); 47 | obj.varargs("Hello World",10,30,80,90); 48 | obj.varargs(10.9f,8.0f); 49 | //obj.varargs(true,false); 50 | //obj.varargs("Disha","Argha","World"); 51 | obj.varargs();//ambiguous 52 | obj.varargs("A");//ambiguous.Compiler cannot resolve between varargs(String...) and varargs(String,int...) 53 | } 54 | } -------------------------------------------------------------------------------- /Methods/DynamicMethodDispatch1.java: -------------------------------------------------------------------------------- 1 | class A { 2 | A() { 3 | System.out.println("A's Constructor"); 4 | } 5 | 6 | void method() { 7 | System.out.println("A's Method"); 8 | } 9 | } 10 | 11 | class B extends A { 12 | B() { 13 | System.out.println("B's Constructor"); 14 | } 15 | 16 | void method() { 17 | System.out.println("B's Method"); 18 | } 19 | } 20 | 21 | class C extends A { 22 | C() { 23 | System.out.println("C's Constructor"); 24 | } 25 | 26 | void method() { 27 | System.out.println("C's Method"); 28 | } 29 | 30 | } 31 | 32 | class DynamicMethodDispatch1 { 33 | public static void main(String[] args) { 34 | A a=new A(); 35 | B b=new B(); 36 | C c=new C(); 37 | // obtain a reference of type A 38 | A ref; 39 | 40 | // ref refers to an A object 41 | ref = a; 42 | 43 | // calling A's version of m1() 44 | ref.method(); 45 | 46 | // now ref refers to a B object 47 | ref = b; 48 | 49 | // calling B's version of m1() 50 | ref.method(); 51 | 52 | // now ref refers to a C object 53 | ref = c; 54 | 55 | // calling C's version of m1() 56 | ref.method(); 57 | } 58 | } -------------------------------------------------------------------------------- /Methods/EqualsOverriding.java: -------------------------------------------------------------------------------- 1 | import javax.lang.model.util.ElementScanner6; 2 | 3 | class Person 4 | { 5 | String name; 6 | int age; 7 | Person(String name,int age) 8 | { 9 | this.name=name; 10 | this.age=age; 11 | } 12 | } 13 | 14 | class Person1 { 15 | String name; 16 | int age; 17 | 18 | Person1(String name, int age) { 19 | this.name = name; 20 | this.age = age; 21 | } 22 | public boolean equals(Object o) 23 | { 24 | // If the object is compared with itself then return true 25 | if (o==this) 26 | { 27 | return true; 28 | } 29 | //Check if o is an instance of Person1 or not 30 | if (!(o instanceof Person1)) 31 | { 32 | return false; 33 | } 34 | // typecast o to Person1 so that we can compare data members 35 | Person1 p=(Person1) o; 36 | return name.equals(p.name) == true && Integer.compare(age, p.age) == 0; 37 | 38 | } 39 | } 40 | 41 | class EqualsOverriding 42 | { 43 | public static void main(String[] args) { 44 | 45 | Person p1=new Person("Disha",22); 46 | Person p2 = new Person("Disha",22); 47 | if (p1==p2) 48 | { 49 | System.out.println("Equal"); 50 | } 51 | else 52 | { 53 | System.out.println("Not Equal"); 54 | } 55 | System.out.println("The reason for printing “Not Equal” is simple: when we compare p1 and p2, it is checked whether both p1 and p2 refer to same object or not.p1 and p2 refer to two different objects, hence the value (p1 == p2) is false. If we create another reference say p3 like following, then (p1 == p3) will give true.\nPerson p3 = p1"); 56 | 57 | System.out.println("After Overriding equals() method"); 58 | Person1 p11=new Person1("Disha",22); 59 | Person1 p21 = new Person1("Disha",22); 60 | if(p11.equals(p21)) 61 | { 62 | System.out.println("Equal"); 63 | } 64 | else{ 65 | System.out.println("Not Equal"); 66 | } 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /Methods/MainOverloading.java: -------------------------------------------------------------------------------- 1 | 2 | // A Java program with overloaded main() 3 | import java.io.*; 4 | 5 | class MainOverloading{ 6 | 7 | // Normal main() 8 | public static void main(String[] args) { 9 | System.out.println("Hello world (from main)"); 10 | MainOverloading.main("Disha"); 11 | } 12 | 13 | // Overloaded main methods 14 | public static void main(String arg1) { 15 | System.out.println("Hi, " + arg1); 16 | MainOverloading.main("Dear ppl", "Hello all"); 17 | } 18 | 19 | public static void main(String arg1, String arg2) { 20 | System.out.println("Hi, " + arg1 + ", " + arg2); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Methods/MethodOverloading1.java: -------------------------------------------------------------------------------- 1 | class Overload 2 | { 3 | void test() 4 | { 5 | System.out.println("No parameter"); 6 | 7 | } 8 | void test(int a) 9 | { 10 | System.out.println("a="+a); 11 | } 12 | void test (int a,int b) 13 | { 14 | System.out.println("a="+a); 15 | System.out.println("b=" + b); 16 | 17 | } 18 | double test(double a) 19 | { 20 | return a*a; 21 | } 22 | void test(byte b) 23 | { 24 | System.out.println("byte b="+b); 25 | } 26 | void test(String s) 27 | { 28 | System.out.println("String:"+s); 29 | } 30 | } 31 | class MethodOverloading1 { 32 | public static void main(String[] args) { 33 | byte a =8; 34 | Overload obj=new Overload(); 35 | obj.test(a);//goes to method with byte argument 36 | obj.test(250);//int 37 | System.out.println("Square of double a:"+obj.test(7.5));//double 38 | obj.test("Hello");//String 39 | obj.test('A');// Since char is 40 | // not available, so the datatype 41 | // higher than char in terms of 42 | // range is int. 43 | System.out.println("Square of float a:" + obj.test(5f));// double 44 | 45 | } 46 | } -------------------------------------------------------------------------------- /Methods/MethodOverloading2.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | void id(String name,int id) 4 | { 5 | System.out.println("Name:"+name+"\tId:"+id); 6 | } 7 | void id(int id,String name) 8 | { 9 | System.out.println("Name:" + name + "\tId:" + id); 10 | 11 | } 12 | } 13 | public class MethodOverloading2 { 14 | 15 | public static void main(String[] args) { 16 | Test obj=new Test(); 17 | obj.id("Disha",101); 18 | obj.id(102,"Argha"); 19 | } 20 | } -------------------------------------------------------------------------------- /Methods/MethodOverriding1.java: -------------------------------------------------------------------------------- 1 | class A { 2 | int i, j; 3 | 4 | A() { 5 | 6 | } 7 | 8 | A(int a, int b) { 9 | i = a; 10 | j = b; 11 | } 12 | 13 | void Showij() { 14 | System.out.println("A's i=" + i); 15 | System.out.println("A's j=" + j); 16 | } 17 | } 18 | 19 | class B extends A { 20 | int k; 21 | 22 | B(int a, int b, int c) { 23 | i = a; 24 | j = b; 25 | k = c; 26 | } 27 | 28 | void Showij() { 29 | System.out.println("B's i=" + i); 30 | System.out.println("B's j=" + j); 31 | 32 | } 33 | 34 | void Showk() { 35 | System.out.println("k=" + k); 36 | } 37 | } 38 | 39 | /** 40 | * SingleInheritence 41 | */ 42 | class MethodOverriding1 { 43 | public static void main(String[] args) { 44 | //If a Parent type reference refers 45 | // to a Parent object, then Parent's 46 | // Showij is called 47 | A obj=new A(20,30); 48 | obj.Showij(); 49 | // If a Parent type reference refers 50 | // to a Child object Child's show() 51 | // is called. This is called RUN TIME 52 | // POLYMORPHISM. 53 | 54 | A obj1=new B(12,45,78); 55 | obj1.Showij(); 56 | B subobj=new B(5,10,15); 57 | subobj.Showij(); 58 | subobj.Showk(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Methods/MethodOverriding2.java: -------------------------------------------------------------------------------- 1 | class A { 2 | int i, j; 3 | 4 | A() { 5 | 6 | } 7 | 8 | A(int a, int b) { 9 | i = a; 10 | j = b; 11 | } 12 | 13 | protected void Showij() { 14 | System.out.println("A's i=" + i); 15 | System.out.println("A's j=" + j); 16 | } 17 | } 18 | 19 | class B extends A { 20 | int k; 21 | 22 | B(int a, int b, int c) { 23 | i = a; 24 | j = b; 25 | k = c; 26 | } 27 | 28 | public void Showij() { 29 | System.out.println("B's i=" + i); 30 | System.out.println("B's j=" + j); 31 | 32 | } 33 | 34 | void Showk() { 35 | System.out.println("k=" + k); 36 | } 37 | } 38 | 39 | /** 40 | * SingleInheritence 41 | */ 42 | class MethodOverriding2 { 43 | public static void main(String[] args) { 44 | // If a Parent type reference refers 45 | // to a Parent object, then Parent's 46 | // Showij is called 47 | A obj = new A(20, 30); 48 | obj.Showij(); 49 | // If a Parent type reference refers 50 | // to a Child object Child's show() 51 | // is called. This is called RUN TIME 52 | // POLYMORPHISM. 53 | 54 | A obj1 = new B(12, 45, 78); 55 | obj1.Showij(); 56 | B subobj = new B(5, 10, 15); 57 | subobj.Showij(); 58 | subobj.Showk(); 59 | } 60 | } -------------------------------------------------------------------------------- /Methods/MethodOverriding3.java: -------------------------------------------------------------------------------- 1 | class A { 2 | int i, j; 3 | 4 | A() { 5 | 6 | } 7 | 8 | A(int a, int b) { 9 | i = a; 10 | j = b; 11 | } 12 | 13 | void Showij() { 14 | System.out.println("A's i=" + i); 15 | System.out.println("A's j=" + j); 16 | } 17 | } 18 | 19 | class B extends A { 20 | int k; 21 | 22 | B(int a, int b, int c) { 23 | i = a; 24 | j = b; 25 | k = c; 26 | } 27 | 28 | void Showij() { 29 | super.Showij(); 30 | System.out.println("B's i=" + i); 31 | System.out.println("B's j=" + j); 32 | 33 | } 34 | 35 | void Showk() { 36 | System.out.println("k=" + k); 37 | } 38 | } 39 | 40 | /** 41 | * SingleInheritence 42 | */ 43 | class MethodOverriding3 { 44 | public static void main(String[] args) { 45 | A obj1 = new B(12, 45, 78); 46 | obj1.Showij(); 47 | B subobj = new B(5, 10, 15); 48 | subobj.Showk(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Methods/NullError.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | void nullError(String name) 4 | { 5 | System.out.println("name:"+name); 6 | } 7 | void nullError(Integer i) 8 | { 9 | System.out.println("integer:"+i); 10 | } 11 | } 12 | class NullError { 13 | public static void main(String[] args) { 14 | Test obj=new Test(); 15 | obj.nullError(null); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /Methods/NullErrorSolution.java: -------------------------------------------------------------------------------- 1 | class Test { 2 | void nullError(String name) { 3 | System.out.println("name:" + name); 4 | } 5 | 6 | void nullError(Integer i) { 7 | System.out.println("integer:" + i); 8 | } 9 | } 10 | 11 | class NullErrorSolution { 12 | public static void main(String[] args) { 13 | Test obj = new Test(); 14 | String arg=null; 15 | obj.nullError(arg); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /Methods/PassByValue1.java: -------------------------------------------------------------------------------- 1 | class PassByValue1{ 2 | public static void main(String[] args) { 3 | int i=0; 4 | change(i); 5 | System.out.println("i="+i); 6 | } 7 | public static void change(int i) 8 | { 9 | i=10; 10 | } 11 | } -------------------------------------------------------------------------------- /Methods/PassingObjects1.java: -------------------------------------------------------------------------------- 1 | class A 2 | { 3 | int a; 4 | A(int i) 5 | { 6 | a=i; 7 | } 8 | } 9 | public class PassingObjects1 { 10 | public static void main(String[] args) { 11 | 12 | 13 | A obj=new A(100); 14 | change(obj); 15 | System.out.println("a="+obj.a); 16 | } 17 | static void change(A obj1) 18 | { 19 | obj1=new A(10); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /Methods/PassingObjects2.java: -------------------------------------------------------------------------------- 1 | class A { 2 | int a; 3 | 4 | A(int i) { 5 | a = i; 6 | } 7 | } 8 | 9 | public class PassingObjects2 { 10 | public static void main(String[] args) { 11 | 12 | A obj = new A(100); 13 | change(obj); 14 | System.out.println("a=" + obj.a); 15 | } 16 | 17 | static void change(A obj1) { 18 | obj1.a=10; 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /Methods/PassingObjects3.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | int a,b; 4 | Test(int i,int j) 5 | { 6 | a=i; 7 | b=j; 8 | } 9 | boolean equals(Test obj) 10 | { 11 | if (obj.a==a && obj.b==b) 12 | { 13 | return true; 14 | } 15 | else{ 16 | return false; 17 | } 18 | } 19 | } 20 | public class PassingObjects3 { 21 | public static void main(String[] args) { 22 | Test obj1=new Test(100, 3); 23 | Test obj2= new Test(100, 3); 24 | Test obj3 = new Test(30,40); 25 | System.out.println("obj1==obj2:"+obj1.equals(obj2)); 26 | System.out.println("obj2==obj3:" + obj2.equals(obj3)); 27 | System.out.println("obj3==obj1:" + obj3.equals(obj1)); 28 | 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /Methods/ReturningObjects.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | int x; 4 | Test(int a) 5 | { 6 | x=a; 7 | } 8 | Test MultiplybyTen() 9 | { 10 | Test obj=new Test(x*10); 11 | return obj; 12 | } 13 | } 14 | class ReturningObjects { 15 | public static void main(String[] args) { 16 | Test obj=new Test(100); 17 | Test obj1; 18 | obj1=obj.MultiplybyTen(); 19 | System.out.println("obj.x="+obj.x); 20 | System.out.println("obj1.x=" + obj1.x); 21 | obj1=obj1.MultiplybyTen(); 22 | System.out.println("new obj1.x=" + obj1.x); 23 | 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /Methods/ReturningValues1.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | int[] getarray() 4 | { 5 | int[] arr=new int[3]; 6 | arr[0]=1; 7 | arr[1]=2; 8 | arr[2]=8; 9 | return arr; 10 | } 11 | } 12 | public class ReturningValues1 { 13 | public static void main(String[] args) { 14 | Test obj=new Test(); 15 | int[] array=obj.getarray(); 16 | System.out.println("Item1:"+array[0]); 17 | System.out.println("Item2:" + array[1]); 18 | System.out.println("Item3:" + array[2]); 19 | 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /Methods/ReturningValues2.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | int a; 4 | int b; 5 | int c; 6 | Test(int i,int j,int k) 7 | { 8 | a=i; 9 | b=j; 10 | c=k; 11 | } 12 | } 13 | public class ReturningValues2 { 14 | static Test getValues() 15 | { 16 | return new Test(10,20,50); 17 | } 18 | public static void main(String[] args) { 19 | getValues(); 20 | System.out.println("a="+getValues().a); 21 | System.out.println("b=" + getValues().b); 22 | System.out.println("c="+getValues().c); 23 | } 24 | } -------------------------------------------------------------------------------- /Methods/ReturningValues3.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Test 3 | { 4 | List getValues() 5 | { 6 | String name="Disha"; 7 | int rno=75; 8 | int height=5; 9 | return Arrays.asList(name,rno,height); 10 | } 11 | } 12 | public class ReturningValues3 { 13 | public static void main(String[] args) { 14 | 15 | Test obj=new Test(); 16 | List person= obj.getValues(); 17 | System.out.println("Name:"+person.get(0)); 18 | System.out.println("Roll Number:" + person.get(1)); 19 | System.out.println("Height:" + person.get(2)); 20 | 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Methods/Varargs.java: -------------------------------------------------------------------------------- 1 | class Varargs { 2 | // A method that takes variable number of integer 3 | // arguments. 4 | static void varargs(int... x) { 5 | System.out.println("Number of arguments: " + x.length); 6 | 7 | // using for each loop to display contents of x 8 | for (int i : x) 9 | System.out.print(i + " "); 10 | System.out.println(); 11 | } 12 | 13 | // Driver code 14 | public static void main(String args[]) { 15 | // Calling the varargs method with different number 16 | // of parameters 17 | varargs(100); // one parameter 18 | varargs(1, 2, 3, 4,10,20); // four parameters 19 | varargs(); // no parameter 20 | } 21 | } -------------------------------------------------------------------------------- /Methods/VarargsMethodOverloading.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | void varargs(int...a) 4 | { 5 | System.out.println("METHOD:varargs(int...)\tNUMBER OF ARGUMENTS:"+a.length+"\tITEMS:"); 6 | for(int i:a) 7 | { 8 | System.out.println(i+" "); 9 | } 10 | } 11 | 12 | /*void varargs(boolean...a) { 13 | System.out.println("METHOD:varargs(boolean...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"); 14 | for(boolean i:a) 15 | { 16 | System.out.println(i+" "); 17 | } 18 | } 19 | 20 | void varargs(String... a) { 21 | System.out.println("METHOD:varargs(String...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"); 22 | for (String i:a) 23 | { 24 | System.out.println(i+" "); 25 | } 26 | }*/ 27 | 28 | void varargs(float... a) { 29 | System.out.println("METHOD:varargs(float...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"); 30 | for(float i:a) 31 | { 32 | System.out.println(i+" "); 33 | } 34 | } 35 | 36 | void varargs(String msg,int... a) { 37 | System.out.println("METHOD:varargs(String,int...)\tNUMBER OF ARGUMENTS:" + a.length + "\tITEMS:"+msg +"\t"); 38 | for(int i:a) 39 | { 40 | System.out.println(i+" "); 41 | } 42 | } 43 | } 44 | class VarargsMethodOverloading { 45 | public static void main(String[] args) { 46 | Test obj=new Test(); 47 | obj.varargs("Hello World",10,30,80,90); 48 | obj.varargs(10.9f,8.0f); 49 | //obj.varargs(true,false); 50 | //obj.varargs("Disha","Argha","World"); 51 | obj.varargs();/*int is more specific than double. If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case: 52 | 53 | double > float 54 | float > long 55 | long > int 56 | int > char 57 | int > short 58 | short > byte*/ 59 | 60 | 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /Misc Programmes/Bubble_sort.java: -------------------------------------------------------------------------------- 1 | class Bubble_sort{ 2 | public static void main(String args[]) 3 | { 4 | int n=Integer.parseInt(args[0]); 5 | int i; 6 | int a[]=new int[n]; 7 | for (i=0;ia[j+1]) 16 | { 17 | temp=a[j]; 18 | a[j]=a[j+1]; 19 | a[j+1]=temp; 20 | } 21 | } 22 | } 23 | System.out.println("Numbers in ascending order:"); 24 | for(i=0;i=0;i--) 7 | { 8 | reverse=reverse+word.charAt(i); 9 | } 10 | System.out.println("Reverse of given word is :"+reverse); 11 | if(word.equalsIgnoreCase(reverse)) 12 | { 13 | System.out.println("So the string is Palindrome."); 14 | } 15 | else 16 | { 17 | System.out.println("So the string is not Palindrome."); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Misc Programmes/PrimeAndFiboThread.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | class fibonacci extends Thread{ 3 | int a=0,b=1,n; 4 | fibonacci(int n){ 5 | super("FIBONACCI THREAD"); 6 | System.out.println("Fibonacci Thread in control"); 7 | this.n=n; 8 | start(); 9 | } 10 | public void run() 11 | { 12 | try{ 13 | for(int i=1;i<=n;i++) 14 | { 15 | int temp=a+b; 16 | System.out.println("Fibonacci term:"+temp); 17 | a=b; 18 | b=temp; 19 | Thread.sleep(1000); 20 | } 21 | } 22 | catch(InterruptedException e) 23 | { 24 | System.out.println(Thread.currentThread().getName() + "interrupted"); 25 | } 26 | System.out.println("Exiting"+ Thread.currentThread().getName()); 27 | } 28 | } 29 | 30 | class prime extends Thread { 31 | int n; 32 | 33 | prime(int n) { 34 | super("PRIME THREAD"); 35 | System.out.println("Prime Thread in control"); 36 | this.n = n; 37 | start(); 38 | } 39 | 40 | public void run() { 41 | try { 42 | for (int i = 1; i <=n; i++) { 43 | int flag=0; 44 | for(int j=2;j0) 17 | { 18 | temp=city[i]; 19 | city[i]=city[j]; 20 | city[j]=temp; 21 | } 22 | } 23 | } 24 | System.out.println("Cities in alphabetical order:"); 25 | for(i=0;i10) 17 | { 18 | stop(); 19 | } 20 | System.out.println(click++); 21 | } 22 | } 23 | public void stop() 24 | { 25 | running=false; 26 | } 27 | } 28 | /** 29 | * ThreeThread 30 | */ 31 | public class ThreeThread { 32 | 33 | public static void main(String[] args) { 34 | Thread.currentThread().setPriority(10); 35 | Multithread th1=new Multithread(7); 36 | Multithread th2=new Multithread(5); 37 | Multithread th3=new Multithread(3); 38 | try{ 39 | System.out.println("Sleeping main Thread"); 40 | Thread.sleep(1000); 41 | } 42 | catch(InterruptedException e) 43 | { 44 | System.out.println("Interrupted:"+e); 45 | } 46 | th1.stop(); 47 | th2.stop(); 48 | th3.stop(); 49 | try{ 50 | th1.t.join(); 51 | th2.t.join(); 52 | th3.t.join(); 53 | } 54 | catch(Exception e) 55 | { 56 | System.out.println("Interrupted:"+e); 57 | } 58 | System.out.println("Thread1:"+th1.click); 59 | System.out.println("Thread2:"+th2.click); 60 | System.out.println("Thread3:"+th3.click); 61 | 62 | } 63 | } -------------------------------------------------------------------------------- /Multithreading/MultiThreading6.java: -------------------------------------------------------------------------------- 1 | package Multithreading; 2 | 3 | class NewThread implements Runnable{ 4 | String name; 5 | Thread t; 6 | NewThread(String thdname) 7 | { 8 | name=thdname; 9 | t=new Thread(this,name); 10 | System.out.println("New Thread:"+t); 11 | t.start(); 12 | } 13 | public void run() 14 | { 15 | try{ 16 | for(int i=5;i>0;i--) 17 | { 18 | System.out.println(name+":"+i); 19 | Thread.sleep(500); 20 | } 21 | } 22 | catch(InterruptedException e) 23 | { 24 | System.out.println(name + " Interrupted"); 25 | } 26 | System.out.println(name+" exiting"); 27 | } 28 | } 29 | /** 30 | * MultiThreading6 31 | */ 32 | class MultiThreading6 { 33 | public static void main(String[] args) { 34 | NewThread ob1=new NewThread("Thread One"); 35 | NewThread ob2=new NewThread("Thread Two"); 36 | NewThread ob3=new NewThread("Thread Three"); 37 | System.out.println("Ob1 is Alive:"+ob1.t.isAlive()); 38 | System.out.println("Ob2 is Alive:"+ob2.t.isAlive()); 39 | System.out.println("Ob3 is Alive:"+ob3.t.isAlive()); 40 | try 41 | { 42 | ob1.t.join(); 43 | ob2.t.join(); 44 | ob3.t.join(); 45 | } 46 | catch(InterruptedException e) 47 | { 48 | System.out.println("Main Interrupted"); 49 | System.out.println("Ob1 is Alive:" + ob1.t.isAlive()); 50 | System.out.println("Ob2 is Alive:" + ob2.t.isAlive()); 51 | System.out.println("Ob3 is Alive:" + ob3.t.isAlive()); 52 | } 53 | 54 | } 55 | 56 | 57 | } -------------------------------------------------------------------------------- /Multithreading/Multithreading1.java: -------------------------------------------------------------------------------- 1 | package Multithreading; 2 | 3 | class Multithreading1 { 4 | public static void main(String[] args) { 5 | Thread t=Thread.currentThread(); 6 | System.out.println("Current Thread: "+t); 7 | t.setName("MyThread"); 8 | System.out.println("After Name Change:"+t); 9 | try{ 10 | for(int i=5;i>0;i--) 11 | { 12 | System.out.println(i); 13 | Thread.sleep(1000); 14 | } 15 | } 16 | catch(InterruptedException e){ 17 | System.out.println("Main Interrupted"); 18 | } 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /Multithreading/Multithreading2.java: -------------------------------------------------------------------------------- 1 | package Multithreading; 2 | 3 | /** 4 | * Multithreading2 5 | */ 6 | class DemoThread extends Thread { 7 | DemoThread() 8 | { 9 | super("Demo Thread"); 10 | System.out.println("Child Thread:"+this); 11 | start(); 12 | } 13 | public void run() { 14 | try{ 15 | for(int i=8;i>0;i--) 16 | { 17 | System.out.println("Child:"+i); 18 | Thread.sleep(500); 19 | } 20 | } 21 | catch(InterruptedException e) 22 | { 23 | System.out.println("Child Interrupted"); 24 | } 25 | System.out.println("Child Exiting"); 26 | } 27 | 28 | } 29 | class Multithreading2 { 30 | public static void main(String[] args) { 31 | new DemoThread(); 32 | try{ 33 | for(int i=5;i>0;i--) 34 | { 35 | System.out.println("Main:"+i); 36 | Thread.sleep(1000); 37 | } 38 | } 39 | catch(InterruptedException e) 40 | { 41 | System.out.println("Main Interrupted"); 42 | } 43 | System.out.println("Main Exiting"); 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /Multithreading/Multithreading3.java: -------------------------------------------------------------------------------- 1 | package Multithreading; 2 | 3 | /** 4 | * Multithreading2 5 | */ 6 | class DemoThread implements Runnable { 7 | Thread t; 8 | DemoThread() { 9 | t=new Thread(this,"Demo Thread"); 10 | System.out.println("Child Thread:" + t); 11 | t.start(); 12 | } 13 | 14 | public void run() { 15 | try { 16 | for (int i = 8; i > 0; i--) { 17 | System.out.println("Child:" + i); 18 | Thread.sleep(500); 19 | } 20 | } catch (InterruptedException e) { 21 | System.out.println("Child Interrupted"); 22 | } 23 | System.out.println("Child Exiting"); 24 | } 25 | 26 | } 27 | 28 | class Multithreading3 { 29 | public static void main(String[] args) { 30 | new DemoThread(); 31 | try { 32 | for (int i = 5; i > 0; i--) { 33 | System.out.println("Main:" + i); 34 | Thread.sleep(1000); 35 | } 36 | } catch (InterruptedException e) { 37 | System.out.println("Main Interrupted"); 38 | } 39 | System.out.println("Main Exiting"); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /Multithreading/Multithreading4.java: -------------------------------------------------------------------------------- 1 | package Multithreading; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * Multithreading4 7 | */ 8 | class PrintTask extends Thread { 9 | 10 | 11 | public void run() 12 | { 13 | Random generator=new Random(); 14 | 15 | int sleeptime=generator.nextInt(5000); 16 | 17 | try { 18 | System.out.printf("%s is going to sleep for %d milliseconds\n",Thread.currentThread().getName(),sleeptime); 19 | Thread.sleep(sleeptime); 20 | 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | System.out.println(Thread.currentThread().getName()+" state after .sleep is called:"+Thread.currentThread().getState()); 25 | 26 | System.out.println(Thread.currentThread().getName()+" done sleeping"); 27 | } 28 | } 29 | /** 30 | * Multithreading4 31 | */ 32 | public class Multithreading4 { 33 | 34 | public static void main(String[] args) { 35 | PrintTask t1=new PrintTask(); 36 | System.out.println("State of "+t1.getName()+" after creating it:"+t1.getState()); 37 | 38 | PrintTask t2=new PrintTask(); 39 | System.out.println("State of "+t2.getName()+" after creating it:"+t2.getState()); 40 | 41 | PrintTask t3=new PrintTask(); 42 | System.out.println("State of "+t3.getName()+" after creating it:"+t3.getState()); 43 | 44 | t1.start(); 45 | System.out.println("State of " + t1.getName() + " after .start is called :" + t1.getState()); 46 | try { 47 | System.out.println("Current Thread: " + Thread.currentThread().getName()); 48 | t1.join(); 49 | System.out.println(t1.getName()+" After .join is called "+t1.getState()); 50 | } 51 | 52 | catch (Exception ex) { 53 | System.out.println("Exception has " + "been caught" + ex); 54 | } 55 | t2.start(); 56 | System.out.println("State of " + t2.getName() + " after .start is called :" + t2.getState()); 57 | try { 58 | System.out.println("Current Thread: " + Thread.currentThread().getName()); 59 | t2.join(); 60 | System.out.println(t2.getName() + " After .join is called " + t2.getState()); 61 | } 62 | 63 | catch (Exception ex) { 64 | System.out.println("Exception has " + "been caught" + ex); 65 | } 66 | t3.start(); 67 | System.out.println("State of " + t3.getName() + " after .start is called :" + t3.getState()); 68 | 69 | } 70 | } -------------------------------------------------------------------------------- /Multithreading/Multithreading5.java: -------------------------------------------------------------------------------- 1 | package Multithreading; 2 | class thread implements Runnable { 3 | public void run() { 4 | // moving thread2 to timed waiting state 5 | try { 6 | Thread.sleep(1500); 7 | } catch (InterruptedException e) { 8 | e.printStackTrace(); 9 | } 10 | 11 | System.out.println("State of thread1 while it called join() method on thread2 -" + Multithreading5.thread1.getState()); 12 | try { 13 | Thread.sleep(200); 14 | } catch (InterruptedException e) { 15 | e.printStackTrace(); 16 | } 17 | } 18 | } 19 | 20 | public class Multithreading5 implements Runnable { 21 | public static Thread thread1; 22 | public static Multithreading5 obj; 23 | 24 | public static void main(String[] args) { 25 | obj = new Multithreading5(); 26 | thread1 = new Thread(obj); 27 | 28 | // thread1 created and is currently in the NEW state. 29 | System.out.println("State of thread1 after creating it - " + thread1.getState()); 30 | thread1.start(); 31 | 32 | // thread1 moved to Runnable state 33 | System.out.println("State of thread1 after calling .start() method on it - " + thread1.getState()); 34 | } 35 | 36 | public void run() { 37 | thread myThread = new thread(); 38 | Thread thread2 = new Thread(myThread); 39 | 40 | // thread1 created and is currently in the NEW state. 41 | System.out.println("State of thread2 after creating it - " + thread2.getState()); 42 | thread2.start(); 43 | 44 | // thread2 moved to Runnable state 45 | System.out.println("State of thread2 after calling .start() method on it - " + thread2.getState()); 46 | 47 | // moving thread1 to timed waiting state 48 | try { 49 | // moving thread1 to timed waiting state 50 | Thread.sleep(200); 51 | } catch (InterruptedException e) { 52 | e.printStackTrace(); 53 | } 54 | System.out.println("State of thread2 after calling .sleep() method on it - " + thread2.getState()); 55 | 56 | try { 57 | // waiting for thread2 to die 58 | thread2.join(); 59 | } catch (InterruptedException e) { 60 | e.printStackTrace(); 61 | } 62 | System.out.println("State of thread2 when it has finished it's execution - " + thread2.getState()); 63 | } 64 | 65 | } -------------------------------------------------------------------------------- /NestedClass/NestedClass1.java: -------------------------------------------------------------------------------- 1 | package NestedClass; 2 | 3 | class OuterClass 4 | { 5 | //static 6 | static int x_static; 7 | //nonstatic 8 | int x_nons; 9 | //private static 10 | private static int x; 11 | 12 | private int x_pri; 13 | OuterClass(int a,int b,int c,int d) 14 | { 15 | x_static=a; 16 | x_nons=b; 17 | x=c; 18 | x_pri=d; 19 | } 20 | // static nested class 21 | 22 | static class Inner { 23 | 24 | void display() 25 | { 26 | OuterClass obj=new OuterClass(10, 20, 30,40); 27 | System.out.println("static int"+x_static); 28 | System.out.println("Private static int"+x); 29 | System.out.println("Nonstatic Integer"+obj.x_nons);//cannot be accessed directly 30 | System.out.println("Nonstatic Private integer"+obj.x_pri);// cannot be accessed directly 31 | } 32 | } 33 | } 34 | /** 35 | * NestedClass1 36 | */ 37 | class NestedClass1 { 38 | 39 | public static void main(String[] args) { 40 | OuterClass.Inner obj1=new OuterClass.Inner(); 41 | obj1.display(); 42 | } 43 | } -------------------------------------------------------------------------------- /NestedClass/NestedClass2.java: -------------------------------------------------------------------------------- 1 | package NestedClass; 2 | 3 | class OuterClass { 4 | // static 5 | static int x_static; 6 | // nonstatic 7 | int x_nons; 8 | // private static 9 | private static int x; 10 | 11 | private int x_pri; 12 | 13 | OuterClass(int a, int b, int c, int d) { 14 | x_static = a; 15 | x_nons = b; 16 | x = c; 17 | x_pri = d; 18 | } 19 | // static nested class 20 | 21 | class Inner { 22 | 23 | void display() { 24 | System.out.println("static int" + x_static); 25 | System.out.println("Private static int" + x); 26 | System.out.println("Nonstatic Integer" +x_nons);// cannot be accessed directly 27 | System.out.println("Nonstatic Private integer" +x_pri);// cannot be accessed directly 28 | } 29 | } 30 | } 31 | 32 | /** 33 | * NestedClass1 34 | */ 35 | class NestedClass2 { 36 | 37 | public static void main(String[] args) { 38 | //accessing Inner class 39 | OuterClass obj = new OuterClass(10, 20, 30, 40); 40 | 41 | OuterClass.Inner obj1 = obj.new Inner(); 42 | obj1.display(); 43 | } 44 | } -------------------------------------------------------------------------------- /NestedClass/NestedClass3.java: -------------------------------------------------------------------------------- 1 | package NestedClass; 2 | 3 | class OuterClass { 4 | // static 5 | static int x_static; 6 | // nonstatic 7 | int x_nons; 8 | // private static 9 | private static int x; 10 | 11 | private int x_pri; 12 | 13 | OuterClass(int a, int b, int c, int d) { 14 | x_static = a; 15 | x_nons = b; 16 | x = c; 17 | x_pri = d; 18 | } 19 | void show() 20 | { 21 | class Inner { 22 | 23 | void display() { 24 | System.out.println("static int" + x_static); 25 | System.out.println("Private static int" + x); 26 | System.out.println("Nonstatic Integer" + x_nons);// cannot be accessed directly 27 | System.out.println("Nonstatic Private integer" + x_pri);// cannot be accessed directly 28 | } 29 | } 30 | Inner obj=new Inner(); 31 | obj.display(); 32 | } 33 | } 34 | 35 | /** 36 | * NestedClass3 37 | */ 38 | class NestedClass3 { 39 | 40 | public static void main(String[] args) { 41 | // accessing Inner class 42 | OuterClass obj1 = new OuterClass(10, 20, 30, 40); 43 | obj1.show(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /NestedClass/NestedClass4.java: -------------------------------------------------------------------------------- 1 | package NestedClass; 2 | 3 | class OuterClass { 4 | // static 5 | static int x_static; 6 | // nonstatic 7 | int x_nons; 8 | // private static 9 | private static int x; 10 | 11 | private int x_pri; 12 | 13 | OuterClass(int a, int b, int c, int d) { 14 | x_static = a; 15 | x_nons = b; 16 | x = c; 17 | x_pri = d; 18 | } 19 | void show(){ 20 | if (x_nons>20) { 21 | class Inner { 22 | 23 | void display() { 24 | System.out.println("static int" + x_static); 25 | System.out.println("Private static int" + x); 26 | System.out.println("Nonstatic Integer" + x_nons);// cannot be accessed directly 27 | System.out.println("Nonstatic Private integer" + x_pri);// cannot be accessed directly 28 | } 29 | } 30 | Inner obj = new Inner(); 31 | obj.display(); 32 | } 33 | else{ 34 | System.out.println("No inner class"); 35 | } 36 | } 37 | } 38 | 39 | /** 40 | * NestedClass3 41 | */ 42 | class NestedClass4 { 43 | 44 | public static void main(String[] args) { 45 | // accessing Inner class 46 | OuterClass obj1 = new OuterClass(10, 20, 30, 40); 47 | obj1.show(); 48 | OuterClass obj2 = new OuterClass(10, 50, 30, 40); 49 | obj2.show(); 50 | // Inner inner = new Inner(); 51 | //System.out.println(inner.display());will generate compilation error as inner class can be accessed only inside the block it belongs to 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /NestedClass/NestedClass5.java: -------------------------------------------------------------------------------- 1 | package NestedClass; 2 | interface Age { 3 | int x = 21; 4 | 5 | void getAge(); 6 | } 7 | 8 | class NestedClass5 { 9 | public static void main(String[] args) { 10 | 11 | // Myclass is hidden inner class of Age interface 12 | // whose name is not written but an object to it 13 | // is created. 14 | Age oj1 = new Age() { 15 | @Override 16 | public void getAge() { 17 | // printing age 18 | System.out.print("Age is " + x); 19 | } 20 | }; 21 | oj1.getAge(); 22 | } 23 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Object-Oriented-Programming-in-Java 2 | 3 | References: [Geeksforgeeks](https://www.geeksforgeeks.org/java/) , [javabeginnerstutorial](https://javabeginnerstutorial.com/core-java-tutorial/) 4 | 5 | 6 | **JAVA IS A PLATFORM-INDEPENDENT LANGUAGE** 7 | 8 | The codes written in Java are converted into an intermediate level language called **bytecode**,after compilation which becomes a part of the java platform,independent of the machine on which the code runs.This makes Java highly portable as its bytecodes can be run on any machine by an interpreter called **Java Virtual Machine(JVM)** 9 | 10 | **JAVA IDENTIFIERS** 11 | 12 | An identifier can be a method name,class name,variable name or label. 13 | 14 | **Code1::[FirstProgramme.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/FirstProgramme.java):** 15 | 16 | In this Code,there are 5 identifiers: 17 | 18 | **FirstProgramme:** Class Name 19 | 20 | **main:** Method name 21 | 22 | **String:** predefined class name 23 | 24 | **args:** variable name 25 | 26 | **a:** variable name 27 | 28 | **JAVA RESERVED WORDS** 29 | 30 | There are **53** reserved words in Java of which **50** are **keywords** and **3** are **literals**(**true,false,null**) 31 | 32 | # CLASS: 33 | 34 | A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 35 | 36 | Modifiers : A class can be public or has default access. 37 | 38 | Class name: The name should begin with a initial letter (capitalized by convention). 39 | 40 | Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 41 | 42 | Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 43 | 44 | Body: The class body surrounded by braces, { }. 45 | 46 | # OBJECT: 47 | 48 | An object is an instance of a class.Technically, Class is a template which describes what state and behavior of an instance this class can have. Object implements the state and behavior in the form of variables and methods and requires some memory allocated.An object consists of: 49 | 50 | State : It is represented by attributes of an object. It also reflects the properties of an object. 51 | 52 | Behavior : It is represented by methods of an object. It also reflects the response of an object with other objects. 53 | 54 | Identity : It gives a unique name to an object and enables one object to interact with other objects. 55 | 56 | 57 | **Declaring Objects (Also called instantiating a class):** 58 | 59 | When an object of a class is created, the class is said to be **instantiated**. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. 60 | 61 | **PACKAGE:[Class and objects](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/Classes%20and%20objects):** 62 | 63 | **Code1:[CreatingObjects1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/Creatingobjects1.java):** Shows the creation of object using 'new' keyword.The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. 64 | 65 | **Code2:[Constructor.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/Constructor.java) :** Shows the creation and invoking of a constructor.The new operator also invokes the class constructor. 66 | 67 | **Code3:[CreatingObjects2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/Creatingobjects2.java):** Shows the creation of object and accessing class members without creating a constructor. 68 | 69 | **Code4:[GuessingGame.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/GuessingGame.java):** A simple game implemented using classes and objects. 70 | 71 | **Code5:[OrderOfExecution.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/OrderOfExecution.java):** Shows the order of execution of static anonymous and init(constructor) block.From the output of this code it can be seen that STATIC block will execute only once when class gets loaded.But Anonymous block and Constructor will run every time object of a Class gets created. Init block will get executed first and then constructor. 72 | 73 | **Code6:[SwapObjects.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/SwapObjects.java):** code to swap two objects of the same class with only one class member. 74 | 75 | **Code7:[SwapObjects2problem.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/SwapObjects2Problem.java):** Code shows the problem to swap two objects of a class with more than one class members if we use the same way used in Code6. 76 | 77 | **Code8:[SwapObjects2Solution.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/SwapObjects2Solution.java):** Code shows the solution to Code7 problem using Wrapper class.A wrapper class solution works even if the user class doesn’t have access to members of the class whose objects are to be swapped. 78 | 79 | 80 | # METHODS: 81 | 82 | A method is a collection of statements that perform certain tasks upon calling and return the result to the caller. A method can perform certain tasks without even returning anything. Methods allow us to reuse the code without retyping the code. 83 | 84 | **Method Declaration:** 85 | Method delaration contains six components: 86 | 87 | 1.**Modifier:** Defines access type of the method i.e. from where it can be accessed in your application. In Java, there 4 type of the access specifiers. 88 | 89 | public: accessible in all class in your application. 90 | protected: accessible within the class in which it is defined and in its subclass(es) 91 | private: accessible only within the class in which it is defined. 92 | default (declared/defined without using any modifier) : accessible within same class and package within which its class is defined. 93 | 2.**The return type :** The data type of the value returned by the method or void if does not return a value. 94 | 95 | 3.**Method Name :** the rules for field names apply to method names as well, but the convention is a little different. 96 | 97 | 4.**Parameter list :** Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters,empty parentheses () are used. 98 | 99 | 5.**Exception list :** The exceptions the method can throw can be specified. 100 | 101 | 6.**Method body :** It is enclosed between braces {} and contains the code to be executed to perform the intended operations. 102 | 103 | **Memory allocation for methods calls:** 104 | 105 | Methods calls are implemented through stack. Whenever a method is called a stack frame is created within the stack area and after that the arguments passed to and the local variables and value to be returned by this called method are stored in this stack frame and when execution of the called method is finished, the allocated stack frame would be deleted. There is a stack pointer register that tracks the top of the stack which is adjusted accordingly. 106 | 107 | **Java is strictly pass by value**: 108 | 109 | **PACKAGE:[Methods](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/Methods):** 110 | 111 | **Code1:[PassByValue1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/PassByValue1.java):** We pass an int to the function “change()” and as a result the change in the value of that integer is not reflected in the main method.Java creates a copy of the variable being passed in the method and then do the manipulations. Hence the change is not reflected in the main method. 112 | 113 | In Java, all non-primitives (or objects of any class) are always references. Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other object to reference passed inside method, the object from calling method as well its reference will remain unaffected. 114 | 115 | 116 | **Code2:[PassingObjects1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/PassingObjects1.java):** A program to show that references are also passed by value. 117 | 118 | If we do not change the reference to refer some other object (or memory location), we can make changes to the members and these changes are reflected back. 119 | 120 | **Code3:[PassingObjects2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/PassingObjects2.java):** A program to show that we can change members of a reference if we do not change the reference itself. 121 | 122 | Java doesnot support returning multiple values by a method 123 | 124 | **Code4:[ReturningValues1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/ReturningValues1.java):** Returning multiple values using array. 125 | 126 | **Code5:[ReturningValues2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/ReturningValues2.java):** Returning multiple values by returning object. 127 | 128 | **Code6:[ReturningValues3.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/ReturningValues3.java):** Returning multiple values by using List Object class 129 | 130 | When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does what’s sort of a hybrid between pass-by-value and pass-by-reference. Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it. 131 | 132 | While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.This effectively means that objects act as if they are passed to methods by use of call-by-reference.Changes to the object inside the method do reflect in the object used as an argument. 133 | 134 | 135 | **Code8:[PassingObjects3.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/PassingObjects3.java):** Another Program to illustrate passing object to methods. 136 | 137 | **Code9:[ReturningObjects.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/ReturningObjects.java):** A program to illustrate method returning object. 138 | 139 | ### METHOD OVERLOADING: 140 | 141 | In java,it is possible to define two or more methods within the same class that share the same name as long as their parameter declaration are different either in terms of number of parameters or type of the parameters or both.This process is called Method Overloading. 142 | Priority wise, compiler take these steps when the exact Prototype doesnot match with the arguments: 143 | 144 | 145 | 1.Type Conversion but to higher type(in terms of range) in same family. 146 | 2.Type conversion to next higher family(suppose if there is no long data type available for an int data type, then it will search for the float data type). 147 | 148 | **Code10:[MethodOverloading1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/MethodOverloading1.java):** A program to illustrate how method Overloading works. 149 | 150 | We can overload two or more static methods with same name, but differences in input parameters.We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is same). 151 | 152 | The compiler does not consider the return type while differentiating the overloaded method. But two methods with the same signature and different return type can not be declared. It will throw a compile time error. 153 | 154 | Hence Method overloading can be done by changing: 155 | 156 | 1.The number of parameters in two methods. 157 | 2.The data types of the parameters of methods. 158 | 3.The Order of the parameters of methods. 159 | 160 | **Code11:[MethodOverloading2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/MethodOverloading2.java):** A program to illustrate method overloading by changing the order of parameters in the methods. 161 | 162 | **Code12:[NullError.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/NullError.java):** In this Code the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. 163 | 164 | **Code13:[NullErrorSolution.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/NullErrorSolution.java):** A Solution to the problem which occured in **Code12**. 165 | 166 | **Code14:[MainOverloading.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/MainOverloading.java):** A program to illustrate overloading main method. 167 | 168 | **Code15:[Varargs.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/Varargs.java):** A variable-length argument is specified by three periods(…).This syntax tells the compiler that a method varargs( ) can be called with zero or more arguments. As a result, here x is implicitly declared as an array of type int[]. 169 | 170 | **Code16:[VarargsMethodOverloading.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/VarargsMethodOverloading.java):** A Program to show method Overloading in methods with variable-length argument. 171 | 172 | **Code17:[AmbiguousVarargsMethodOverloading.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/AmbiguousVarargsMethodOverloading.java):** A Program to illustrate ambiguity while overloading method with variable-length arguments. 173 | 174 | There are 3 phases used in overload resolution: First phase performs overload resolution without permitting boxing or unboxing conversion, Second phase performs overload resolution while allowing boxing and unboxing and Third phase allows overloading to be combined with variable arity methods, boxing, and unboxing. If no applicable method is found during these phases, then ambiguity occurs. 175 | 176 | ### METHOD OVERRIDING: 177 | 178 | When a method in a subclass has the same name, same parameters declaration and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. 179 | 180 | **Code18:[MethodOverriding1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/MethodOverriding1.java):** A simple program to demonstrate Method overriding in java. 181 | 182 | **Code19:[MethodOverriding2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/MethodOverriding2.java):** The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error. 183 | 184 | Private methods cannot be overridden as they are bonded during compile time. Therefore we can’t even override private methods in a subclass. 185 | 186 | It is possible to have different return type for a overriding method in child class, but child’s return type must be sub-type of parent class’ return type. This is known as covariant return type. 187 | 188 | **Code20:[MethodOverriding3.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/MethodOverriding3.java):** A program to demonstrate that parent class overriden method can be called in overriding method of sub class using super keyword. 189 | 190 | **Code21:[EqualsOverriding.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/EqualsOverriding.java):** A program which overrides equals() method of Object class of java to find if two different objects of a same class are equal or not. 191 | 192 | ### DYNAMIC METHOD DISPATCH/RUN-TIME POLYMORPHISM: 193 | 194 | Method Overriding is one of the ways in which Java supports Run-time polymorphism.Dynamic Method Dispatch is a process in which a call to a overriden method is resolved during runtime rather than compile time. 195 | 196 | 1.When an overriden method is called by superclass reference,Java determines which version of the method is to be executed depending on the type of object being reffered to at the time of calling.Thus this determination is made during run-time. 197 | 198 | 2.At run-time,it depends on the type of the object being reffered to which determines the version of the overriden method to be executed. 199 | 200 | 3.A superclass reference variable reffering to a subclass object is known as upcasting. 201 | 202 | **Code22:[DynamicMethodDispatch1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Methods/DynamicMethodDispatch1.java):** A Java program to illustrate Dynamic Method Dispatch using hierarchical inheritance. 203 | 204 | In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members. 205 | 206 | The **java.lang.System.exit()** method exits current program by terminating running Java virtual machine. This method takes a status code. 207 | 208 | exit(0) : Generally used to indicate successful termination. 209 | exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination. 210 | 211 | 212 | # CONSTRUCTORS: 213 | 214 | Constructors are used for initializing new objects. Constructors does not return any values but implicitly it returns the object of the class. Fields are variables that provides the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. 215 | 216 | **PACKAGE:[Constructors](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/Constructors)** 217 | 218 | **Constructors cannot be Inherited:** 219 | 220 | When a class extends another class,the child class inherits the variables ,methods and the behaviour of the super class but not the constructors.Constructors have same name as the class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name. 221 | 222 | **Default Constructors:** 223 | 224 | Java creates a default constructor automatically if no default or parameterized constructor is created by user.The default constructor in java initializes the member data variables to default values 225 | 226 | **Code1:[DefaultContructor.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Constructors/DefaultConstructor.java):** A program to illustrate the behaviour of default constructors. 227 | 228 | **Copy Constructor:** 229 | Java supports copy constructor but doesn't create a default copy of constructor if user doesn't create one. 230 | 231 | **Code2:[CopyConstructor.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Constructors/CopyConstructor.java):** A program to illustrate the use of copy constructor 232 | 233 | ### CONSTRUCTOR CHAINING: 234 | 235 | Constructor chaining is the process of calling one constructor from another constructor with respect to current object. 236 | Constructor chaining can be done in two ways: 237 | 238 | 1.**Within same class:** It can be done using this() keyword for constructors in same class.See [this2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/this%20keyword/this2.java) 239 | 240 | 2.**From base class:** by using super() keyword to call constructor from the base class.See [superWithConstructor.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Super%20keyword/superWithConstructor.java) 241 | 242 | This process is used when we want to perform multiple tasks in a single constructor. Rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable. 243 | 244 | **Points to be noted:** 245 | 246 | 1.The this() expression should always be the first line of the constructor. 247 | 2.There should be at-least be one constructor without the this() keyword. 248 | 3.Constructor chaining can be achieved in any order. 249 | 250 | ### PRIVATE CONSTRUCTORS AND SINGLETON CLASS: 251 | 252 | We can provide access specifier to the constructor. If made private, then it can only be accessed inside the class. 253 | We can use private constructors for 1. Internal Constructor Chaining 2. Singleton class design 254 | 255 | A singleton class is a class that can have not more than a single object. 256 | After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So whatever modifications we do to a variable inside the class through any instance, it affects the variable of the single instance created and is visible if we access that variable through any instance of that class. 257 | 258 | **Code3:[PrivateConstructor.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Constructors/PrivateConstructor.java):** A program to illustrate singleton class using Private constructor. 259 | 260 | To design a singleton class: 261 | 262 | 1.Make constructor as private. 263 | 2.Write a static method that has return type object of this singleton class. Here, the concept of Lazy initialization in used to write this static method. 264 | 265 | ## CONSTRUCTORS VS METHODS: 266 | 267 | Constructors in Java can be seen as Methods in a Class. But there is a big difference be tween Constructors and Methods. 268 | 269 | 1.Constructors have only one purpose, to create an Instance of a Class. This instantiation includes memory allocation and member initialization (Optional). 270 | 271 | By contrast, Methods cannot be used to create an Instance of a Class. 272 | 273 | 2.Constructors cannot have Non Access Modifiers while Methods can. 274 | 275 | 3.Constructors cannot have a return type(Including void) while Methods require it. 276 | 277 | 4.The Constructor name must be the same as the Class name while Methods are not restricted. 278 | 279 | 5.As per Java naming convention, Method names should be camelcase while Constructor names should start with capital letter. 280 | 281 | ### CONSTRUCTOR OVERLOADING: 282 | 283 | In java,it is possible to define two or more constructor of the same class that obviously share the same name but their parameter declaration are different either in terms of number of parameters or type of the parameters or both.This process is called Constructor Overloading. 284 | 285 | **Code4:[ConstructorOverloading.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Constructors/ConstructorOverloading.java):** Java program to demostrate constructor overloading. 286 | 287 | See more on contructors: [Rules And Properties of Constructor](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Classes%20and%20objects/RulesAndPropertiesOfConstructor.txt) 288 | 289 | # ENCAPSULATION: 290 | 291 | Encapsulation is the mechanism that binds together code and the data it manipulates.Other way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield. 292 | 293 | 1.Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared. 294 | 2.As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding. 295 | 3.Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. 296 | 297 | **Code 2::[Encapsulation.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Encapsulation.java):** Java Program to illustrate encapsulation. 298 | 299 | #### Advantages of Encapsulation: 300 | 301 | 1.**Data Hiding:** The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is storing values in the variables. He only knows that we are passing the values to a setter method and variables are getting initialized with that value. 302 | 303 | 2.**Increased Flexibility:** We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to omit the setter methods like setName(), setAge() etc. from the above program or if we wish to make the variables as write-only then we have to omit the get methods like getName(), getAge() etc. from the above program. 304 | 305 | 3.**Reusability:** Encapsulation also improves the re-usability and the code becomes easy to change with new requirements. 306 | 307 | 4.**Testing code:** Encapsulated code is easy to test for unit testing. 308 | 309 | # ABSTRACTION: 310 | 311 | Data Abstraction is defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details.The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects. 312 | 313 | Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is. 314 | In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces. 315 | 316 | 317 | An abstract class is a class that is declared with abstract keyword. 318 | An abstract method is a method that is declared without an implementation. 319 | An abstract class may or may not have all abstract methods. Some of them can be concrete methods 320 | A method defined abstract must always be redefined in the subclass,thus making overriding compulsory OR either make subclass itself abstract. 321 | Any class that contains one or more abstract methods must also be declared with abstract keyword. 322 | There can be no object of an abstract class.That is, an abstract class can not be directly instantiated with the new operator. 323 | An abstract class can have parametrized constructors and default constructor is always present in an abstract class. 324 | 325 | Code:**[Abstraction.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Abstraction.java)** :Abstraction implemented using Abstract class and abstract methods. 326 | 327 | # PACKAGES: 328 | 329 | A package is a container within which we can store multiple classes,subpackages and interfaces.A package is a container of a group of related classes where some of the classes are accessible are exposed and others are kept for internal purpose. 330 | 331 | Packages are used for: 332 | 333 | 1.Avoiding namespace collision ie Preventing naming conflicts.Thus there can be two classes of same name in two different packages. 334 | 2.Searching and using classes, interfaces, enumerations and annotations becomes easier 335 | 3.Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only. 336 | 4.Packages can be considered as data encapsulation (or data-hiding). 337 | 338 | **How packages work?** 339 | 340 | If a package name is college.dept.cse, then there are three directories, college, dept and cse such that cse is present in dept and dept is present college. Also, the directory college is accessible through **CLASSPATH** variable, i.e., path of parent directory of college is present in CLASSPATH. The idea is to make sure that classes are easy to locate.We can add more classes to a created package by using package name at the top of the program and saving it in the package directory. We need a new java file to define a public class, otherwise we can add the new class to an existing .java file and recompile it. 341 | 342 | // import the Vector class from util package. 343 | import java.util.vector; 344 | 345 | // import all the classes from util package 346 | import java.util.*; 347 | // All the classes and interfaces of this package 348 | // will be accessible but not subpackages. 349 | import package.*; 350 | 351 | // Only mentioned class of this package will be accessible. 352 | import package.classname; 353 | 354 | // Class name is generally used when two packages have the same 355 | // class name. For example in below code both packages have 356 | // date class so using a fully qualified name to avoid conflict 357 | import java.util.Date; 358 | import my.packag.Date; 359 | 360 | Packages can be of two types: 361 | 362 | **Built-in Packages:** 363 | 364 | These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are: 365 | 1) **java.lang:** Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported. 366 | 367 | 2) **java.io:** Contains classed for supporting input / output operations. 368 | 369 | 3) **java.util:** Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations. 370 | 371 | 4) **java.applet:** Contains classes for creating Applets. 372 | 373 | 5) **java.awt:** Contain classes for implementing the components for graphical user interfaces (like button , menus etc). 374 | 375 | 6) **java.net:** Contain classes for supporting networking operations. 376 | 377 | **Points to be noted:** 378 | 379 | 1.Every class is part of some package. 380 | 2.If no package is specified, the classes in the file goes into a special unnamed package (the same unnamed package for all files). 381 | 3.All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name. 382 | 4.If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name). 383 | 5.We can access public classes in another (named) package using: package-name.class-name 384 | 385 | **User-defined packages:** 386 | 387 | These are the packages that are defined by the user. First we create a directory with the desired package name (name should be same as the name of the package). Then we create the desired class inside the directory with the first statement being the package names. 388 | 389 | Static import is a feature introduced in Java programming language ( versions 5 and above ) that allows members ( fields and methods ) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. 390 | 391 | **Code3::[StaticImport.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/StaticImport.java):** A program to illustrate how Static import works. 392 | 393 | # INTERFACES: 394 | 395 | Interface looks like a class and has variables and methods declaration like that of a class but it doesnot contain any method definition. 396 | 397 | 398 | 1.Interfaces specify what a class must do and not how. It is the blueprint of the class. 399 | 2.An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement. 400 | 3.If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract. 401 | 4.A Java library example is, Comparator Interface. If a class implements this interface, then it can be used to sort a collection. 402 | 403 | **Use of Interface:** 404 | 405 | 1.It is used to achieve total abstraction. 406 | 407 | 2.Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance . 408 | 409 | 3.It is also used to achieve loose coupling. 410 | 411 | 4.It provides boundness to the program. 412 | 413 | 5.Abstract classes may contain non-final variables, whereas variables in interface are final, public and static. 414 | 415 | **PACKAGE:[Interface](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/Interface):** 416 | 417 | **Code1:[Interface1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/Interface1.java):** A simple java program to illustrate use of Interface. 418 | 419 | **Code2:[Interface2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/Interface2.java):** A simple program to show that we can now define static methods in interfaces(JDK 8 onwards) which can be called independently without an object.These methods are not inherited. 420 | 421 | Read more on Interface **[here](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/MoreAboutInterface.txt)** 422 | 423 | Inheritence can be extended or inherited. 424 | 425 | **Code3:[Interface3.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/Interface3.java):** A Java program to show Interface can be extended. 426 | 427 | # Abstract class: 428 | A class with a pure virtual function ie, an abstract method is termed as Abstract class.In java, however the class has to be declared with abstract keyword to make it Abstract. 429 | 430 | **Code4:[AbstractClass1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/AbstractClass1.java):** A program to illustrate use of Abstract class. 431 | 432 | **Code5:[Abstractclass2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/Abstractclass2.java):** A program to show that java allows abstract classes without any abstract method in it. 433 | ### ABSTRACT CLASS VS INTERFACE: 434 | 435 | |**PROPERTIES**|**ABSTRACT CLASS**|**INTERFACE**| 436 | |:------------:|:----------------:|:-----------:| 437 | |**Methods**|Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.|Interface can have only abstract methods.| 438 | |**Variables**|An abstract class can have final,non-final,static,non-static variables.|Variables declared in a Java interface are by default final.Interface can have only static and final variables.| 439 | |**Implementation**|Abstract class can provide the implementation of interface.|Interface can’t provide the implementation of abstract class.| 440 | |**Inheritance vs Abstraction**|Abstract class can be extended using keyword “extends”.|A Java interface can be implemented using keyword “implements” | 441 | |**Multiple implementation**|An abstract class can extend another Java class and implement multiple Java interfaces.|An interface can extend another Java interface only.| 442 | |**Accessibility of Data Members**|A Java abstract class can have class members with access as private, protected, etc.|Members of a Java interface are public by default| 443 | 444 | ### NESTED INTERFACE: 445 | 446 | Interfaces declared as member of a class or another interface are called member interface or nested interface. 447 | 448 | **Code6:[NestedInterface1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/NestedInterface1.java):** Java program to demonstrate working of interface inside a class. 449 | 450 | **Code7:[NestedInterface2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/NestedInterface2.java):** // Java program to demonstrate protected specifier for nested interface. 451 | 452 | **Code8:[NestedInterface3.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/NestedInterface3.java):** Java program to demonstrate working of interface inside another interface. 453 | 454 | **Code9:[NestedInterface4.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Interface/NestedInterface4.java):** Java program to demonstrate an interface cannot have non-public member interface. 455 | 456 | # NESTED CLASSES: 457 | 458 | When a class is defined within another class, such classes are known as nested classes. 459 | 460 | 461 | 1.The scope of a nested class is bounded by the scope of its enclosing class. Thus in above example, class NestedClass does not exist independently of class OuterClass. 462 | 2.A nested class has access to the members, including private members, of the class in which it is nested. However, reverse is not true i.e. the enclosing class does not have access to the members of the nested class. 463 | 3.A nested class is also a member of its enclosing class. 464 | 4.As a member of its enclosing class, a nested class can be declared private, public, protected, or package private(default). 465 | 466 | Nested classes are divided into two categories: 467 | 468 | 1.static nested class : Nested classes that are declared static are called static nested classes.A static nested class cannot refer directly to instance variables or methods defined in its enclosing class.It can use them only through an object reference.They are accessed using the enclosing class name. 469 | 2.inner class : An inner class is a non-static nested class.Inner class has access to all members(static and non-static variables and methods, including private) of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. 470 | Inner class are of two categories: 471 | 472 | 1.Local Inner class: When an inner class is defined inside a block generally the method of the Outer Class or sometimes a for loop or if clause then it becomes local inner class.Local inner classes cannot have any access modifiers associated with them. However, they can be marked as final or abstract. These class have access to the fields of the class enclosing it. Local inner class must be instantiated in the block they are defined in. 473 | 474 | 2.Anonymous Inner class:It is an inner class without a name and for which only a single object is created. 475 | 476 | **PACKAGE:[NestedClass](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/NestedClass):** 477 | 478 | **Code1:[NestedClass1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/NestedClass/NestedClass1.java):** A Java Program to illustrate static nested class. 479 | 480 | **Code2:[NestedClass2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/NestedClass/NestedClass2.java):** A Java Program to illustrate non-static nested class(inner class). 481 | 482 | **Code3:[NestedClass3.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/NestedClass/NestedClass3.java):** A Java Program to illustrate local inner class inside a method. 483 | 484 | **Code4:[NestedClass4.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/NestedClass/NestedClass4.java):** A Java Program to illustrate local inner class inside an if clause. 485 | 486 | **Code5:[NestedClass5.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/NestedClass/NestedClass5.java):** A Java Program to illustrate anonymous inner class. 487 | 488 | 489 | **JAVA ACCESS MODIFIERS:** 490 | 491 | | | **PRIVATE**|**DEFAULT**|**PROTECTED**|**PUBLIC**| 492 | |:---------:|:----------:|:---------:|:-----------:|:--------:| 493 | |**WITHIN SAME CLASS**|YES|YES|YES|YES| 494 | |**FROM ANY CLASS IN SAME PACKAGE**|NO|YES|YES|YES| 495 | |**FROM ANY SUB CLASS IN SAME PACKAGE**|NO|YES|YES|YES| 496 | |**FROM ANY NON-SUB CLASS IN SAME PACKAGE**|NO|YES|YES|YES| 497 | |**FROM ANY SUB-CLASS FROM DIFFERENT PACKAGE**|NO|NO|YES|YES| 498 | |**FROM ANY NON-SUB CLASS FROM DIFFERENT PACKAGE**|NO|NO|NO|YES| 499 | 500 | 501 | # INHERITANCE: 502 | 503 | Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class. 504 | 505 | Super Class: The class whose features are inherited is known as super class(or a base class or a parent class). 506 | 507 | Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. 508 | 509 | Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. 510 | 511 | ### Types Of Inheritence: 512 | 513 | **1.Single Inheritence:** In single inheritance,one subclass inherit the features of one superclass. 514 | 515 | **2.Multilevel Inheritence:** In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. 516 | 517 | **3.Hierarchical Inheritence:** In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class. 518 | 519 | **4.Multiple Inheritence:** In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes.Java does not support multiple inheritance with classes. In java, we can achieve multiple inheritance only through Interfaces. 520 | Multiple inheritance is not supported by Java using classes , handling the complexity that causes due to multiple inheritance is very complex. It creates problem during various operations like casting, constructor chaining etc 521 | 522 | **PACKAGE:[Inheritence](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/Inheritence):** 523 | 524 | **Code1: [ObjectCreation.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Inheritence/ObjectCreation.java):** Code shows that super class and sub class constructors refer to the same objects. 525 | 526 | **Code2: [SingleInheritence.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Inheritence/SingleInheritence.java):** Code to demostrate how Single Inheritence works. 527 | 528 | **Code3: [MultilevelInheritence.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Inheritence/MultilevelInheritence.java):** Code to demonstrate how Multilevel Inheritence works. 529 | 530 | **Code4: [HierarchicalInheritance.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Inheritence/HierarchicalInheritance.java):** Code to demonstrate how Hierarchical Inheritance works. 531 | 532 | # this KEYWORD: 533 | 534 | 'this' works as a reference to the current object, whose method or constructor is being invoked. This keyword can be used to refer to any member of the current object from within an instance method or a constructor. 535 | 536 | **PACKAGE: [this keyword](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/this%20keyword)**: 537 | 538 | **Code1: [this1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/this%20keyword/this1.java):** this used to refer current class instance variables. 539 | 540 | **Code2: [this2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/this%20keyword/this2.java):** used to invoke current class constructor.This code is an example of **Constructor chaining using this()** discussed above. 541 | 542 | **Code3: [this3.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/this%20keyword/this3.java):** used to invoke current class instances. 543 | 544 | **Code4: [this4.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/this%20keyword/this4.java):** used as method parameter. 545 | 546 | **Code5: [this5.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/this%20keyword/this5.java):** used to invoke current class method. 547 | 548 | **Code6: [this6.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/this%20keyword/this6.java):** used as an argument in constructor call. 549 | 550 | # super KEYWORD: 551 | 552 | The super keyword in java is a reference variable that is used to refer parent class objects. 553 | 554 | **PACKAGE:[super KEYWORD](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/Super%20keyword):** 555 | 556 | **Code1:[superWithConstructor.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Super%20keyword/superWithConstructor.java):** 'super' keyword can also be used to access the parent class constructor.'super' can call both parametric as well as non parametric constructors depending upon the situation.This code is also an example of **Constructor chaining with super()** discussed above. 557 | 558 | **Code2:[superWithMethods.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Super%20keyword/superWithMethods.java):** A program to illustrate that whenever a parent and child class have same named methods then to resolve ambiguity we use super keyword. 559 | 560 | **Code3:[superWithVariables.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Super%20keyword/superWithVariables.java):** A Program to illustrate how use of 'super' with data member of parent class can avoid ambiguity if derived class and parent class has same data members. 561 | 562 | # EXCEPTION HANDLING: 563 | 564 | An exception is an unwanted or unexcepted event,which occurs during the execution of a program ie. at run-time that disrupts the normal-flow of the program's execution. 565 | 566 | ### JAVA EXCEPTION HIERARCHY: 567 | 568 | ![](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/snapshots/Exception_Hierarchy.jpg) 569 | 570 | **PACKAGE:[EXCEPTION HANDLING](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/tree/master/Exception%20Handling)** 571 | 572 | **Code1:[ExceptionHandling1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Exception%20Handling/ExceptionHandling1.java):** A java program to show three ways of printing exception msg using printStackTrace(),toString(),getMessage() methods of Throwable class. 573 | 574 | **Code2:[ControlFlow1.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Exception%20Handling/ControlFlow1.java):** If a statement in try block raised an exception, then the rest of the try block doesn’t execute and control passes to the corresponding catch block. After executing the catch block, the control will be transferred to finally block(if present) and then the rest program will be executed. 575 | 576 | **Code3:[ControlFlow2.java](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Exception%20Handling/ControlFlow2.java):** Java program to demonstrate control flow of try-catch-finally clause when exception occur in try block and handled in catch block. 577 | 578 | # MULTITHREADING: 579 | 580 | Most programming languages do not enable programmers to specify concurrent activities.Java makes concurrency available to the programmers through APIs.The programmer specifies that applications contain thread of execution,where each thread designates a portion of a program that may execute concurrently with other threads.This capability of java is called multithreading. 581 | 582 | **Example**:When programs download large files such as an audio file over the internet,users may not want to wait until entire lengthy file downloads before starting the playback.To solve this,we can put multiple threads to work-one thread downloads the clip and another plays it. 583 | 584 | Java's garbage collection is also an example of multithreading. 585 | 586 | ### Thread States :Life Cycle Of A Thread: 587 | 588 | ![](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/snapshots/Thread_life_cycle.jpg) 589 | 590 | A thread lifecycle is divided into five different states, which a thread may go through in its lifetime. Each thread can be in one of the following five states. Let's understand each of these different states in the order in which they are mentioned below -: 591 | 592 | 593 | 1.New State. 594 | 2.Runnable State. 595 | 3.Running State. 596 | 4.Waiting or Blocked or Sleeping State. 597 | 5.Dead State. 598 | 599 | ### New State: 600 | 601 | A thread enters a new state when an object of Thread class is created but the start() method hasn't been called on it yet. In new state, a thread is not considered alive as it's not a thread of execution. Once the start() method is called on the thread, it leaves the new state and enters the next state but once it leaves new state, it's impossible for it to return back to new state in its lifetime. 602 | 603 | ### Runnable State: 604 | 605 | A thread enters a runnable state when the **start()** method has been called on it. It means, that a thread is eligible to run, but it's not yet running, as the thread scheduler hasn't selected it to run. At one point of time, there could be multiple thread in a runnable state, it's always the choice of thread scheduler to decide on which thread to move to the next state from runnable state. A thread in runnable state is considered to be alive. A thread can return to a runnable state after coming back from a sleeping, waiting/blocked or running state. 606 | 607 | ### Running State: 608 | 609 | A thread enters a running state when the thread schedular has selected it to run(out of all the threads in a thread pool). In this state, a thread starts executing the run() method and it is alive and kicking. From the running state, a thread can enter into waiting/blocked state, runnable or the final dead state. 610 | 611 | ### Waiting or Blocked or Sleeping State: 612 | 613 | A thread enters a waiting state in three situations: 614 | 615 | When a thread has called wait() method on itself and it is waiting for the other thread to notify it or wake it up. 616 | When a thread code has called sleep() method on a thread, asking it to sleep for a duration. 617 | When a thread is waiting for an Input/Output resource to be free. 618 | 619 | When a thread finds itself in any of the above mentioned three states, such events pushes the thread into a blocking/waiting or sleeping mode and the thread is no longer eligible to run. In any of these states, the thread is still considered to be alive. When thread gets out of waiting, blocking or sleeping state, it re-enters into runnable state. 620 | 621 | ### Dead State: 622 | 623 | This is the last state in a thread's lifetime. A thread enters the dead state after it has successfully completed executing the run() method. At this situation, it is considered to be not alive and hence if you try to call start() method on a dead thread, it raises IllegalThreadStateException. 624 | 625 | See **[code1](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Multithreading/Multithreading4.java)** and **[code2](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Multithreading/Multithreading5.java)** 626 | 627 | Threads can be created by using two mechanisms : 628 | 1. **Extending the Thread class**:We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.See **[code](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Multithreading/Multithreading2.java)** 629 | 630 | 2. **Implementing the Runnable Interface**:We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.See **[code](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Multithreading/Multithreading3.java)** 631 | 632 | ### Thread Class vs Runnable Interface 633 | 634 | 1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes. 635 | 636 | 2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface. 637 | 638 | ### THREAD PRIORITIES: 639 | 640 | Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.Informally,threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. 641 | 642 | public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for this is 1. 643 | public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly define it. Value for this is 5. 644 | public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10. 645 | 646 | **public final int getPriority()**: java.lang.Thread.getPriority() method returns priority of given thread. 647 | 648 | **public final void setPriority(int newPriority)**: java.lang.Thread.setPriority() method changes the priority of thread to the value newPriority. This method throws IllegalArgumentException if value of parameter newPriority goes beyond minimum(1) and maximum(10) limit. 649 | 650 | **isAlive():** Returns true or false based on whether Thread is alive or not. See **[Code](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/Multithreading/MultiThreading6.java)** 651 | 652 | ### SYNCHRONIZATION: 653 | 654 | Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results. 655 | 656 | So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time. 657 | 658 | Java provides a way of creating threads and synchronizing their task by using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.See [code](https://github.com/disha2sinha/Object-Oriented-Programming-in-Java/blob/master/synchronization.java) 659 | 660 | 661 | 662 | 663 | -------------------------------------------------------------------------------- /Simple-Banking-System/banking.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | // Banking System 3 | // class Account---name,balance,credit 4 | // 2 method----1. Deposit 2. Withdraw 5 | // Constraint... balance<3000 ==> print... 6 | 7 | class Account { 8 | String name; 9 | double balance; 10 | 11 | Account(String n, double m) { 12 | name = n; 13 | balance = m; 14 | } 15 | 16 | void deposit(double sal) { 17 | balance += sal; 18 | } 19 | 20 | void withdraw(double with) { 21 | balance -= with; 22 | if (balance < 3000) { 23 | System.out.println("Minimum balance not maintained!"); 24 | } 25 | } 26 | 27 | void display() { 28 | System.out.println("The account balance is: " + balance); 29 | } 30 | } 31 | 32 | class banking { 33 | public static void main(String[] args) { // args[0]-name, args[1]-balance 34 | String fullName = args[0]; 35 | double bal = Integer.parseInt(args[1]); 36 | Account person1 = new Account(fullName, bal); 37 | boolean i = true; 38 | while (i) { 39 | Scanner myObj = new Scanner(System.in); 40 | System.out.println("1. Deposit\n2. Withdraw\n3. See Balance: "); 41 | int option = myObj.nextInt(); 42 | switch (option) { 43 | case 1: 44 | System.out.println("Enter balance:"); 45 | double blnce1 = myObj.nextDouble(); 46 | person1.deposit(blnce1); 47 | break; 48 | case 2: 49 | System.out.println("Enter balance:"); 50 | double blnce2 = myObj.nextDouble(); 51 | person1.withdraw(blnce2); 52 | break; 53 | case 3: 54 | person1.display(); 55 | break; 56 | default: 57 | i = false; 58 | break; 59 | } 60 | } 61 | 62 | } 63 | } -------------------------------------------------------------------------------- /StaticImport.java: -------------------------------------------------------------------------------- 1 | import static java.lang.System.*; 2 | 3 | /** 4 | * StaticImport 5 | */ 6 | class StaticImport { 7 | public static void main(String[] args) { 8 | // We don't need to use 'System.out' 9 | // as imported using static. 10 | out.println("Static Import"); 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /Super keyword/superWithConstructor.java: -------------------------------------------------------------------------------- 1 | class Box{ 2 | double width,height,depth; 3 | Box(double w, double h,double d) 4 | { 5 | width=w; 6 | height=h; 7 | depth=d; 8 | } 9 | double volume() 10 | { 11 | return width*height*depth; 12 | } 13 | } 14 | class Boxweight extends Box 15 | { 16 | double weight; 17 | Boxweight(double w,double h,double d,double m) 18 | { 19 | super(w,h,d); 20 | weight=m; 21 | } 22 | } 23 | class superWithConstructor { 24 | public static void main(String[] args) { 25 | Boxweight obj=new Boxweight(10, 23, 9, 45); 26 | System.out.println("Box Volume="+obj.volume()); 27 | System.out.println("Box Weight="+obj.weight); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /Super keyword/superWithMethods.java: -------------------------------------------------------------------------------- 1 | class A{ 2 | int i; 3 | void display() 4 | { 5 | System.out.println("Class A i="+i); 6 | } 7 | } 8 | class B extends A{ 9 | int j; 10 | B(int a,int b) 11 | { 12 | super.i=a; 13 | j=b; 14 | } 15 | void display() 16 | { 17 | super.display(); 18 | System.out.println("Class B j="+j); 19 | } 20 | } 21 | 22 | class superWithMethods { 23 | public static void main(String[] args) { 24 | B obj=new B(10,80); 25 | obj.display(); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /Super keyword/superWithVariables.java: -------------------------------------------------------------------------------- 1 | class A{ 2 | int i=10; 3 | } 4 | class B extends A{ 5 | int i; 6 | B(int a) 7 | { 8 | i=a; 9 | } 10 | void display() 11 | { 12 | System.out.println("Class A i="+super.i); 13 | System.out.println("class B i="+i); 14 | } 15 | } 16 | class superWithVariables { 17 | public static void main(String[] args) { 18 | 19 | B obj=new B(20); 20 | obj.display(); 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /snapshots/Exception_Hierarchy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/disha2sinha/Object-Oriented-Programming-in-Java/42cae420ccc1e39037f573d74e13614e58b56601/snapshots/Exception_Hierarchy.jpg -------------------------------------------------------------------------------- /snapshots/Thread_life_cycle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/disha2sinha/Object-Oriented-Programming-in-Java/42cae420ccc1e39037f573d74e13614e58b56601/snapshots/Thread_life_cycle.jpg -------------------------------------------------------------------------------- /synchronization.java: -------------------------------------------------------------------------------- 1 | 2 | // A Java program to demonstrate working of 3 | // synchronized. 4 | import java.io.*; 5 | import java.util.*; 6 | 7 | // A Class used to send a message 8 | class Sender { 9 | public void send(String msg) { 10 | System.out.println("Sending\t" + msg); 11 | try { 12 | Thread.sleep(1000); 13 | } catch (Exception e) { 14 | System.out.println("Thread interrupted."); 15 | } 16 | System.out.println("\n" + msg + "Sent"); 17 | } 18 | } 19 | 20 | // Class for send a message using Threads 21 | class ThreadedSend extends Thread { 22 | private String msg; 23 | Sender sender; 24 | 25 | // Recieves a message object and a string 26 | // message to be sent 27 | ThreadedSend(String m, Sender obj) { 28 | msg = m; 29 | sender = obj; 30 | } 31 | 32 | public void run() { 33 | // Only one thread can send a message 34 | // at a time. 35 | synchronized (sender) { 36 | // synchronizing the snd object 37 | sender.send(msg); 38 | } 39 | } 40 | } 41 | 42 | // Driver class 43 | class synchronization { 44 | public static void main(String args[]) { 45 | Sender snd = new Sender(); 46 | ThreadedSend S1 = new ThreadedSend(" Hi ", snd); 47 | ThreadedSend S2 = new ThreadedSend(" Bye ", snd); 48 | 49 | // Start two threads of ThreadedSend type 50 | S1.start(); 51 | S2.start(); 52 | 53 | // wait for threads to end 54 | try { 55 | S1.join(); 56 | S2.join(); 57 | } catch (Exception e) { 58 | System.out.println("Interrupted"); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /this keyword/this1.java: -------------------------------------------------------------------------------- 1 | 2 | //Java code for using 'this' keyword to refer current class instance variables 3 | class Test { 4 | int a; 5 | int b; 6 | 7 | // Parameterized constructor 8 | Test(int a, int b) { 9 | this.a = a; 10 | this.b = b; 11 | } 12 | 13 | void display() { 14 | // Displaying value of variables a and b 15 | System.out.println("a = " + a + " b = " + b); 16 | } 17 | } 18 | class this1{ 19 | public static void main(String[] args) { 20 | Test object1 = new Test(10, 20); 21 | object1.display(); 22 | Test object2 = new Test(30, 40); 23 | object2.display(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /this keyword/this2.java: -------------------------------------------------------------------------------- 1 | 2 | // Java code for using this() to 3 | // invoke current class constructor 4 | class Test { 5 | int a; 6 | int b; 7 | 8 | // Default constructor 9 | Test() { 10 | this(10, 20); //constructor chaining 11 | System.out.println("Inside default constructor \n"); 12 | } 13 | 14 | // Parameterized constructor 15 | Test(int a, int b) { 16 | this.a = a; 17 | this.b = b; 18 | System.out.println("Inside parameterized constructor"); 19 | } 20 | } 21 | class this2{ 22 | public static void main(String[] args) { 23 | Test object = new Test(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /this keyword/this3.java: -------------------------------------------------------------------------------- 1 | 2 | //Java code for using 'this' keyword 3 | //to return the current class instance 4 | class Test { 5 | int a; 6 | int b; 7 | 8 | // Default constructor 9 | Test() { 10 | a = 10; 11 | b = 20; 12 | } 13 | 14 | // Method that returns current class instance 15 | Test get() { 16 | return this; 17 | } 18 | 19 | // Displaying value of variables a and b 20 | void display() { 21 | System.out.println("a = " + a + " b = " + b); 22 | } 23 | } 24 | class this3{ 25 | public static void main(String[] args) { 26 | Test object = new Test(); 27 | object.get().display(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /this keyword/this4.java: -------------------------------------------------------------------------------- 1 | class Test { 2 | int a; 3 | int b; 4 | 5 | // Default constructor 6 | Test() { 7 | a = 100; 8 | b = 200; 9 | } 10 | 11 | // Method that receives 'this' keyword as parameter 12 | void display(Test obj) { 13 | System.out.println("a = " + a + " b = " + b); 14 | } 15 | 16 | // Method that returns current class instance 17 | void get() { 18 | display(this); 19 | } 20 | } 21 | class this4{ 22 | 23 | public static void main(String[] args) { 24 | Test object = new Test(); 25 | object.get(); 26 | } 27 | } -------------------------------------------------------------------------------- /this keyword/this5.java: -------------------------------------------------------------------------------- 1 | class Test { 2 | 3 | void display() { 4 | // calling fuction show() 5 | this.show(); 6 | 7 | System.out.println("Inside display function"); 8 | } 9 | 10 | void show() { 11 | System.out.println("Inside show funcion"); 12 | } 13 | } 14 | class this5{ 15 | 16 | public static void main(String args[]) { 17 | Test t1 = new Test(); 18 | t1.display(); 19 | } 20 | } -------------------------------------------------------------------------------- /this keyword/this6.java: -------------------------------------------------------------------------------- 1 | 2 | // Java code for using this as an argument in constructor 3 | // call 4 | // Class with object of Class B as its data member 5 | class A { 6 | B obj; 7 | 8 | // Parameterized constructor with object of B 9 | // as a parameter 10 | A(B obj) { 11 | this.obj = obj; 12 | 13 | // calling display method of class B 14 | obj.display(); 15 | } 16 | 17 | } 18 | 19 | class B { 20 | int x = 5; 21 | 22 | // Default Contructor that create a object of A 23 | // with passing this as an argument in the 24 | // constructor 25 | B() { 26 | A obj = new A(this); 27 | } 28 | 29 | // method to show value of x 30 | void display() { 31 | System.out.println("Value of x in Class B : " + x); 32 | } 33 | } 34 | class this6{ 35 | 36 | public static void main(String[] args) { 37 | B obj = new B(); 38 | } 39 | } 40 | --------------------------------------------------------------------------------