30 July 2023

Collection Framework In Java - learngreen.net

 The Java Collections Framework is an effective and vital phase of Java programming. It offers a standardized and efficient way to store, manipulate, and system collections of objects. At its core, the Collections Framework consists of a set of interfaces, implementations, and algorithms that allow developers to work with different sorts of collections. The framework consists of interfaces such as List, Set, Queue, and Map, each serving one-of-a-kind purposes. For example, the List interface allows ordered collections, Set ensures the area of expertise of elements, Queue represents a queue-like statistics structure, and Map provides key-value pair mappings. Implementations of these interfaces, such as ArrayList, HashSet, LinkedList, and HashMap, offer extraordinary behaviors and overall performance characteristics. Additionally, the Collections Framework provides algorithms for frequent operations like sorting, searching, and filtering factors within collections. These algorithms can be applied to any collection that implements the terrific interface, making sure of code reusability and efficiency. By leveraging the Java Collections Framework, developers can build robust and environment-friendly applications, manage facts effectively, and leverage a wealth of performance provided through the framework.

   The Collection Framework in Java provides a unified and efficient way to deal with collections of objects. It consists of interfaces, implementations, and algorithms that allow developers to work with different types of collections.

Collection Framework In Java





 package Collections;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;

 public class ListExample {
 public static void main(String[] args) {
	 
 //ArrayList & LinkedList
 /* ArrayList can grow or shrink dynamically
 * as elements are added or removed.ArrayList
 * provides many other useful methods,
 * such as clear() to remove all elements, 
 * contains() to check if an element
 * exists, indexOf() to find the 
 * index of an element.You can refer to the
 * Java documentation for a complete list of 
 * methods available in 
 * the ArrayList class.
 */
	 
 ArrayList list= new ArrayList<>();
 list.add(85);
 list.add(842);
 list.remove(1);
 System.out.println(list);
 
 /* Instead, each element in a LinkedList
  * is represented by a node that contains
  * the element value and references to the
  * previous and next nodes.LinkedList
  * provides several other methods, such as
  * addFirst() and addLast() to insert elements
  * at the beginning or end of the list,
  * removeFirst() and removeLast() to remove 
  * the first or last element, indexOf() to find
  * the index of an element, and more.
  * You can refer to the Java documentation
  * for a complete list of methods available in 
  * the LinkedList class.
 */
		
 List linkedList = new LinkedList<>();
 linkedList.add("Dog");
 linkedList.add("Cat");
 linkedList.add("Elephant");
 System.out.println("LinkedList: " + linkedList);
 
 //Output-> [85]
 //         LinkedList: [Dog, Cat, Elephant]

	}
  }
 

 




 package Collections;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.TreeMap;
 public class MapExample {
 public static void main(String[] args) {
	 
 /*
 * HashMap is a class in Java that implements
 * the Map interface.It represents a collection
 * of key-value pairs, where each key is unique.
 * It provides fast performance for basic
 * operations like insertion, retrieval, and 
 * removal of elements. HashMap uses hashing
 * techniques to store and retrieve elements
 * based on their keys.HashMap provides various
 * other useful methods, such as containsKey()
 * and containsValue() to check for key or value
 * existence, isEmpty() to check if the map is
 * empty,and keySet() to obtain a set of all keys.
 * You can refer to the Java documentation for
 * a complete list of methods available in the
 * HashMap class.The term "key" refers to the
 * unique identifier associated with a value 
 * in the map.The key is used as the identifier
 * to access and manipulate the associated value.
 */

 Map hashMap = new HashMap<>();
 hashMap.put("Apple", 10);
 hashMap.put("Banana", 5);
 hashMap.put("Cherry", 15);
 System.out.println("HashMap: " + hashMap);
 
 /* TreeMap is a class in Java that implements
  * the NavigableMap interface and represents
  * a sorted map. Similar to TreeSet, it uses
  * a self-balancing binary search tree,
  * specifically a red-black tree, to store
  * key-value pairs in sorted order based on
  * the keys. This allows for efficient
  * key-based operations with a logarithmic
  * time complexity.TreeMap provides various
  * other methods, such as firstKey()and
  * lastKey() to retrieve the first and last
  * keys, higherKey()and lowerKey() to get the
  * next higher or lower key, and more.
 */


 Map treeMap = new TreeMap<>();
 treeMap.put("John", 25);
 treeMap.put("Alice", 30);
 treeMap.put("Bob", 20);
 System.out.println("TreeMap: " + treeMap);
 //Output-> HashMap: {Apple=10, Cherry=15, Banana=5}
 //         TreeMap: {Alice=30, Bob=20, John=25}
	}
 }
 

 



 package Collections;
 import java.util.LinkedList;
 import java.util.PriorityQueue;
 import java.util.Queue;
 public class QueueExample {
 public static void main(String[] args) {
	 
 /* LinkedList is a class in Java that
  * implements the Queue interface,
  * making it a suitable choice for
  * implementing a queue data structure.
  * In this example, we create a Queue
  * using LinkedList by utilizing the
  * Queue interface. We add elements to
  * the queue using the add() method.
  * It also contains the method poll()
  * to remove elements, peek() method to
  * access the element at front of queue
  * and isEmpty() method to check if the
  * queue is empty.Note that LinkedList
  * can be used as both a Queue and a List,
  * providing flexibility in implementing
  * different data structures.
 */

 
 Queue linkedListQueue = new LinkedList<>();
 linkedListQueue.add("Apple");
 linkedListQueue.add("Banana");
 linkedListQueue.add("Cherry");
 System.out.println("LinkedList Queue: "+linkedListQueue);
       
 /* Elements in a PriorityQueue are
  * ordered based on their natural
  * ordering or a custom comparator
  * that is provided during initialization.
  * The elementwith the highest priority
  * is always at the front of the queue
  * and is the first to be removed when using
  * methods like poll() or remove().
  * PriorityQueue provides various other
  * methods, such as size() to obtain the
  * number of elements in the queue,
  * contains() to check if an element is
  * present,and more. You can refer to the
  * Java documentation for a complete list
  * of methods available in the
  * PriorityQueue class.
 */


  Queue priorityQueue = new PriorityQueue<>();
  priorityQueue.add(10);
  priorityQueue.add(20);
  priorityQueue.add(5);
  System.out.println("Priority Queue: " + priorityQueue);
  // Output-> LinkedList Queue: [Apple, Banana, Cherry]
  // Priority Queue: [5, 20, 10]
	}
  }
 

 





 package Collections;
 import java.util.HashSet;
 import java.util.Set;
 import java.util.TreeSet;
 public class SetExample {
 public static void main(String[] args) {
	 
 /* HashSet represents an unordered collection
  * of unique elements.It uses a hash table data
  * structure to store elements and provides
  * constant-time performance for basic operations
  * like adding, removing, and checking for
  * element existence.HashSet provides various
  * other useful methods, such as clear()
  * to remove all elements, isEmpty() to
  * check if the set is empty,and addAll()
  * to add all elements from another collection.
  * You can refer to the Java documentation for
  * a complete list of methods available in
  * the HashSet class.
  */
	 
 Set hashSet = new HashSet<>();
 hashSet.add(10);
 hashSet.add(20);
 hashSet.add(30);
 System.out.println("HashSet: " + hashSet);
     
 /* TreeSet is a class in Java that implements
  * the NavigableSet interface and represents
  * a sorted set of elements. It uses
  * a self-balancing binary search tree,
  * specifically a red-black tree,to store
  * elements in sorted order. This allows for
  * efficient element retrieval and provides
  * logarithmictime complexity for basic
  * operations like adding, removing, and
  * searching for elements. TreeSet provides
  * various other methods, such as first()
  * and last()to retrieve the first and last
  * elements, higher()and lower() to get the
  * next higher or lower element,and more.
  * You can refer to the Java documentation for
  * a complete list of methods available in the
  * TreeSet class.
 */

 
 Set treeSet = new TreeSet<>();
 treeSet.add("John");
 treeSet.add("Alice");
 treeSet.add("Bob");
 System.out.println("TreeSet: " + treeSet);
  // HashSet: [20, 10, 30]
 //  TreeSet: [Alice, Bob, John]
	}
 }
 

 













