Skip to content

Instantly share code, notes, and snippets.

@sumanssaurabh
Forked from amelieykw/00 - Basic.md
Created March 31, 2019 22:46
Show Gist options
  • Save sumanssaurabh/3f3bfa12beb950e1329ed94c31ea3d6f to your computer and use it in GitHub Desktop.
Save sumanssaurabh/3f3bfa12beb950e1329ed94c31ea3d6f to your computer and use it in GitHub Desktop.
[Java Interview Preparation] #java #interview
  1. Java Identifiers
  2. Data types
  3. How to define our own data type in java(enum)
  4. Variables
  5. Scope of Variables
  6. Loops in Java(Practice)
  7. For-each loop in Java
  8. For Loop in Java | Important points
  9. Decision Making(if, if-else, switch, break, continue, jump)(Practice)
  10. Switch Statement in Java(Practice)
  11. String in Switch Case in Java
  12. Forward declarations
  13. Widening Primitive Conversion
  14. Type conversion in Java
  15. Comments in Java
  16. Does Java support goto?
  17. Interesting facts about null in Java
  18. Using underscore in Numeric Literals

1. Java Identifiers

Java Identifiers:

  • class name
  • method name
  • variable name
  • label

Rules for defining Java Identifiers:

  • The only allowed characters are ([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore)
  • Identifiers should not start with digits([0-9])
  • case-sensitive
  • no limit on the length
  • Reserved words can't be used as an identifier

2. Data Type

  • Statically typed language (Java)
    • each variable and expression type is already known at compile time
    • once a variable is declared to be of a certain data type, it cannot hold values of their data types
  • Dynamically typed language (Python, Ruby)
    • these languages can receive different data types over the time

Java = statically typed and a strongly typed language - each type of data is predefined as part of the programming language - all constants or variables defined for a given program must be described with one of the data types

Java:

  1. Primitive data
  2. Object data (programmer created type)

3. enum in Java

Enumerations serve the purpose of representing a group of named constants in a programming language.

Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.

The main objective of enum is to define our own data types(Enumerated Data Types).

Declaration of enum in java :

Enum declaration can be done outside a Class or inside a Class but not inside a Method.

// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
    RED, GREEN, BLUE;
}
 
public class Test
{
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

or

// enum declaration inside a class.
public class Test
{
    enum Color
    {
        RED, GREEN, BLUE;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

Rules:

  • First line inside enum should be list of constants and then other things like methods, variables and constructor.
  • According to Java naming conventions, it is recommended that we name constant with all capital letters

points of enum:

  • Every enum internally implemented by using Class.
/* internally above enum Color is converted to
class Color
{
     public static final Color RED = new Color();
     public static final Color BLUE = new Color();
     public static final Color GREEN = new Color();
}*/
  • Every enum constant represents an object of type enum.
  • enum type can be passed as an argument to switch statement.
// A Java program to demonstrate working on enum
// in switch case (Filename Test. Java)
import java.util.Scanner;
 
// An Enum class
enum Day
{
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY;
}
 
// Driver class that contains an object of "day" and
// main().
public class Test
{
    Day day;
 
    // Constructor
    public Test(Day day)
    {
        this.day = day;
    }
 
    // Prints a line about Day using switch
    public void dayIsLike()
    {
        switch (day)
        {
        case MONDAY:
            System.out.println("Mondays are bad.");
            break;
        case FRIDAY:
            System.out.println("Fridays are better.");
            break;
        case SATURDAY:
        case SUNDAY:
            System.out.println("Weekends are best.");
            break;
        default:
            System.out.println("Midweek days are so-so.");
            break;
        }
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "MONDAY";
        Test t1 = new Test(Day.valueOf(str));
        t1.dayIsLike();
    }
}
  • Every enum constant is always implicitly public static final.
    • Since it is static, we can access it by using enum Name.
    • Since it is final, we can’t create child enums.
  • We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt.
// A Java program to demonstrate that we can have
// main() inside enum class.
enum Color
{
    RED, GREEN, BLUE;
 
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

Enum and Inheritance:

