Top Stories

Ankaj Gupta
December 27, 2020
how to create enum in java

What is enum in Java?

An enum is a special "data type" that used to create our own datatype like classes and It represents a group of constants (a variable that does not change).

The enum is short for "enumerations", which means "specifically listed" and the Enum data also known as Enumerated Data Type.

# Defining Java enum

Instead of C/C++, in java programming language enum types are more powerful. Here, we can define an enum both inside and enum outside the class but not inside a Method

"Rules" to defing enum in Java:

  • To create an enum in Java, use the enum keyword (instead of class or interface), and separate the constants with a comma(,).

  • The enum can be defined within or outside the class because it is similar to a class. The semicolon (;) at the end of the enum constants are optional

  • Because enum are constants, the names of an enum type's fields are in uppercase letters.

Syntax :
  • enum Directions { EAST, WEST, NORTH, SOUTH; }

  •   OR

  • enum Directions { EAST, WEST, NORTH, SOUTH }

# Access Java enum

You can access enum constants with the help of dot operator.

Syntax :
  • Directions myVar = Directions.NORTH;

Let's see, the simple examples of enum Java :

1.) enum inside class

  ➤ Example 2: Defined enum inside class

  1. class EnumExample {

  2. //Defining the enum inside the class

  3. enum Directions{

  4.   EAST, WEST, NORTH, SOUTH

  5. } //semicolon(;) is optional here

  6. public static void main(String args[]) {

  7.   Directions myvar= Directions.NORTH;

  8.   System.out.println(myvar);

  9. }

  10. }

Output :
  • NORTH

Java program Java programming
Read more
Ankaj Gupta
October 02, 2020
Polymorphism in php with example

What is polymorphism in php?

Polymorphism in PHP is a concept by which we can perform a single action in different ways. Polymorphism is derived in two from Greek word “poly” and “morphism”.

"Poly" means many and "morphism" means (forms) property which help us to assign more than one property.

# Types of polymorphism :

There are two types of Polymorphism:

  • Overriding(Run-time polymorphism).

  • Overloading(Compile-time polymorphism).

1.) Method Overriding : Method overriding is one of the ways in which Php supports Runtime Polymorphism. If same functions defined in parents and child class with same signature know as function overriding.

  • It is also known as dynamic binding or late binding.

Let’t see an example of Function overriding :

  ➤ Example : function overriding;

  1. <?php

  2. class ParentClass {

  3. public function myMessage(){

  4.   echo "Parent-Class method called";

  5. }

  6. }

  7. class ChildClass extends ParentClass{

  8. public function myMessage(){

  9.   echo "Child-Class method called";

  10. }

  11. }

  12. $obj = new ChildClass(); // Creating object for ChildClass

  13. $obj -> myMessage(); // Method callng

  14. ?>

Output :
  • Child-Class method called

2.) Overloading : If a class has multiple functions having same name but different in parameters, It is known as function overloading.

  • It contains the same function name and that function preforms different tasks according to the number of arguments.

  • It is also known as static or early binding.

Note : Like other OOP programming languages function overloading, PHP can not be done by native approach.

In PHP function overloading is done with the help of magic function __call() and this function takes parameter( name and arguments).

Let's see, by the simple example :

  ➤ Example : overloading;

<?php
  class Overloading{
    function sum($a, $b){
      echo $a+$b;
    }
    function sum($a, $b, $c){
      echo $a+$b+$b; 
    }
  }
  $obj = new Overloading(); // Creating object
  $obj -> sum(10, 20); 
  $obj -> sum(11, 22, 33); 
?>
Output :
  • Fatal error: Cannot redeclare PropertyOverload::sum() in Overloading.php on line 6


Important "Property" and "Rules" of overloading in PHP:

  • overloading methods must be defined as public

  • After creating the object for a class, we can access a set of entities that are methods or properties not defined within the scope of the class.

  • Such entities are said to be overloaded properties or methods, and the process is called as overloading.

  • For working with these overloaded properties or methods, PHP magic methods are used.

  • Most of the magic methods will be triggered in object context except __callStatic() method which is used in a static context.