27 July 2023

Polymorphism In Java - learngreen.net

 Polymorphism In Java

  Polymorphism is an important concept in object-oriented programming. It's from the four most important concepts of object-oriented programming which are encapsulation, inheritance and abstraction, and polymorphism. It treats objects of different classes common as objects of superclass which helps in code reusability. Polymorphism gets into action through method overriding and method overloading. We have already discussed about method overloading and method overriding in our previous blogs.

Let's recall method overloading and method Overriding:-


Method Overriding:-

Method overriding permits the subclass to implement the method from the superclass which has the same name, return type, and parameters. This allows the subclass to replace or extend the behavior of the superclass method.






  //Example Method Overriding
  package Java;
  /* Base class representing a
   * TwoWheeler with a method company() 
   */
  class TwoWheeler {
  void company() {
  System.out.println("Honda");
    }
  }
  /* Subclass of TwoWheeler representing
   *  a vehicle with a method company()
   */
  class vehicle extends TwoWheeler {
  /* Method overriding: Custom implementation
   * of company() for the vehicle subclass
   */
   void company() {
   System.out.println("BMW");
     }
  }

  /* Another subclass of TwoWheeler
   * representing an automobile with
   * a method company()
   */
  class automobile extends TwoWheeler {
  /* Method overriding: Custom implementation
   * of company() for the automobile subclass
  */
  void company() {
  System.out.println("Bajaj");
     }
  }

  /* Main class MDOR to
   * test the vehicle hierarchy
   */
  public class MDOR {
  public static void main(String[] args) {
  TwoWheeler obj = new TwoWheeler();
  obj.company(); // Output: Honda
  vehicle obj1 = new vehicle();
  obj1.company(); // Output: BMW
  automobile obj2 = new automobile();
  obj2.company(); // Output: Bajaj
        }
    }
 

 

 Method Overloading:-

Method overloading in Java possesses multiple methods having the same name but different parameters. These methods can have different numbers or different parameter types.


 package Java;
  public class MDOL {
  // Method to divide two integers	 
  int divide(int x, int y){
  return x/y;
   }	
  /*  Method overloading:- 
   *  Method to divide two doubles
   */
  double divide( double x, double y) {
  return x/y;	 
  }
  public static void main(String[] args) {
  MDOL obj = new MDOL();
  /* Call the int version
  * of divide method, result is 2 (8 / 4) 
  */
  System.out.println(obj.divide(8,4));
  /* Call the double version of divide method, 
   * result is 4.0 (8.0 / 2.0)
   */
  System.out.println(obj.divide(8.0, 2.0));
  //Output-> 2
  //         4.0

	}
 }

 


 //Example of Polymorphism
 package Java;
 public class PYMS {
 public static void main(String[] args) {
 //Runtime Polymorphism (Dynamic Polymorphism)
 /* Method overriding has runtime polymorphism
  * which permits objects of different classes
  * to act as objects of their common superclass
  * and enables to implement to decide the JVM
  * which specific method needs to be declared.
  * 	 
  */
  TwoWheeler obj = new TwoWheeler();
  /* Classes vehicle and automobile overriding
   * the method company() of superclass Twowheeler 
   * This is an example of Rutime polymorphism	 
   */
  vehicle obj1 = new vehicle();
  automobile obj2 = new automobile();
  obj.company();
  obj1.company();
  obj2.company();
 
  //Compile time Polymorphism(Static Polymorphism)
  /* Compile time polymorphism comes in action 
  * by method overloading.This permits different 
  * methods with same name but having different
  * parameters which are from same class.Types
  * of arguments has been provided during method
  * declaration choosing appropriate method 
  * determine by the compile time.
  */
  MDOL object = new MDOL();
  /* Two overloaded methods has been called
  * one which takes as integers and other which
  * takes as doubles Java compiler identifies
  * the correct method to be called based on
  * the data types of arguments.This is an
  * example of compile-time polymorphism. 
  */
  System.out.println(object.divide(8,4));
  System.out.println(object.divide(8.0, 2.0));
 
  /* Output->
  * Honda
  * BMW
  * Bajaj
  * 2
  * 4.0
  */
	}
  }
 

 