  • All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.
  • toString() method is overridden in java.lang.Enum class, which returns enum constant name.
  • enum can implement many interfaces.

values(), ordinal() and valueOf() methods :

  • These methods are present inside java.lang.Enum.
  • values() method can be used to return all values present inside enum.
  • Order is important in enums. By using ordinal() method, each enum constant index can be found, just like array index.
  • valueOf() method returns the enum constant of the specified string value, if exists.

enum and constructor :

  • enum can contain constructor and it is executed separately for each enum constant at the time of enum class loading.
  • We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.

enum and methods :

  • enum can contain concrete methods only i.e. no any abstract method.
// Java program to demonstrate that enums can have constructor
// and concrete methods.
 
// An enum (Note enum keyword inplace of class keyword)
enum Color
{
    RED, GREEN, BLUE;
 
    // enum constructor called separately for each
    // constant
    private Color()
    {
        System.out.println("Constructor called for : " +
        this.toString());
    }
 
    // Only concrete (not abstract) methods allowed
    public void colorInfo()
    {
        System.out.println("Universal Color");
    }
}
 
public class Test
{    
    // Driver method
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
        c1.colorInfo();
    }
}
Output:

Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

A variable is the name given to a memory location. It is the basic unit of storage in a program.

  • The value stored in a variable can be changed during program execution.
  • A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In Java, all the variables must be declared before they can be used.

How to declare variables?

Types of variables

  • Local Variables : A variable defined within a block or method or constructor is called local variable.
    • The scope of these variables exists only within the block in which the variable is declared
    public class StudentDetails
{
    public void StudentAge() 
    {   //local variable age
        int age = 0;
        age = age + 5;
        System.out.println("Student age is : " + age);
    }
 
    public static void main(String args[])
    {
        StudentDetails obj = new StudentDetails();
        obj.StudentAge();
    }
}

Student age is : 5
public class StudentDetails
{
    public void StudentAge() 
    {   //local variable age
        int age = 0;
        age = age + 5;
    }
 
    public static void main(String args[]) 
    {   
        //using local variable age outside it's scope
        System.out.println("Student age is : " + age);
    }
}
error: cannot find symbol
 " + age);
  • Instance Variables : Instance variables are non-static variables and are declared in a class outside any method, constructor or block.
    • As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
    • Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.
import java.io.*;
class Marks
{   
    //These variables are instance variables.
    //These variables are in a class and are not inside any function
    int engMarks;
    int mathsMarks;
    int phyMarks;
}
 
class MarksDemo
{
    public static void main(String args[])
    {   //first object
        Marks obj1 = new Marks();
        obj1.engMarks = 50;
        obj1.mathsMarks = 80;
        obj1.phyMarks = 90;
 
        //second object
        Marks obj2 = new Marks();
        obj2.engMarks = 80;
        obj2.mathsMarks = 60;
        obj2.phyMarks = 85;
 
        //displaying marks for first object
        System.out.println("Marks for first object:");
        System.out.println(obj1.engMarks);
        System.out.println(obj1.mathsMarks);
        System.out.println(obj1.phyMarks);
     
        //displaying marks for second object
        System.out.println("Marks for second object:");
        System.out.println(obj2.engMarks);
        System.out.println(obj2.mathsMarks);
        System.out.println(obj2.phyMarks);
    }
}
  • Static Variables : (Class variables)
    • These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
    • Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
    • Static variables are created at start of program execution and destroyed automatically when execution ends.

access the variable as:

class_name.variable_name;
import java.io.*;
class Emp {
 
   // static variable salary
   public static double salary;
   public static String name = "Harsh";
}
 
public class EmpDemo
{
     public static void main(String args[]) {
       
      //accessing static variable without object         
      Emp.salary = 1000;
      System.out.println(Emp.name + "'s average salary:" + Emp.salary);
   }
     
}

Instance variable Vs Static variable