There are two types of overloading in PHP:

  • Property overriding.

  • Method overloading.

2.1 ) Property Overriding : PHP property overloading is used to create dynamic properties in the object context.

  • A property associated with a class instance, and if it is not declared within the scope of the class, it is considered as overloaded property..

Note : For creating these properties no separate line of code is needed.

There are following operations performed with overloaded properties in PHP:
  1. Setting and getting overloaded properties.

  2. Evaluating overloaded properties setting.

  3. Undo such properties setting.

  4. Before performing the operations, we should define appropriate magic methods. which are,

    • __set() - __set() method is run when writing data to inaccessible (private or protected) or non-existing properties.

    • __get() - __get() methog is utilized for reading data from inaccessible (private or protected) or non-existing properties.

    • __isset() - __isset() magic method is invoked when we check overloaded properties with isset() function

    • __unset() - Similarly, this function will be invoked on using PHP unset() for overloaded properties.

Let's try, to create simple example :

  ➤ Example : property overriding;

  1. <?php

  2. class PropertyOverloading {

  3. // Location of overloading data

  4. private $data = array();

  5.  

  6. // Overloading not used on declared properties.

  7. public $declared = 1;

  8.  

  9. // Overloading only used on when accessed outside the class.

  10. private $hidden = 2;

  11.  

  12. // Function definition

  13. public function __set($name, $value){

  14.   echo "Setting '$name' to '$value'\n";

  15.   $this->data[$name] = $value;

  16. }

  17. // Function definition

  18. public function __get($name){

  19.   echo "Getting '$name': ";

  20. if(array_key_exists($name, $this->data)){

  21.   return $this->data[$name];

  22. }

  23.   $trace = debug_backtrace();

  24.   return null;

  25. }

  26. // Function definition

  27. public function __isset($name){

  28.   echo "Is '$name' set? \n";

  29.   return isset($this->data[$name]);

  30. }

  31. // Definition of __unset function

  32. public function __unset($name){

  33.   echo "Unsetting '$name'\n";

  34.   unset($this->data[$name]);

  35. }

  36. // getHidden functinon definition

  37. public function getHidden(){

  38.   return $this->hidden;

  39. }

  40. }

  41.  

  42. $obj = new PropertyOverloading(); // Create an object

  43.  

  44. // Set value 1 to the object variable

  45. $obj->a = 1;

  46. echo $obj->a . "\n";

  47.  

  48. // Use isset function to check

  49. var_dump(isset($obj->a)); // 'a' is set or not

  50.  

  51. unset($obj->a); // Unset 'a'

  52.  

  53. var_dump(isset($obj->a));

  54.  

  55. echo $obj->declared . "\n\n";

  56.  

  57. echo "Private property are visible inside the class";

  58. echo $obj->getHidden() . "\n\n";

  59.  

  60. echo "Private property are not visible outside of class\n";

  61. echo $obj->hidden . "\n";

  62. ?>

Output :
  • Setting 'a' to '1'

  • Getting 'a: 1

  • Is 'a' set?

  • bool(true)

  • Unsetting 'a'

  • Is 'a' set?

  • bool(false)

  • 1

  •  

  • Private property are visible inside the class 2

  •  

  • Private property are not visible outside of class

  • Getting 'hidden:

2.2 ) Method Overloading : It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic-methods dedicated to the appropriate purpose, Unlike property overloading.

PHP method overloading allows function call on both static and object context, The related magic functions are following,

  • __call() - It is triggered when invoking inaccessible methods in the object context.

  • __callStatic() - It is triggered when invoking inaccessible methods in static context.

Note : value of $name in '__call' and '__callStatic' is case sensitive.

Let's try, to create simple example :

  ➤ Example : method overriding;

  1. <?php

  2. class MethodOverloading {

  3. public function __call($name, $arguments){

  4.   echo "Calling object method '$name'"

  5.    . implode(', ', $arguments) . "\n";

  6. }

  7. public static function __callStatic($name, $arguments){

  8.   echo "Calling static method '$name'"

  9.    . implode(', ', $arguments) . "\n";

  10. }

  11. }

  12. $obj = new MethodOverloading(); // Create an object

  13. $obj -> runTest('in object context');

  14. MethodOverloading::runTest('in static context');

  15. ?>

Output :
  • Calling object method 'runTest' in object context

  • Calling static method 'runTest' in static context

oops php
Read more
Ankaj Gupta
September 29, 2020
Java program for student mark list using inheritance - java code examples with output

Program to print student mark list using inheritance

In this section, You will learn how to calculate and print student marks lists of n number of student in java, with the help of single level inheritance.

single level inheritance

Let's try to create a simple example :

  ➤ Example : student.java;

  1. import java.io.*;

  2. class MList {

  3. static public StudentWrapper theStudents = new StudentWrapper();

  4. public void ViewRecords() {

  5.   System.out.println("_______________________________________________________________");

  6.   System.out.println("SNo Student Name Sub1 Sub2 Sub3 Sub4 Sub5 Total");

  7.   System.out.println("_______________________________________________________________");

  8.  

  9.   for(int i = 0; i < theStudents.m_nMaxStudents; i++){

  10.   System.out.format("%1$-5d", i+1);

  11.  

  12.   System.out.format("%1$-19s", theStudents.m_studList[i].name);

  13.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[0]);

  14.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[1]);

  15.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[2]);

  16.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[3]);

  17.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[4]);

  18.   System.out.format("%1$-7d", theStudents.m_studList[i].total);

  19.   System.out.println();

  20. }

  21.   System.out.println("_______________________________________________________________");

  22. }

  23. public void InputRecords() {

  24. try{

  25.   InputStreamReader input = new InputStreamReader(System.in);

  26.   BufferedReader reader = new BufferedReader(input);

  27.  

  28.   System.out.print("Student Name : ");

  29.   String name;

  30.  

  31.   int[] marks = new int[5];

  32.   name = reader.readLine();

  33.  

  34. for(int i = 1; i <= 5; i++){

  35.   System.out.print("Sub "+i+" Mark : ");

  36.   marks[i-1] = Integer.parseInt(reader.readLine());

  37. }

  38.   theStudents.AddRecord(name, marks);

  39. }

  40. catch(Exception e){

  41.   e.printStackTrace();

  42. }

  43. }

  44. }

  45. class Student extends MList {

  46. public static void main(String args[]) {

  47.   MList obj_marks = new MList();

  48.   String stdNumber = "";

  49.   InputStreamReader input = new InputStreamReader(System.in);

  50.   BufferedReader reader = new BufferedReader(input);

  51.  

  52. try{

  53.   System.out.print("Enter the number of students: ");

  54.   stdNumber = reader.readLine();

  55.   int numStudents = Integer.parseInt(stdNumber);

  56.  

  57. for(int i = 1; i <= numStudents; i++){

  58.   System.out.println("\nEnter "+i+" Student Information \n");

  59.   obj_marks.InputRecords();

  60. }

  61.   obj_marks.ViewRecords();

  62. }

  63. catch(Exception e){

  64.   e.printStackTrace();

  65. }

  66. }

  67. }

  68. class StudentsInfo {

  69.   public String name;

  70.   public int[] marks = new int[5];

  71.   public int total;

  72. }

  73. class StudentWrapper {

  74. public StudentsInfo[] m_studList = new StudentsInfo[100];

  75. public int m_nMaxStudents;

  76.  

  77. public int AddRecord(String name, int[] marks) {

  78.   StudentsInfo stud = new StudentsInfo();

  79.   stud.name = name;

  80.   stud.marks = marks;

  81.   stud.total = 0;

  82. for(int i = 0; i < 5; i++){

  83.   stud.total += stud.marks[i];

  84. }

  85.   m_studList[m_nMaxStudents++] = stud;

  86.   return 1;

  87. }

  88. }