24 July 2023

Arrays In Java - learngreen.net

   An array is a unique object that can contain the factors of an ordered collection. The kind of array element is known as the base type of the array; the number of elements it includes is a fixed attribute known as length. Java supports all primitive and reference types.

The fundamental array syntax is very similar to that of C++. We create an array of the detailed length and get entry to the elements with the index operator [ ]. Unlike different languages, arrays in Java are authentic high-quality objects. An array is an instance of an extraordinary Java array classification and has a corresponding type in the type system. With this ability that to get the right of entry to an array, like any different object, we first declare a variable of the fabulous kind and then create an instance of it for the usage of the new operator.


  Java implicitly creates a distinctive array class kind for us on every occasion we declare a new array type. You do not always want to recognize about this method to use arrays, however, it will help you apprehend their shape and relationship to other Java objects later. Java lets us use the[ ] operator to access array elements so that arrays look the way we anticipate them to. We should enforce our very own classes that act like arrays, however, we have to settle for strategies like get( ) and set( ) rather than using the extraordinary [ ] notation.

  Java presents an equivalent one-of-a-kind form of the new operator that lets in us to construct an array instance of a given length with [ ] notation or to initialize it immediately from a structured list of values.

An array-type variable is denoted by means of a base type followed by means of the empty brackets [ ].


 int [ ] numbers;

 In each case, numbers (Array variable) are declared as an array of integers. The measurement of the array is no longer yet trouble because we are declaring solely the array type variable. We have now not yet created a proper occasion of the array class, with its associated storage. It’s no longer even possible to specify the length of an array when declaring an array type variable. The measurement is strictly a feature of the array object itself, not a reference to it.


Arrays In Java

 
Creation of Arrays and initialization:-

  For creating an instance of an array new operator is used. We specify the base type of the array and its length in square brackets after the new operator as follows.




 int [ ] numbers = new int [8];

 // base type is int
 // Array variable is numbers
 // Size(length) of array is 8

Array index always starts with zero. Hence in the above code, the first element of the number [ ] is zero and its last element is 7.

The default value of each element in an array is always null until we assign value to that element as follows.



 String names [ ] = new String [3];
 names [0] = "Ram";
 names [1] = "Shyam";
 // names [2] == null

 

Creating an array using Array Literal:-

In Java, an array literal is a shorthand used to create and initialize an array with specific values ​​directly in the source code. This makes it possible to define the table and its elements concisely and clearly. 


An array literal is represented by a comma-separated list of elements ​ in { } braces. The values ​​in the brackets correspond to the elements of the table, and the elements are automatically assigned to the corresponding positions in the table according to their order in the letter.


Syntax of an Array Literal:-




 dataType[ ] arrayName = {Element1, Element2, Element3, ...};
 // dataType-> data type of an element which will stored in the array
 // arrayName-> Array variable name

 


 // Example on Array Literal
 package Java;
 public class ArrayLiteral {
 public static void main(String[] args) {
 //Initialize an integer array 
 int []	digits = {8,5,4,7,9 };
 //Use for loop to print the array
 /* "digits.length" is a property of 
  * array variable 'digits' which gives
  * the number of elements(length)
  * in the array.
  */
 for(int i=0; i<=digits.length;i++) {
 System.out.print(digits[i]+ " ");
 //Output-> 8 5 4 7 9
     }
   }
 }
 

 Accessing Array Elements:-

Array index starts from zero and ended up at array length minus 1. In the below example if we have to access element 5 then we have to write the index number (digits[2]) of that element. 




 package Java;
 public class ArrayLiteral {
 public static void main(String[] args) {
 //Initialize an integer array 
 int []	digits = {8,5,4,7,9 };
 System.out.println(digits[0]);
 System.out.println(digits[1]);
 System.out.println(digits[2]);
 System.out.println(digits[3]);
 System.out.println(digits[4]);
 
 //Output->
 // 8
 // 5
 // 4
 // 7
 // 9
    }
 }

 Accessing  an array Length:-

We use the length property of the array to access the length of the array Below example shows how to access the length of an array.



 package Java;
 public class ArrayLG {
 public static void main(String[] args) {
 //Create string Array words with size 3	 
 String [] words = {"Ram","Laxman","Shyam"};
 //Accessing array Length using property length
 System.out.println(words.length);
 //Output-> 3
	}
 }

 Multidimensional Arrays:-

 An array of arrays is a multidimensional array. When we want to store data in a tabular form, such as a table with rows and columns, multidimensional arrays are helpful.