  • Each object will have its own copy of instance variable whereas We can only have one copy of a static variable per class irrespective of how many objects we create.
  • Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of instance variable. In case of static, changes will be reflected in other objects as static variables are common to all object of a class.
  • We can access instance variables through object references and Static Variables can be accessed directly using class name.
  • Syntax for static and instance variables:
class Example
{
    static int a; //static variable
    int b;        //instance variable
}
Modifier Package Subclass World
public Yes Yes Yes
protected Yes Yes No
Default (no modifier) Yes No No
private No No No
public class Test
{
    public static void main(String[] args)
    {
        System.out.print("Y" + "O");
        System.out.print('L' + 'O');
    }
}

At first glance, we expect “YOLO” to be printed.

Actual Output: “YO155”.

Explanation: When we use double quotes, the text is treated as a string and “YO” is printed, but when we use single quotes, the characters ‘L’ and ‘O’ are converted to int. This is called widening primitive conversion. After conversion to integer, the numbers are added ( ‘L’ is 76 and ‘O’ is 79) and 155 is printed.

public class Test 
{
    public static void main(String[] args) 
    {
        System.out.print("Y" + "O");
        System.out.print('L');
        System.out.print('O');
    }
}

Output: YOLO

Explanation: This will now print “YOLO” instead of “YO7679”. It is because the widening primitive conversion happens only when ‘+’ operator is present.

  1. Classes and Objects
  2. Java object storage
  3. Different ways to create objects in Java
  4. How to swap or exchange objects
  5. Inheritance in Java
  6. Encapsulation in Java
  7. Abstraction in Java
  8. Run-time Polymorphism in Java
  9. Association,Composition and Aggregation
  10. Access and Non Access Modifiers in Java
  11. Access Modifiers
  12. this reference
  13. Method Overloading
  14. Output of Java program | Set 22 (Overloading)
  15. Method Overriding
  16. Output of Java program | Set 18 (Overriding)
  17. Shadowing of static methods(Also called Method Hiding)
  18. Covariant return types
  19. Object class
  20. Flexible nature of java.lang.Object
  21. Overriding equals method of Object class
  22. Overriding toString() method of Object class
  23. Instance Variable Hiding
  24. initializer block in java(static block)
  25. instance initializer block in java(non-static block)
  26. Static vs Dynamic Binding
  27. Why Java is not a purely Object-Oriented Language?

Classes

  1. Modifiers : A class can be public or has default access (Refer this for details).
  2. Class name : The name should begin with a initial letter (capitalized by convention).
  3. 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.
  4. 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.
  5. Body: The class body surrounded by braces, { }.

Objects

  1. State : attributes of an object / the properties of an object.
  2. Behavior : methods of an object / the response of an object with other objects.
  3. Identity : It gives a unique name to an object and enables one object to interact with other objects.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated.

Dog tuffy;

If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.

Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.

All classes have at least one constructor.

If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor.

This default constructor calls the class parent’s no-argument constructor (as it contain only one statement i.e super();), or the Object class constructor if the class has no other parent (as Object class is parent of all classes either directly or indirectly).

The objects that are not referenced anymore will be destroyed by Garbage Collector of java.

Anonymous objects

Anonymous objects are the objects that are instantiated but are not stored in a reference variable.

  • They are used for immediate method calling.
  • They will be destroyed after method calling.
  • They are widely used in different libraries. For example, in AWT libraries, they are used to perform some action on capturing an event(eg a key press).

In example below, when a key is button(referred by the btn) is pressed, we are simply creating anonymous object of EventHandler class for just calling handle method.

btn.setOnAction(new EventHandler()
{
    public void handle(ActionEvent event)
    {
        System.out.println("Hello World!");
    }
});

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.

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 (See this for more details).

one class is allow to inherit the features(fields and methods) of another class.

  1. Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
  2. 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.
  3. 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment