- Package
Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub packages. They are used to avoid name conflicts and to control access of class, interface and enumeration etc. A package can be defined as a group of similar types of classes, interface, enumeration and sub-package. Using package it becomes easier to locate the related classes. By convention packages are written in small letters.
package co.mymusing
- Boolean operator
a & b boolean logical AND
a | b boolean logical OR
a ^ b boolean logical exclusive OR - Arrays
An array is a collection of similar data types. Array is a container object that hold values of homogenous type. It is also known as static data structure because size of an array must be specified at the time of its declaration.// Array declaration syntax datatype[] identifier or datatype identifier[] // Example int [] aAAry = {2, 3, 4};
- for-each loop
Used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.// Syntax for(data_type variable : array | collection){ } // Example for(String s:list){ System.out.println(s); }
- Class
Class is a template for creating objects which defines its state and behavior. A class contains field and method to define the state and behavior of its object.<Access Modifier> class <Class_Name> extends <Super_Class_Name> implements <Interface_Name>
ACCESS MODIFIER : Defines who can access this class and members of the class.
CLASS_NAME : Unique name for the class in a specific package.
SUPER_CLASS_NAME : Name of the class which given class extends.
INTERFACE_NAME : Name of an Interface which above class implements.There can be only one public class per source code file but it can have multiple non public classes. In case there is any public class present in the source code file, the name of the file should be the name of the class.
Static Variable
When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.Static Method
Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. You cannot call non-static methods from inside a static method.Instance Variable
Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. The term ‘object’, however, refers to an actual instance of a class. Every object must belong to a class. Objects are created and eventually destroyed – so they only live in the program for a limited time. While objects are ‘living’ their properties may also be changed significantly.Objects
Object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
- Inner Class
Inner class or nested class is a class i.e. declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.Static Nested Class
A static nested class is the one that has static modifier applied. Because it is static it cannot refer to non-static members of its enclosing class directly. Because of this restriction static nested class is seldom used.Non-static Nested class
It has access to all variables and methods of Outer class and may refer to them directly. But the reverse is not true, that is, Outer class cannot directly access members of Inner class. One more important thing to notice about an Inner class is that it can be created only within the scope of Outer class.class Outer { public void display() { Inner in=new Inner(); in.show(); } class Inner { public void show(){ System.out.println("Inside inner"); } } } class Test { public static void main(String[] args) { Outer ot=new Outer(); Outer.Inner in= ot.new Inner(); in.show(); } }
Anonymous class
A class without any name is called Anonymous class.public class ATest { public static void main(String args[]) { //Annonymous class created Animal an = new Animal(){ public void type() { System.out.println("Anonymous animal"); } }; an.type(); } }
- Access Modifiers
The access modifiers specifies accessibility (scope) of a data member, method, constructor or class. There are four types of access modifiers i.e. private, default, protected and public.private
access modifier is accessible only within class. If you don’t use any modifier, it is treated as default by default.default
modifier is accessible only within package.protected
access modifier is accessible within package and outside the package but through inheritance only. Protected access modifier can be applied on the data member, method and constructor. It can’t be applied on the class.public
access modifier is accessible everywhere. It has the widest scope among all other modifiers. this
keyword
It can be used inside method or constructor of class. It (this) works as a reference to the current object whose method or constructor is being invoked. It can be used to refer to any member of the current object from within an instance method or constructor.this
can be passed as an argument in the method call, argument in the constructor call, and can also be used to return the current class instance.this
keyword with Constructor
this
keyword can be used inside the constructor to call another overloaded constructor in the same Class. This is called the Explicit Constructor Invocation. This occurs if a Class has two overloaded constructors, one without argument and another with argument. Then the “this” keyword can be used to call constructor with argument from the constructor without argument. This is required as the constructor can not be called explicitly.this Keyword with Method
this keyword can also be used inside Methods to call another Method from same Class.- null
There are two major categories of types: primitive and reference. Variables declared of a primitive type store values; variables declared of a reference type store references.String x = null;
In this case, the initialization statement declares a variables
x
.x
stores string reference. It is null here, so there is no memory allocated for it. It indicates that the object reference is not currently referring to an object. - Constructor
Constructor are used to initialize the object. They are invoked at the time of object creation. Constructor name must be same as its class name and must have no explicit return type.Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters. A constructor can be called from inside another constructor usingthis
keyword. A class that extends another class does not inherit its constructors. However, the subclass must call a constructor in the superclass inside one of the subclass constructors.super
keyword is followed by parentheses refers to a constructor in the superclass. Sub class constructor has to invoke super class instructor, either explicitly by programmer or implicitly by compiler. Super class constructor is called before the sub class constructor.// Constructor inheritance class Person { String firstName; String lastName; Person(String fName, String lName) { firstName = fName; lastName = lName; } } class Student extends Person { int id; Student(String fName, String lName, int nId) { super(fName,lName); id = nId; } } // Constructor overloading public class Perimeter { // #1 public Perimeter() { System.out.println("From default"); } // #2 public Perimeter(int x) { this(); System.out.println("Circle perimeter: " + 2*Math.PI*x); } // #3 public Perimeter(int x, int y) { this(100); System.out.println("Rectangle perimeter: " +2*(x+y)); } public static void main(String args[]) { // Calls #3 Perimeter p3 = new Perimeter(10, 20); } }
- Instance initializer block
Instance initializer block is used to initialize the instance data member. The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block. If a class has more than one they all run in the order they appear in the class file.Initialization blocks come in two flavors i.e. Static initialization blocks and instance initialization blocks. Static initialization blocks runs first when the class is first loaded. Declared by using the keyword Static. Instance initialization blocks runs every time when the instance of the class is created.class InitDemo{ static int y; int x; // Static Initialization Block static { y = 10; } // Instance Initialization Block { x = 20; } }
- Method Overloading
Method Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different. Method overloading is also known as Static Polymorphism.- Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method.
- It can have different access modifiers.
- Constructor can be overloaded.
- Overloaded methods must have a different argument list.
- The parameters may differ in their type or number, or in both.
- It allows the user to achieve compile time polymorphism.
- Class Inheritance
Inheritance is one of the feature of Object-Oriented Programming. Inheritance allows a class to use the properties and methods of another class. Derived class inherits the states and behaviors from the base class. Derived class is also called subclass and the base class is also known as super-class. Derived class can add its own additional variables and methods.Inheritance is a compile-time mechanism. A super-class can have any number of subclasses. But a subclass can have only one superclass because Java does not support multiple inheritance. Theextends
keyword indicates that you are making a new class that derives from an existing class.// A class to display the attributes of the vehicle class Vehicle { String color; private int speed; private int size; } // A subclass which extends for vehicle class Car extends Vehicle { int CC; int gears; }
Constructors and Inheritance
The constructor in the superclass is responsible for building the object of the superclass and the constructor of the subclass builds the object of subclass. When the subclass constructor is called during object creation, it by default invokes the default constructor of super-class. Hence, in inheritance the objects are constructed top-down. The superclass constructor can be called explicitly using the keyword super, but it should be first statement in a constructor. The keyword super always refers to the superclass immediately above of the calling class in the hierarchy.Method Overriding
A subclass can override (replace) an inherited method so that the subclass’s version of the method is called instead. An overriding method must specify the same name, parameter list, and return type as the method being overridden. In order to call a superclass method from the overriding subclass method, prefix the method’s name with the reserved word super and the member access operator.// Method overriding class MyBaseClass{ public void disp() { System.out.println(“Parent class method”); } } class MyChildClass extends MyBaseClass{ protected void disp(){ super.disp(); System.out.println(“Child class method”); } public static void main( String args[]) { MyChildClass obj = new MyChildClass(); obj.disp(); } }
Dynamic method dispatch is a technique which enables us to assign the base class reference to a child class object. In dynamic method dispatch the object can call the overriding methods of child class and all the non-overridden methods of base class but it cannot call the methods which are newly declared in the child class.
Rules for method overriding:-
- Argument list should be exactly the same as that of the overridden method.
- Return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
- Access level cannot be more restrictive than the overridden method’s access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or protected.
- Method declared final cannot be overridden.
- Method declared static cannot be overridden but can be re-declared.
Some notes on inheritance:-
- The derived class inherits all the members and methods that are declared as public or protected.
- If declared as private it can not be inherited by the derived classes.
- The derived class cannot inherit a member of the base class if the derived class declares another member with the same name.
- The Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class.
- Constructor are not inherited
- Object class
Object class is parent class of all the classes. Parent class reference variable can refer the child class object, know as upcasting. If a Class does not extend any other class then it is direct child class of Object and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all classes. Hence Object class acts as a root of inheritance hierarchy in any program.
Important methods in Object class:- toString() : It provides String representation of an Object and used to convert an object to String. The default toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object.
- hashCode() : JVM generates a unique number which is hashcode. It returns distinct integers for distinct objects. It convert the internal address of object to an integer by using an algorithm.
- equals(Object obj) : Compares the given object to
this
object (the object on which the method is called). It gives a generic way to compare objects for equality. It is recommended to override equals(Object obj) method to get our own equality condition on Objects. - getClass() : Returns the class object of
this
object and used to get actual runtime class of the object. It can also be used to get metadata of this class. - finalize() : This method is called just before an object is garbage collected. It is called by the Garbage Collector on an object when garbage collector determines that there are no more references to the object.
- clone() : It returns a new object that is exactly the same as this object.
- String
String is sequence of characters, for e.g. “Hello” is a string of 5 characters. String is an immutable object which means it is constant and can cannot be changed once it has been created. String, Integer, Byte, Short, Float, Double and all other wrapper class’s objects are immutable.There are two ways to create a String in Java- String literal
- Using new keyword
Strings can be created like this: Assigning a String literal to a String instance:
String str1 = “Welcome”;
String str2 = “Welcome”;If the string object already exist in the memory (here ‘Welcome’), compiler does not create a new Object rather it assigns the same old object to the new instance, that means even though we have two string instances above(str1 and str2) compiler only created on string object (having the value “Welcome”) and assigned the same to both the instances. If we want to have two different object with the same string, then for that we would need to create strings using new keyword.
// Compiler would create two different object in memory having the same text String str1 = new String("Welcome"); String str2 = new String("Welcome");
- String comparison can be done in three ways :-
- Using equals() method
- Using == operator
- By CompareTo() method
equals() method compares two strings for equality. It compares the content of the strings. It will return true if string matches, else returns false. == operator compares two object references to check whether they refer to same instance. This also, will return true on successful match. compareTo() method compares values and returns an int which tells if the string compared is less than, equal to or greater than th other string.
- String builder class
StringBuilder class is used to create mutable (modifiable) string. StringBuilder class is same as StringBuffer class except that it is non-synchronized, which means it is not thread safe.StringBuilder Constructors- StringBuilder(), creates an empty StringBuilder and reserves room for 16 characters.
- StringBuilder(int size), create an empty string and takes an integer argument to set capacity of the buffer.
- StringBuilder(String str), create a StringBuilder object and initialize it with string str.
Important methods of StringBuilder class
- public int capacity() returns the current capacity of string bulider object
- public int length() returns the length of the string i.e. total number of characters.
- Wrapper class
Wrapper class in java are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Below table shows the primitive types and their wrapper class in java.Primitive type Wrapper class Constructor Arguments byte Byte byte or String short Short short or String int Integer int or String long Long long or String float Float float, double or String double Double double or String char Character char boolean Boolean boolean or String Why do we need wrapper classes in java?
Actually we can use primitive types in many places but not all. In some cases we can’t use primitive values as is, so wrapper classes are needed/required. For example, if we need to store numbers in a collection, we can’t use primitives because collections such as List, Set, and Map need objects as their elements. In such cases you must use wrapper classes. The main difference between primitive data types and wrapper classes is that the primitive types can be used as raw data for operations such as arithmetic, logical, etc. and wrapper classes acts as data holders for these primitive data types.The primitive data type values will be stored in Stack Memory whereas wrapper class objects (like any other java objects) are stored in Heap Memory.
- BufferedReader
BufferedReader class (java.io.BufferedReader) provides buffering to Reader instances. Buffering can speed up IO quite a bit. Rather than read one character at a time from the network or disk, the BufferedReader reads a larger block at a time. This is typically much faster, especially for disk access and larger data amounts.The Java BufferedReader is similar to the BufferedInputStream but they are not exactly the same. The main difference between BufferedReader and BufferedInputStream is that BufferedReader reads characters (text), whereas the BufferedInputStream reads raw bytes.BufferedReader bufferedReader = new BufferedReader(new FileReader(“c:\\data\\file.txt”));The BufferedReader will read a block of characters from the FileReader (typically into a char array). Each character returned from read() is thus returned from this internal array. When the array is fully read the BufferedReader reads a new block of data into the array etc. The buffer size of BufferedReader can be set by passing argument to the constructor.
Except for adding buffering to Reader instances, a Java BufferedReader behaves pretty much like a Reader. The BufferedReader has one extra method though, the readLine() method. This method can be handy if you need to read input one line at a time.
When you are finished reading characters from the BufferedReader you should remember to close it. Closing a BufferedReader will also close the Reader instance from which the BufferedReader is reading. Closing a BufferedReader is done by calling its close() method - Interfaces
Interface is a pure abstract class. They are syntactically similar to classes, but you cannot create instance of an Interface and their methods are declared without any body. Interface is used to achieve complete abstraction in Java. When you create an interface it defines what a class can do without saying anything about how the class will do it.Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. A class can implement more than one interfaces, however it cannot extend more than one classes. An interface can not implement another interface. It has to extend the other interface if required.interface printable{ void print(); } class InterfaceExample implements printable{ public void print(){System.out.println("Hello"); }
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
Key points to remember about interfaces:
- We can’t instantiate an interface in java.
- Interface provides complete abstraction as none of its methods can have body. On the other hand, abstract class provides partial abstraction as it can have abstract and concrete(methods with body) methods both.
- Class implementing any interface must implement all the methods, otherwise the class should be declared as abstract.
- Interface cannot be declared as private, protected or transient.
- All the interface methods are by default abstract and public.
- Variables declared in interface are public, static and final by default.
- Interface variables must be initialized at the time of declaration otherwise compiler will through an error.
- If there are two or more same methods in two interfaces and a class implements both interfaces, implementation of the method once is enough
- Polymorphism
Polymorphism in java is a concept by which we can perform a single action by different ways. There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. If you overload static method in java, it is the example of compile time polymorphism.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:class A{} class B extends A{} // upcasting A a=new B();
In below example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class Bike{ void run(){System.out.println("running");} } class Splender extends Bike{ void run(){ System.out.println("running safely with 60km"); } public static void main(String args[]){ Bike b = new Splender(); //upcasting b.run(); } }
Compile time polymorphism is nothing but the method overloading in java. In simple terms we can say that a class can have more than one methods with same name but with different number of arguments or different types of arguments or both.
Related Posts :-