Each array should be added within its own set of curly braces to form a two-dimensional array.



 package Java;
 public class MA {
 public static void main(String[] args){
 //Create int array RandomNumbers with size 2
 int[ ][ ] RandomNumbers = {{5,2,8}, {7,9,2}};
 //Accessing the length of array RandomNumbers
 System.out.println(RandomNumbers.length);
 /* Accessing the element 8(index number is 2)
  * in the first array (Index number of
  * first array is 0).
  */
 System.out.println(RandomNumbers[0][2]);	 
 //Output->
 // 2
 // 8
  }
 }

 


 //Changing the Elements
 package Java;
 public class MA1 {
 public static void main(String[] args) {
 //Create int array Numbers with size 2
 int[][] Numbers = {{9,10,88}, {79,5,4}};
 /* Changing value of element second 5
  * to 2
  */
  Numbers[1][1]= 2; 
 System.out.println(Numbers[1][1]);		 
 //Output->
 // 2 
   }
 }

 Arrays Class:-

The "java.util.Arrays" class has different methods to work with Arrays such as sorting, searching, and filling. We will discuss more in detail about Array Class in Java in our next blog. Meanwhile, we will see a short code example of the sorting method of the "java.util.Arrays" class.



 package Java;
 import java.util.Arrays;
 public class AC {
 public static void main(String[] args) {
 // Create int array Numbers with size 5
 int[] Numbers = {8, 5, 9, 1, 2};
 // Sorting the array in ascending order
 Arrays.sort(Numbers);
 /* Printing the sorted array
  * using Arrays.toString()
  */
 System.out.println(Arrays.toString(Numbers));
 //Output-> [1, 2, 5, 8, 9]
     }
  }

 Array Exception:-

When we try to access an element that is outside the index range of an array, we get an error ArrayIndexOutOfBoundsException. This is a type of RuntimeException. Below is an example of an ArrayIndexOutOfBoundsException error.



 package Java;
 public class AE {
 public static void main(String[] args){
 String [] Cities = new String[5];
 try {
 Cities[0]= "Delhi";
 Cities[1]= "Bangalore";
 Cities[2]= "Bombay";
 Cities[3]= "Chennai";
 Cities[4]= "Ahmedabad";
 /* This will throw an Array 
  * ArrayIndexOutOfBoundsException
  */
 Cities[5]= "Pune";
 }
 catch(ArrayIndexOutOfBoundsException error){
 System.out.println
 ("Handled error:- "+ error.getMessage()); 
 // Output-> Handled error:- 5
     }
    }
  }

 Array Clone:-

  For creating a copy of an array we can use the clone( ) method.



 package Java;
 import java.util.Arrays;
 public class CL {
 public static void main(String[] args) {
 int[] MainArray = {88,47,89};
 //Cloning the original Array
 /* Use the 'clone()' method to create a
  * new array named 'clonedArray' which is
  * the copy of MainArray.
  */
 int[] clonedArray = MainArray.clone();
 //Modifying the cloned Array
 /* Modify the second element 47 of
  * MainArray with 84.
  */
 clonedArray[1]=84;
 // Printing both Arrays
 /* Array cloning creates a new copy with
  * separate memory allocation.
  */
 System.out.println(Arrays.toString(MainArray));
 System.out.println(Arrays.toString(clonedArray));
 //Output->
 // [88, 47, 89]
 // [88, 84, 89]
    }
  }
 

 







18 July 2023

Encapsulation In Java - learngreen.net

 Encapsulation is one of Java's four fundamental principles of object-oriented programming (OOP). It is a mechanism that combines data and the methods (or functions) that operate on that data into a single unit called a class. Encapsulation provides data hiding and abstraction, allowing better data control and protection.  


 Here are the main aspects of Java encapsulation:-

 

 1. Data Hiding:-  Encapsulation hides the internal data of an object and exposes only the necessary data through public methods. By marking internal data fields as private, you restrict direct access to them outside the class. This prevents unauthorized changes and ensures that data is only accessed and modified using controlled methods. 


 2. Access modifiers:-  Java provides access modifiers like public, private, protected, and default (no modifier). You can use these modifiers to control the visibility and accessibility of class members (fields and methods). Private members can only be accessed within the same class, while public members can be accessed from any class. Protected members have limited access to the same package or subcategories. 


 3. Getters and Setters:-  You can interact with private data fields by defining public methods called getters and setters. Getters provide read-only access to data, allowing other classes to retrieve values. Setters allow write access, allowing other classes to modify the data. By encapsulating the data in these methods, you can apply additional logic, validation, or handling as needed.  


 4. Data validation and consistency:-  Encapsulation allows you to enforce validation rules and maintain data consistency. By encapsulating data in methods, you can perform checks, validations, and transformations before receiving or returning data. This helps keep the integrity of the object's state and prevents incorrect or inconsistent data from being stored.  


 5. Abstraction:-  Encapsulation supports abstraction by exposing only the essential details of an object while hiding complexity. Users of an encapsulated class interact with a well-defined interface of public methods without knowing the details of the internal implementation. 


In general, Java encapsulation promotes safe, modular, and maintainable code by encapsulating data and behavior within a class, controlling access with accessor specifications, and providing a well-defined interface for interacting with an object.