Output :
  • Enter the number of students:2

  • Enter 1 Student Information

  • Student Name: Ankaj

  • Sub 1 Mark : 8

  • Sub 1 Mark : 9

  • Sub 1 Mark : 6

  • Sub 1 Mark : 7

  • Sub 1 Mark : 9

  •  

  • Enter 1 Student Information

  •  

  • Student Name: Anmol

  • Sub 1 Mark : 9

  • Sub 1 Mark : 6

  • Sub 1 Mark : 7

  • Sub 1 Mark : 8

  • Sub 1 Mark : 9

  • ---------------------------------------------------------------------

  • SNO Student Name Sub1 Sub2 Sub3 Sub4 Sub5 Total

  • ---------------------------------------------------------------------

  • 1 Ankaj 8 9 6 7 9 39

  • 2 Anmol 9 6 7 8 9 39

  • ---------------------------------------------------------------------

Screenshot :
Java program for student mark list using inheritance
Recommended Posts:
Java program
Read more
Ankaj Gupta
September 29, 2020
Java program for student mark list using class and object - java code examples with output

Program to print student mark list using class and object

In this section, You will learn how to calculate and print student total marks lists of n nuumber of student in java, with the help of InputStreamReader and BufferedReader class.

java program to calculate and display the total and the n student marks
Java program for student mark list using class and object

Let's try to create a simple example :

  ➤ Example : student.java;

  1. import java.io.*;

  2. class MList {

  3. static public StudentsInfo theStudents = new StudentsInfo();

  4. public static void ViewRecords() {

  5.   System.out.println("_______________________________________________________________");

  6.   System.out.println("SNo Student Name Sub1 Sub2 Sub3 Sub4 Sub5 Total");

  7.   System.out.println("_______________________________________________________________");

  8.  

  9.   for(int i = 0; i < theStudents.m_nMaxStudents; i++){

  10.   System.out.format("%1$-5d", i+1);

  11.  

  12.   System.out.format("%1$-19s", theStudents.m_studList[i].name);

  13.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[0]);

  14.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[1]);

  15.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[2]);

  16.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[3]);

  17.   System.out.format("%1$-7d", theStudents.m_studList[i].marks[4]);

  18.   System.out.format("%1$-7d", theStudents.m_studList[i].total);

  19.   System.out.println();

  20. }

  21.   System.out.println("_______________________________________________________________");

  22. }

  23. public static void InputRecords() {

  24. try{

  25.   InputStreamReader input = new InputStreamReader(System.in);

  26.   BufferedReader reader = new BufferedReader(input);

  27.  

  28.   System.out.print("Student Name : ");

  29.   String name;

  30.  

  31.   int[] marks = new int[5];

  32.   name = reader.readLine();

  33.  

  34. for(int i = 1; i <= 5; i++){

  35.   System.out.print("Sub "+i+" Mark : ");

  36.   marks[i-1] = Integer.parseInt(reader.readLine());

  37. }

  38.   theStudents.AddRecord(name, marks);

  39. }

  40. catch(Exception e){

  41.   e.printStackTrace();

  42. }

  43. }

  44. public static void main(String args[]) {

  45.   String stdNumber = "";

  46.   InputStreamReader input = new InputStreamReader(System.in);

  47.   BufferedReader reader = new BufferedReader(input);

  48.  

  49. try{

  50.   System.out.print("Enter the number of students: ");

  51.   stdNumber = reader.readLine();

  52.   int numStudents = Integer.parseInt(stdNumber);

  53.  

  54. for(int i = 1; i <= numStudents; i++){

  55.   System.out.println("\nEnter "+i+" Student Information \n");

  56.   InputRecords();

  57. }

  58.   ViewRecords();

  59. }

  60. catch(Exception e){

  61.   e.printStackTrace();

  62. }

  63. }

  64. }

  65. class Student {

  66.   public String name;

  67.   public int[] marks = new int[5];

  68.   public int total;

  69. }

  70. class StudentsInfo {

  71. public Student[] m_studList = new Student[100];

  72. public int m_nMaxStudents;

  73.  

  74. public int AddRecord(String name, int[] marks) {

  75.   Student stud = new Student();

  76.   stud.name = name;

  77.   stud.marks = marks;

  78.   stud.total = 0;

  79. for(int i = 0; i < 5; i++){

  80.   stud.total += stud.marks[i];

  81. }

  82.   m_studList[m_nMaxStudents++] = stud;

  83.   return 1;

  84. }

  85. }

import java.io.*;

class MList {
    static public StudentsInfo theStudents = new StudentsInfo();

    public static void ViewRecords() {
        System.out.println("_______________________________________________________________");
        System.out.println("SNo Student Name       Sub1   Sub2   Sub3   Sub4   Sub5   Total");
        System.out.println("_______________________________________________________________");

        for(int i = 0; i < theStudents.m_nMaxStudents; i++){
            System.out.format("%1$-5d", i+1);

            System.out.format("%1$-19s", theStudents.m_studList[i].name);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[0]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[1]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[2]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[3]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[4]);
            System.out.format("%1$-7d", theStudents.m_studList[i].total);
            System.out.println();
        }
        System.out.println("_______________________________________________________________");
    }   

    public static void InputRecords() {
        try{
            InputStreamReader input = new InputStreamReader(System.in);  
            BufferedReader reader = new BufferedReader(input);  

            System.out.print("Student Name : ");
            String name;

            int[] marks = new int[5];
            name = reader.readLine(); 

            for(int i = 1; i <= 5; i++){
                System.out.print("Sub "+i+" Mark : ");
                marks[i-1] = Integer.parseInt(reader.readLine()); 
            }
            theStudents.AddRecord(name, marks);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        String stdNumber = "";
        InputStreamReader input = new InputStreamReader(System.in);  
        BufferedReader reader = new BufferedReader(input); 

        try{
            System.out.print("Enter the number of students: ");
            stdNumber = reader.readLine(); 
            int numStudents = Integer.parseInt(stdNumber); 

            for(int i = 1; i <= numStudents; i++){
                System.out.println("\nEnter "+i+" Student Information \n");
                InputRecords();
            }

            ViewRecords();

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

        }

    }

}

class Student {
  public String name;
  public int[] marks = new int[5];
  public int total;

}

class StudentsInfo {
    public Student[] m_studList = new Student[100];
    public int m_nMaxStudents;

    public int AddRecord(String name, int[] marks) {
        Student stud = new Student();
        stud.name = name; 
        stud.marks = marks; 
        stud.total = 0; 

        for(int i = 0; i < 5; i++){
            stud.total += stud.marks[i]; 
        }

        m_studList[m_nMaxStudents++] = stud; 
        return 1;
    }
}
Output :
  • Enter the number of students:2

  • Enter 1 Student Information

  • Student Name: Ankaj

  • Sub 1 Mark : 90

  • Sub 1 Mark : 80

  • Sub 1 Mark : 85

  • Sub 1 Mark : 82

  • Sub 1 Mark : 70

  •  

  • Enter 1 Student Information

  •  

  • Student Name: Anmol

  • Sub 1 Mark : 88

  • Sub 1 Mark : 75

  • Sub 1 Mark : 80

  • Sub 1 Mark : 92

  • Sub 1 Mark : 70

  • ---------------------------------------------------------------------

  • SNO Student Name Sub1 Sub2 Sub3 Sub4 Sub5 Total

  • ---------------------------------------------------------------------

  • 1 Ankaj 90 80 85 82 70 407

  • 2 Anmol 88 75 80 92 70 405

  • ---------------------------------------------------------------------

Recommended Posts:
Java program
Read more
Ankaj Gupta
September 03, 2020
java program for student details using inheritance

# Java program to print student details using "single-level" inheritance

In this section, You will learn how to print student details using single inheritance in java, with Scanner and without Scanner class.

1.) With "Scanner" class

Let's try to create a simple example :

  ➤ Example : student.java;

  1. import java.util.Scanner;

  2. class StudentDetails {

  3.   int roll_no;

  4.   String name, cl;

  5. //creating a function to take student details

  6.   void input() {

  7. Scanner sc = new Scanner(System.in);

  8.  

  9. System.out.print("Enter Roll Number: ");

  10. roll_no = sc.nextInt(); //=> 22\n == buffer

  11.  

  12. sc.nextLine(); // => \n

  13.  

  14. System.out.print("Enter Name: ");

  15. name = sc.nextLine();

  16.  

  17. System.out.print("Enter class: ");

  18. cl = sc.nextLine();

  19.   }

  20. }

  21. class Student extends StudentDetails {

  22.   //method to display student details

  23.   void display() {

  24. System.out.println("/******* Student details printed ********/");

  25. System.out.println("Roll Number is: "+roll_no);

  26. System.out.println("Your name is: "+name);

  27. System.out.println("Your class is: "+cl);

  28.   }

  29.   public static void main(String args[]) {

  30. Student obj = new Student();

  31. obj.input();

  32. obj.display();

  33.   }

  34. }

Output :
  • Enter Roll Number: 22

  • Enter Name: Coder Website

  • Enter class: 12th

  • /******* Student details printed ********/

  • Roll Number is: 22

  • Your name is: Coder Website

  • Your class is: 12th

2.) Without "Scanner" class

Let's try to create a simple example :

  ➤ Example 2: student.java;

  1. class StudentDetails {

  2.   int roll_no;

  3.   String name, cl;

  4. //creating a function to take student details

  5.   void input(int roll, String nam, String cl_name) {

  6. roll_no = roll;

  7. name = nam;

  8. cl = cl_name;

  9.   }

  10. }

  11. class Student extends StudentDetails {

  12.   //method to display student details

  13.   void display() {

  14. System.out.println("\n/******* Student details printed ********/");

  15. System.out.println("Roll Number is: "+roll_no);

  16. System.out.println("Your name is: "+name);

  17. System.out.println("Your class is: "+cl);

  18.   }

  19.   public static void main(String args[]) {

  20. Student std1 = new Student();

  21. std1.input(20, "Ankaj Gupta", "12th");

  22. std1.display();

  23.  

  24. Student std2 = new Student();

  25. std2.input(10, "Anmol kumar", "10th");

  26. std2.display();

  27.   }

  28. }

Output :
  • /******* Student details printed ********/

  • Roll Number is: 20

  • Your name is: Ankaj Gupta

  • Your class is: 12th

  •  

  • /******* Student details printed ********/

  • Roll Number is: 10

  • Your name is: Anmol kumar

  • Your class is: 10th

Recommended Posts:
Java program
Read more
Ankaj Gupta
August 31, 2020
How to calculate content-length python

# Python requests calculate content length

In this section, we'll create a simple "content-length" calculate program in python. Let's follow the following steps and get content-length of your web page:

Step 1 : It is very important to install python requests module / package(eg : pip install requests).

  • pip install requests # for window

  • OR

  • pip3 install requests # for max, linux

Step 2 : After installing the request package, To verify the installation, you can try to import it like below:

  • import requests

Note : If you don't receive any errors importing the requests module, then it was successful installed.

Step 3 : Now, You can use 'GET request' to retrieve data from any destination

Let's create the simple example :

  ➤ Example : length.py

  1. import requests

  2. response = requests.get('https://www.google.com')

  3. #Just take the len() of the content of the response:

  4. content_len= len(response.content)

  5. print(content_len)

Output :
14227
Python programming
Read more
Ankaj Gupta
August 20, 2020
Javascript division by 0

# Javascript Divide by Zero Check

In JavaScript, division by zero does not cause an any error. While, it generates Infinity, which is a reserved word in JavaScript.

Let's try to create simple example:
  • If the division number is positive then it generates positive Infinity.

Example 1 : divided by zero;

  • In this code, we will divide the positive integers by 0.

  1. <script type="text/javascript">
  2. var a = 10, b= 0;

  3. var division;

  4.  

  5. division = a / b;

  6. console.log(division);

  7. </script>
Output :
  • Infinity

  • If the division number is negative then it generates negative -Infinity.

Example 2: divided by zero;

  • In this code, we will divide the negative integers by 0.

  1. <script type="text/javascript">
  2. var a = -10, b= 0;

  3. var division;

  4.  

  5. division = a / b;

  6. console.log(division);

  7. </script>
Output :
  • -Infinity

Recommended Posts:
Code JavaScript Code
Read more

Discover more amazing content below