Encapsulation In Java




 package Java;
 class Bike {
 // Private data field for the bike company	 
 private String company;
 //Private data field for the bike's cc
 private int cc;
 //Getter for the company field
 public String getcompany() {
 return company;
   }
 //Setter for the company field
 public void setcompany(String company) {
 this.company = company;	 
   }
 //Getter for the cc field
 public int getcc() {
 return cc;	 
   }
 //Setter for the cc field
 public void setcc(int cc) {
 this.cc=cc;	 
   }
 }
 public class MainCode {
 public static void main(String[] args) {
 // Creating an instance of the Bike class	 
 Bike obj = new Bike();
/* Setting the company and cc
 * values using the setter methods
 */
 obj.setcompany("Royal Enfield");
 obj.setcc(350);
 System.out.println
 ("Bike Company "+ obj.getcompany());
 System.out.println
 ("Bike cc "+ obj.getcc());
 //Output-> 
 /* Bike Company Royal Enfield
  * Bike cc 350
  */
  }
 }

 


 package Java;
 class Machine {
 //Use private to hide data	 
 private int price;
 //Getter for the price field
 public int getprice() {
 return price;	 
  }
 //Setter for the price field
 public void setPrice(int price)
 {
   this.price = price; 
   }
 }
 public class LearnGreen {
 public static void main(String[] args) {
 Machine obj = new Machine();
 obj.setPrice(150000);
 System.out.println
("The price of the machine is "+obj.getprice());
 /* Output->
  * The price of the
  * machine is 150000
  */
   }
 }

 


 package Java;
 class Addition {
 //fields to calculate addition	
 int first;
 int second;
 //constructor to initialize values
 Addition(int first, int second) {
 this.first=first;
 this.second=second;
 }
 //method to calculate addition
 public void getaddition() {
 int Addition = first + second;
 System.out.println("Addition is "+Addition);
   }
 }

 public class MainClass {
 public static void main(String[] args) {
 //Create object of class Addition	 
 Addition obj = new Addition(8,4);
 //call method getaddition()
 obj.getaddition();
 /* Output->
  * Addition is 12
  */
 }

}

 



16 July 2023

Access Modifiers In Java - learngreen.net

 Access modifiers in Java are keywords used to specify the accessibility or visibility of classes, methods, and variables in a Java program. There are four access modifiers in Java public, protected, default and private.

Public Access Modifier:- This is the most  accessible modifier. Public access modifiers are accessible from any class or package. Public keyword is used to specify public acceess modifier.




//Example of Public Access Modifier
 package Interview;
 //Create class PB
 public class PB {
 //Create method display	 
 public void display()
 {
 System.out.println
 ("Public Access Modifier");	
 }
 public static void main(String[] args) {
 //Create object of class PB	 
 PB obj = new PB();
 //Call method display
 obj.display();
 //Output-> Public Access Modifier
	}
}

 


 import Interview.PB;
 public class PB1 {
 public static void main(String[] args) {
 PB obj = new PB();
 /* Call method display from package
  * Interview of class PB
  */
 obj.display();
 //Output-> Public Access Modifier
	}
  }

 Protected Access Modifier:- Protected access modifier are accessible within the same package and subclasses in different packages.



 /* Program is about
  * protected modifier 
  */
 package Interview;
 //Create class PT
 public class PT {
 protected void method() {
 System.out.println("Protected Method");	 
  }
 }

 


  package InterviewOne;
 /* Import class PT of package
  * Interview to call method
  * method
  */
 import Interview.PT;
 public class PT_One extends PT {
 public static void main(String[] args) {
 //Create object of class PT_One	 
 PT_One obj = new PT_One();
 //Call Method method
 obj.method();
 //Output-> Protected Method
  }
 }

 Default Access Modifier (No Keyword):-  When not any keyword is specified it is an default accesss modifier. These are accessible only within the same package.




  /* Program to describe
    * about default modifier
   */
 package Interview;
 /* create class default
  * access modifier which
  * contains method Exercise
  */
 public class DT {
 void Exercise() {
 System.out.println("Swimming"); 
  }

 }


 



  /* Program shows error
  * when we try to call 
  * default method from
  * class DT of package
  * interview to class DT1
  * of Package InterviewOne
  */
 package InterviewOne;
 import Interview.DT;
 public class DT1 {
 public static void main(String[] args) {
 DT obj = new DT();
 obj.Exercise();
 //Error-> 
 /* The method Exercise() from
  * the type DT is not visible
  */
   }
 }

Private Access Modifier:- We can access priavte access only from same class. They are not accessible from any other package or classs. They are specified using keyword private.

We can not declare super classes or interfaces as private because private denotes class is accessed only within the enclosing class and protected denotes class is accessed only within the super class and subclasses.


 


 package Interview;
 /* Program is about
  * private modifier
  * when we try to access 
  * method method from
  * PrivateOne class we do 
  * get an compilation error
  */
 //create class PrivateOne
 class PrivateOne {
 //create method method	 
 private void method(){
 System.out.println
 ("Private Modifier");	 
	}
 }
 public class Private {
 public static void main(String[] args) {
 PrivateOne obj = new PrivateOne();
 obj.method();
 //Error->
 /* The method() from the type
  * privateOne is not visible
  */
	}
 }

 

Access Modifiers In Java




14 July 2023

Difference between Abstract class and Interface In Java - learngreen.net


Difference between Abstract class and Interface In Java


In Java, each abstract class and interface are used to define common behaviors and supply a contract for classes to implement. However, there are countless key variations between abstract classes and interfaces:


1. Definitions:-

- Abstract Class:- An abstract type is a class that cannot be instantiated. It serves as a blueprint for derived classes and can comprise both abstract and non-abstract methods. It may also encompass instance variables, constructors, and approach implementations.

- Interface:- An interface is a collection of summary methods that outline a contract for classes to implement. It can't include any instance variables or method implementations, only method signatures. It is implemented by way of lessons to provide particular behavior.


2. Instantiation:-

- Abstract Class:- An abstract type can't be instantiated directly with the usage of the 'new' keyword. Instead, it must be extended by way of a subclass, and the subclass can be instantiated.

- Interface:- An interface can't be instantiated at all. It can only be implemented via classes, which ability a class has to provide implementations for all the strategies declared in the interface.


3. Multiple Inheritance:

- Abstract Class:- A class can extend only one abstract class due to the fact Java does now not aid more than one inheritance for classes.

- Interface:- A class can implement more than one interface. This lets in for achieving multiple inheritance of behavior through implementing a couple of interfaces.


4. Method Implementation:

- Abstract Class:- An abstract type can provide approach implementations (non-abstract methods) along with abstract methods. Subclasses can select to override or use the provided method implementations.

- Interface:- An interface can't provide method implementations. It only broadcasts method signatures that implementing instructions need to define.


5. Access Modifiers:

- Abstract Class:- An abstract category can have abstract methods with any access modifier (public, private, protected, or default) and non-abstract techniques with any access modifier.

- Interface:- All methods declared in an interface are implicitly public and abstract. It is no longer indispensable to specify these modifiers explicitly.


6. Usage:-

- Abstract Class:- Abstract classes are often used when there is a joint base implementation among the derived classes. They supply a way to share code and common functionality.

- Interface:- Interfaces are used when there is a want for multiple unrelated classes to share a common behavior. They define a contract that ensures classes adhere to a particular behavior except imposing any implementation details.


In general, if you favor furnishing a common base implementation or if you need to acquire a couple of inheritance of behavior, a summary class is a higher choice. On the other hand, an interface is more appropriate if you want to outline a contract for unrelated training to implement a specific behavior.





 //Abstract class Example
 abstract class City {
 protected String name;
    
 public City(String name) {
 this.name = name;
    }
 public abstract void area(); 
 public void special() {
 System.out.println
 (name + " Education");
    }
 }

 class CityOne extends City {
 public CityOne(String name) {
 super(name);
    }
    
 @Override
 public void area() {
 System.out.println
 (name + " is a large city");
    }
    
 @Override
 public void special() {
 System.out.println
 (name + " has a rich cultural heritage");
    }
 }
 public class Class {
 public static void main(String[] args) {
 CityOne obj = new CityOne("Pune");
 obj.area();
 // Output-> Pune is a large city          
 obj.special();
 // Output-> Pune has a rich cultural heritage        
    }
 }
 

 


 
 //Interface Example
 
 interface Project {
 oid start();
 void stop();
 }
 class Engineering implements Project {
 @Override
 public void start() {
 System.out.println
 ("Engineering Work started");
    }
 @Override
 public void stop() {
 System.out.println
 ("Engineering Work stopped");
    }
 }
 class Pharmacy implements Project {
 @Override
 public void start() {
 System.out.println
 ("Pharmacy work started");
    }
    
 @Override
 public void stop() {
 System.out.println
 ("Pharmacy work stopped");
    }
 }
 public class MainClass {
 public static void main(String[] args) {
 Project obj = new Engineering();
 obj.start();
 // Output-> Engineering Work started  
 obj.stop();
 // Output-> Engineering Work stopped   
 Project obj2 = new Pharmacy();
 obj2.start();
 // Output-> Pharmacy work started
 obj2.stop();
 // Output-> Pharmacy work stopped   
    }
 }
 

 



11 July 2023

What is an Interface In Java - learngreen.net

 In Java, an interface is a reference type that defines a set of summary methods. It serves as a contract or blueprint for the class to follow. It specifies which methods the class have to implement except specifying how to implement them.


What is an Interface In Java?


Here are some key points about Java interfaces:-

1.  An interface is described by way of the key-word "interface" followed through the title of the interface. It can additionally contain general fields and default methods.

2. Abstract Methods:- An interface can declare summary methods that each and every class implementing the interface must implement. These methods have no body and are public and summary by using default. Any class that implements an interface must supply an implementation of all summary methods.  

3 Implementation of multiple interfaces:- A Java type can put into effect multiple interfaces. This lets in a class to inherit behavior from a couple of sources and operate a couple of inheritance-like operations.

4. Interface Inheritance:- Interfaces can additionally extend different interfaces the usage of the "extends" keyword. This approves growing a hierarchy of interfaces the place the child interface inherits methods and constants from the parent interface.

5. Default Methods:- Since Java 8, interfaces can have default methods. A default technique is a method that has a default implementation inside the interface itself. These techniques can be overridden by means of implementation classes, but they supply a default implementation if now not overridden through the implementation class. 

6. Persistent Fields:- Interfaces can declare persistent fields that are implicitly public, static, and final. These fields can be accessed the usage of the UI name and the discipline name.

7. Application isolation:- Interfaces assist isolate the specification or contract of the application. By programming the user interface, you can write flexible and extensible code that works in distinct implementations of the person interface.

Interfaces are extensively used in Java to outline conventions and acquire type polymorphism. They enable for loose coupling, code reusability, and abstraction, allowing instructions to put into effect a couple of interfaces and outline behavior barring implementation information.




 Syntax of Interface

 interface {

 // constant fields

 // Abstract methods

 // Default method (Java 8 onwards)

 }

 To declare an interface, use the interface keyword. It is used to provide complete abstraction. That capacity all the methods in an interface are declared with an empty body and are public and all fields are public, static, and closing by default. A type that implements an interface must implement all the methods declared in the interface. To implement interface use implements keyword.

Importance of Interface:-

It is used to achieve complete abstraction.  Since java does not support multiple inheritance for a class, multiple inheritance can be achieved using an interface. Each class can extend only one class, but each class  can  implement an infinite number of interfaces. It is also used to secure a loose joint. Interfaces are used to implement abstraction. So the question arises, why use interfaces when we have abstract classes? This is because abstract classes can contain non-final variables, while interface variables  are final, public and static.

 Object of interface could not be created but we can create reference variable of interface type. By assigning this reference variable to object of class which implements interface

A class has the potential to put in force more than one interfaces simultaneously. This potential that a single type can declare that it adheres to the specs of more than one interfaces and furnish implementations for all the techniques described inside every interface. By imposing more than one interfaces, a type can inherit and make use of the behaviors and contracts distinctive by each interface independently.

Interfaces have the ability to prolong different interfaces, which approves them to inherit strategies from the prolonged interfaces. This capacity that an interface can declare additional strategies in addition to the techniques inherited from the prolonged interfaces. By extending interfaces, new functionality and approach contracts can be added, presenting greater precise behaviors and requirements for instructions that put in force these interfaces.

When a class implements an interface, it is required to provide implementations for all the strategies that are described inside the interface. This capacity that the class need to define the unique functionality and behavior for every method declared in the interface. By imposing the interface, the class is in reality making a promise to adhere to the contract designated with the aid of the interface and to furnish the integral code for every method. Failure to implement any of the interface methods in the category will end result in a compilation error.

In an interface, all methods are by default public and abstract. This capability that the strategies declared in an interface do now not have a body or implementation. They serve as a contract or a declaration of the methods that any type imposing the interface have to define. The accountability of supplying the proper implementation of these techniques lies with the classes that implement the interface. Therefore, when a class implements an interface, it need to supply the concrete implementation of all the abstract methods declared in the interface.  All methods in an interface are public and abstract, which means they do not have a body. All the fields in an interface are public, static, and final, making them constant values. Interfaces are beneficial for accomplishing multiple inheritances, enabling a class to inherit behaviors from more than one interfaces. Interfaces promote free coupling between classes, making it less complicated to change implementations barring affecting other components of the code. Interface cannot declare occasion variables because they are by default public, static, and final. Constructors are now not allowed inner an interface. The essential method cannot be declared inner an interface. 


interface First { //Default method that prints // "www.learngreen.net" default void Language() { System.out.println ("www.learngreen.net"); } } class programming implements First { public static void main(String[] args) { //Create an object of class programming programming skill = new programming(); //Call the Language() method skill.Language(); //Output-> www.learngreen.net } }

 



 interface MyClassOne {
 //Abstarct method declaration    
 public void information(); }
 class child implements MyClassOne {
  public void information()  {
 //Implementation of the
 // information() method 
 String name = "Shyam";
 int height = 6;
 System.out.println
 ("name "+ name);
 System.out.println
 (" height " +height+ " ft");
  }  }
 public class MyClass1 {
 public static void main(String[] args) {
 //Create an object of child class
 child object = new child();
 //Call the information() method       
 object.information();
//Output-> name shyam
//         height 6 ft      
    }
 }

 



08 July 2023

How Abstract class works In Java - learngreen.net

 In Java, an abstract class is a special  class that cannot be used to create objects directly. Instead, it provides a template or example for copying other classes. It is designed to be extended with subclasses that provide specific instructions for how the abstract class works. 


 An abstract class is a special  class that has the word "abstract" in its declaration. For example, a class called MyClass that is not directly accessible. An abstract class is a unique  class that can have methods without any real code. Subclasses must create their own versions of all methods required by the abstract class. Subclasses must make their own versions of any methods  not fully defined in the abstract class. 

 Abstract methods are a type of special method declared with a specific keyword called "abstract". They are empty and  contain no instructions or computer commands.  Abstract classes can have  clear and well-defined methods called concrete methods. These methods  set behavior that can be shared with lower classes. Concrete methods are ordinary methods that do not contain the word "abstract". 


Objects of an abstract class cannot be created using the "new" keyword because abstract classes cannot be instantiated directly. But you can use a generic class to talk about specific objects of that specific type. Abstract classes are made to complement other classes. When a subclass extends an abstract class, it must create its own versions of all  methods defined by the abstract class, but those versions need not  contain the actual code. If a subclass does not have code for specific abstract methods, it must also  be marked as "abstract". Abstract classes are usually used to create a common layout for a group of similar classes. They also provide certain features or functions that are already configured for use. They help reuse code  and ensure that subclasses follow a certain format. 

 

 Simply put, an abstract class in Java is like a blueprint for other classes. It does not work by itself and  needs other classes to modify it with certain methods. This helps you establish a common way of doing things and gives you a starting point for  subclasses.


How Abstract class works In Java?






// Abstract class Syntax

abstarct class Space
 {
     int address;

 // Abstarct method

 abstract void city( );

 }

 


 
package Interview;
 //create abstract class
 public abstract class Rain{
/* create abstract methods
 * start and stop	 
 */
 abstract void start();
 abstract void stop();
 //create nested class city
 public static class City extends Rain {
 /* Declared methods start and stop
  * from abstract class Rain	 
 */
 void start() {
 System.out.println("Rain started");
	 }
 void stop() {
 System.out.println("Rain Stopped");	 
 }
	 
 }
 public static void main(String[] args) {
 //create object of class city	 
 City obj = new City();
 //call methods start and stop
 obj.start();
 obj.stop();
 
 /* Output->
  * Rain started
  * Rain Stopped
  */
 
   }
 }

 


 package Interview;
 // Create abstract class
 public abstract class He {
 // Create abstract method MethodA	 
 abstract void MethodA();
 /* Create nested class You
  * which extends the He class
  */
 public static class You extends He {
 /* Implement the abstract method	
  * MethodA from the He class 
  */
 public void MethodA() {
 System.out.println("Message");
        }
    }
 public static void main(String[] args) {
 /* Create an object of
  * the nested class You
  * using the enclosing class name		 
  */
 He.You obj1 = new He.You();
 obj1.MethodA();
 /* Call the overridden MethodA 
  * from the You class
  */
 
 //Output:- Message
    }
 }

 


 package Interview;
 // Create Abstract class
 /* This program is about
  * abstract class having
  * no abstract method
  */
 public abstract class Mother {
 /* Create Method working
 * (Not an abstract method) 
 */
 public void Working () {
 System.out.println
 ("Method working called");	
 }
 
 /* create Nested class daughter
  * which extends superclass Mother 
  */
 public static class
 daughter extends Mother {
	 
 }
 public static void main(String[] args) {
 daughter obj = new daughter();
 obj.Working();
 //Output->
 // Method working called
	}
 }

 


 package Interview;
 /* This program is about
  * we can call static method
  * of abstract class in main
  */
 //create abstract class
 public abstract class LG {
 //create static method	 
 static void method() {
 System.out.println("Method calling"); 
 }
 public class son extends LG {
  
 }
 public static void main(String[] args) {
 /* called static method
  * defined in abstract class LG
  * (Superclass)	 
  */
 LG.method();
 //Output-> Method calling
	}
 }

 




04 July 2023

Explain about Final Keyword In Java - learngreen.net

 In Java, the final keyword is utilized to define variables, methods and classes  that cannot be changed after assigning  a value . 


When we define variable as final, the value of the variable could not be changed. This denotes that once we assign value to final variable, we cant assign it a different value.


When we declared method as final we can not override that method using any subclass. This is useful when we want to prevent the method to be overriden.


When we declared class as final in Java , we can not make it subclass and we cant extend that class as well. This is useful when we didn't want class to be modified and extended as well.


Explain about Final Keyword In Java




In the above code we initialize data type int  with constant as 8 and and in next step if we try to change the value of constant variable we do get an error because we use Final keyword. 





In the above code we do create method message
and in next step we do create sub class with name X which extends superclass Final. If we try to override method message we do get compilation error as we used Final keyword their to prevent
method overriding.







In the above code we do create class with name final but before class word we use final keyword  &  if we try to extend class sub with superclass we do get an compilation error as we are using final keyword to create class with name final.


















02 July 2023

Super Keyword In Java - learngreen.net

  The "super" key-word in Java is used to refer to the superclass or parent class of a subclass. It lets in you to access and name methods, variables, and constructors from the superclass within the subclass.

1. Accessing superclass variables:- In case a subclass contains a variable with the equal become aware of as a variable in its superclass, you'll utilize the "super" key-word to distinguish between them and get to the superclass variable.


2. Invoking superclass strategies:- If a subclass overrides a strategy from its superclass, you'll utilize the "super" keyword to invoke the superclass method.


This is beneficial when you pick to add some extra performance to the overridden technique whilst nonetheless making use of the unique conduct of the superclass method.


3. Calling superclass constructors:- In a subclass constructor, you can use the "super" key-word to call a constructor from the superclass

This allows you to reuse the initialization code from the superclass and operate any extra subclass-specific initialization.


By the use of the "super" keyword, you can effectively leverage the functionality and assets supplied via the superclass in the subclass. It promotes code reuse and inheritance, enabling you to construct greater modular and extensible Java programs.


Super Keyword In Java


 



 /* Example A.
  * Accessing variable having same
  * name in Super and Nested Class
  * using Super keyword.
  */
 package Interview;
 public class MyClass {
 int a = 5;  
 //Instance variable a with initial value of 5
 public class MyClass1 extends MyClass {
 // Nested class MyClass1 extending MyClass	 
 int a = 8; 
 // Instance variable a with initial value of 8        
 void display() {
 // Method to display values of a	 
 System.out.println(a);
 //Print the value of a in MyClass1 (8)
 System.out.println(super.a);
 //Print the value of a in the superclass MyClass(5)
         }
     }
 public static void main(String[] args) {
 MyClass obj = new MyClass();
 //Create an object of the outer class MyClass
 MyClass1 obj1 = obj.new MyClass1();
 /* Create an object of the nested
  * class MyClass1 using the outer class object
  */
 obj1.display();
 //Call the display()method
 //Output-> 8
 //         5
     }
 }

 



 //Example B
 
 package Interview;
 public class ClassMain {
 public void print() {
 //create print method	 
 System.out.println("ClassMain print method");
}
 
 public class sub extends ClassMain {
 //create nested class sub	 
 public void print() {
 //method override	 
 super.print();
 //Invoking ClassMain method
 System.out.println("sub class print method");
 }
 }

 public static void main(String[] args) {
 ClassMain obj = new ClassMain();
 //create object of ClassMain
 sub obj1 = obj.new sub();
 
 /* create object of nested
  * sub class using object of
  * super class(ClassMain)
  * 
  */
 obj1.print();
 //Call print method
 //Output-> ClassMain print method
 //         sub class print method

	}

}

 


 /* Example C
  * Super keyword is used
  * if we want to call 
  * the constructor in subclass
  * (Page)
  */
 package Interview;
 public class Book {
 Book(){
 //Create constructor 
 System.out.println("Main class constructor");
 }
 public class Page extends Book {
 Page() {
 //Create constructor 
 super();
 //Called Main class(Book)constructor
 System.out.println("Subclass constructor");
	 }
 }
 public static void main(String[] args) {
 Book obj = new Book();
 Page obj1 = obj.new Page();
 //Output->
 /* Main class constructor
    Main class constructor
    Subclass constructor
  */
  }
 }