Core Java Basics

What is platform?

Platform:Platform is the combination of operating system and processor, we can also say platform is a software and hardware combination in which we can run our application programs. For example Windows 7 with combination Intel processor can be called as one platform.

Platform Dependent language:

If any programming language compiled code is generated based on its underlying platform, then that compiled code can't be run on other platform. For instance if you compile 'C' code in windows platform, you can only run this in windows platform, but you can't run in the other platforms, if you want to run it on other platforms, then you have to recompile it on target platform where you want to run the program.

Plat form independent

Platform Independent:

If any programming language compiled code (.class) in one platform can be run on other platforms, then it is called platform independent.
Java has released with the slogan “ write once run anywhere”(i.e) is nothing but the code which is written in a particular platform can be run on any other platform.

Plat form Independent

Byte code:

  • It's a compiled code of java source code.
  • It is called .class file.
  • It is not a machine code (binary code), it is an intermediate byte code generated by java compiler.
  • It can be understandable by JVM only
  • It starts with magic number called 'CAFEBABE'

Why Java:

The following are the special features of java that made it a unique language in the programming world.

Please read 101 reasons why java :-

Platform Independent And Portable:

The most unique feature of Java over other languages is its portability. When a Java file is compiled, the compiler generates an executable file called .class file. This .class file contains byte code . The byte code generated on one platform can be executed on any other platform, it makes, the java as portable language.


Java is a robust language. In general robust means flexible and very strong in nature. Java is robust because it never hangs the system. It provides many safeguards to ensure reliable code. Data types are strictly checked at both compile time and run time. Memory is implicitly managed. Java does not have calloc (), malloc () and size of functions. Java language watches the program’s execution and allocates sufficient memory needed by the program.. It has automatic memory management.

Multithreaded And Interactive:

Handling multiple tasks at a time simultaneously is called multithreading. Java enables multithreaded programs. A process can be divided into a number of threads and each thread can be given a different task to attempt. Developing multithreaded programs in Java is quite simple due to inbuilt classes. Java can lock the resources to avoide data inconsistency with the concept called synchronization.


Java is simple because of which contains rich and high API (application program interface)libraries while implementing the applications. for example: java does not use the concepts which are pointers, preprocessor header files, ”go to” statement and eliminates operator overloading and multiple inheritance.

Memory Management:

Memory is implicitly managed. Java does not support calloc () , malloc() functions. Java language watches the program execution and allocates sufficient memory needed by the program. Java includes another unique concept called “Garbage collection” it deallocates the memory for the objects that are not used in the program.

Safe And Secure:

Java is called as strongly typed language i.e., one type is cannot be assigned to another type. Java is secured by the byte code.

J2SDK (Java 2 Software Development Kit):-

Which contains the develop environment. This is used for application development.

JRE (java runtime environment):-
  • Where we can run java applications.
  • Independent installation is possible and multiple installations possible
  • JRE = API +runtime libraries + JVM.
  • We can install multiple JRE’s at a time in same platform and same system
JVM (Java virtual machine) does:
  1. Conversion to underlying machine it.
  2. will make java as a platform, independent language.
  3. Because of independent from underlying platform it is called as virtual machine.
  4. Memory management.
  5. Instance of JRE is called as JVM.
  6. JVM is a driving vehicle for all other languages.
  7. JVM is a specification (It has ‘n’ no of implementations).
  8. Multiple JVM’s can run at-a-time.
JVM runs n number of programs at a time


  • Identifier is nothing but name of the variable.
  • Identifiers are utilized to denote the classes, methods, variables and labels.
  • Identifiers are case sensitive.
  • Identifiers are composed of a process of characters, where each character in an identifier must be a letter or digit.
  • The identifier doesn’t contain any length restriction.

Identifiers Must Be Follow The Rules:-

  • All the identifiers are started with small letters & next word starting letter is capital letter or it can be started with currency letter [$,€ ] or connecting letter [ _ ].
  • Ex:String studentName;
  • Methods are also follow same rule.

    Package name should be lowercase letters only.
  • Constant field name must be in capital letters
  • Ex:double PI = 3.14;
  • Class name must be started with capital letter and it uses “ CAMEL CASE ”.
public class StudentEnrollment{ }
Correct Wrong nam3e1 123 $currency 1abc inst_name a#abc

JavaBeans Standards:-

JavaBeans are Java classes that have properties. Since they are private, the only way they can be accessed from outside of their class is through methods in the class. The methods which change a property’s value are called “setter methods” and the methods that retrieve a property value iscalled “getter methods”.
The following are the JavaBeans:

  • If the property is not a boolean ,the getter method’s prefix must be “get”. for example , getSize() is a valid Java Bean getter name for a property named “size”.
  • If the property is a boolean , the getter method’s prefix is either “get or is” . for ex: getStopped() or isStopped() are both valid Java Bean names for a boolean property.
  • The setter method’s prefix must be set. For ex: setSize() is the valid JavaBeans name for a property named size.
  • The signature of setter method must be marked as public, with a void return type and an argument that represents the property type.
  • The signature of getter method must be marked as public, takes no arguments, and have a return type that matches the argument type of the setter method for that property.

Class :

A class is a blueprint for objects. The class defines variables, methods and objects. The objects manipulate data through methods. These methods constitute a set of operations. Classes are the fundamental units in an object-oriented programming. We use a class to create objects(instances). Each instances carries its own data. That is, data belonging to one object, if changed, does not affect the data belonging to other objects.

public class FirstProgram { int count; // integer variable/field public void display( ) {// method implementation(display() – method name) count++; } }

Object :

An object is an instance of a class. An object is known by a name.

Object State:-

  1. Collection of all property values of an object at a particular time.
  2. Object state can change when we change the property.
  3. Ex:Age of the student after 1 year
  4. Instance variables refers to the memory location of an object.
class Student { private int age; private String name; private int noc = 1; public String getName() { return name; } public void setName(String name) { = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class S { public static void main(String args[]) { Student s = new Student(); s.setName("geek"); s.setAge(20); // after the above statement given values are stored in memory } }
New Object creation
  1. When the new object is created, immediately memory for that object is created in heap memory.
  2. ‘s’ is reference variable that hold address of an object (i.e. 1000 from diagram).

The difference between “class and object”

Class Object
1.Class is a way of binding the data and Associated method in a single unit. 1.class variable is known as an object.
2. Whenever we start executing a JAVA program, the class will be loaded into main memory with the help of class loader subsystem(a part of JVM)only once. 2. Whenever we start executing a JAVA program, the class will be loaded into main memory with the help of class loader subsystem(a part of JVM)only once. 2.After we are loading the required classes into the main memory,instances can be created in n number.
3.When the class is defined there is no memory space for data members of a class. 3.When an object is created we get the memory space for data members of the class.

Declare Class Members:

Access Modifiers:

Permitting one class to access another class of a different package is called access control. Access control can be used to prevent misuse of classes. The access specifier determines how a member can be accessed. The access specifiers provide different levels of protection. All access specifiers are keywords of Java.

Java supports 4 access specifiers:

  • Public
  • Protected
  • Private
  • Default(not specified at all)

If a member of a class is public, it could be accessed

  1. By the present classes of the same package without any restriction.
  2. By the classes of other packages also without any restriction.
  3. i.e., any class from any package can access. Public gives minimum permission of all access specifiers without any restriction.

public int num; public void display() { } public abstract void add();
Public class importance
  1. By utilizing the classes of the same package without any restriction.
  2. By the classes of the other packages if they inherit the class only.
  3. i.e., a protected member can be accessed which allows the classes of the same package without any restriction as if it is public. But, a restriction comes for the classes of other packages only; they must inherit the class.

protected int num; protected void display() { } protected abstract void add ();
Protected class importance

Actually there is no default specifier (but, default is a keyword used with switch statement). If we omit the specifier, and then JVM assumes it as default.

If a member of class is default,

  1. This access can be done by the classes of the same package without any restriction (as if public).
  2. The classes of other packages cannot access (even if they extend).
  3. Internet
int num; void display(){ } abstract void add();
Default class importance

If a member of a class is private, it must be accessed by the objects of the same class only. i.e., even the objects of the classes of the same package cannot access. That is, private means, purely private to the class only. Private access specifier gives less accessibility when compared to other access specifiers.

Private class importances

Accessibility of access specifiers:

Accessibility of access specifiers

Non Access Modifiers:

List of non access modifiers:

  1. final
  2. abstract
  3. static
  4. transient
  5. volatile
  6. strictfp
  7. native
  8. synchronized

final is a keyword of Java which generically means, cannot be changed once created, that is, it cannot be modified later in the program. Final behaves very differently when called with variables, methods and classes. The final keyword when declared with variables, methods and classes specifically means:

  1. A final variable is that it cannot be reassigned once it has been initialized.
  2. A final method cannot be overridden.
  3. A final class cannot be extended.

Following 3 programs explain the usage of final keyword:

1. Using final with variables:-
public class FinalVariable { public static void main(String[] args) { int x = 10; System.out.println(x); x = 20; System.out.println(x); final int y = 30; System.out.println(y); // y = 40; as y cannot change } }

In the above program, x is not declared as a final and reassigned a value later. But, y is declared final and for this reason could not be reassigned later.

2. Using final keyword with methods:-

A final method cannot be overridden.

public class FinalMethod { public void display() { System.out.println("hello"); } public final void show() { System.out.println("hw r u"); } } public class Test extends FinalMethod { @Override public void display() { System.out.println("hello1"); } public static void main(String[] args) { FinalMethod fm = new FinalMethod(); fm.display();; }

In the above program the final method show() is not overridden as it is declared as final. If overridden, it is a compilation error. But still subclass can call it by inheritance.

3. Using final keyword with classes:-

A final class cannot be extended or sub classed, i.e., it is not fit for inheritance. But still any other program can call the methods of final class by composition.

final class FinalClass { public final void show() { System.out.println("hw r u"); } } public class Test1 { public static void main(String[] args) { FinalClass fc = new FinalClass();; } }

In the above program, FinalClass is decalred as a final and for this reason class Test1 cannot extend it. But, still can use the final class methods by composition.

  1. IEEE standards gives accuracy for floating operations.
  2. Java won’t support IEEE standards.
  3. In Java floating operations does not have accuracy.
  4. Using strictfp we can achieve IEEE standards in java.
  5. By default they are not enabled due to performance (goes down) So, We can use this when needed.
  6. We can give strictfp for class and methods.
  • It is a keyword. It is using on the classes and methods but not variables.
  • Abstract class is an incomplete class.
  • We cannot initiate abstract class directly. This class is used for only subclasses.
  • We can’t create objects for abstract class.
  • This class can includes “zero abstract methods”.
  • But if a class contains one abstract method then that class should be declared as abstract class.
  • Final abstract cannot be used together.
  • Abstract method should be implemented in its child class otherwise give that class as abstract this is mandatory.
  • If a class extends abstract class it should override abstract methods from parent class.
  • Abstract classes not contain abstract method then it is also valid.
abstract class A { public abstract void m(); // abstract method } public abstract class B extends A { public void m() { System.out.println("hi"); // if this method is not overridden then } }


  • An interface is a class containing a group of constants and method declarations that do not provide implementation. It is used for defining the class contract.
  • It is 100% incomplete class.
  • An interface contains all abstract methods. In essence, an interface allows us to specify that a class must what to do, but not how to do.
  • One class can implement any number of interfaces. We must use implements keyword instead ofextends. This is the way of multiple inheritance, which java supports.
  • All the methods in an interface must be abstract and public .
  • All the fields declared in the interface must be public ,static ,final .
  • “public” is to allow the subclass to access the variables as sub class may come from a different package.
  • “final” is for not to allow the subclass to change the value of its variables.
  • “static” is to allow the subclass to call the variable without the help of an object.
  • Class can implements multiple interfaces but it cannot extends multiple classes.
interface Animal1 { public abstract void moves(); } public class InterfaceDemo implements Animal1 { public void moves() { System.out.println("animals move on land"); } } public class InterfaceMain { public static void main(String[] args) { InterfaceDemo id = new InterfaceDemo(); id.moves(); } }


A class may contain constructor apart from methods. Constructor declarations look like method declarations-except that they use the name of the class and have no return type. That is, a constructor looks like method but without a return type. Moreover, the name of the constructor and class name must be same. The advantage of constructors is that it is called automatically when an object is created. We generally use the constructors to initialize the variables, setting background and foreground colors etc., constructor is used to initialize the initial state of the object.

Constructor cannot be inherited by subclasses, hence they cannot be overridden however they can be overloaded. Every class will contain a default constructor. (i.e., if we did not declare any constructor in the class then default constructor will be created automatically).


The following syntax shows the default constructor.
public DefaultConstructor () { //program for default constructor public DefaultConstructor() { System.out.println(“from default constructor”); } public static void main (String args[]) { DefaultConstructor d1= new DefaultConstructor(); }

In the above program, DefaultConstructor () is a constructor of DefaultConstructor class. It is called implicitly when the object d1 is created. Constructors also can have parameters. A constructor which does not have parameters is called as default constructor as it is created by the system, when the programmer does not provide one himself.

Constructor Overloading:

Like methods constructors can also be overloaded. Appropriate constructor is called as per the parameters we pass at the time of object creation. In the following program, the constructor Rectangle () is overloaded 2 times. Compiler differentiates which a constructor is to be called depending on the number of parameters and their sequence of data types.

public class Rectangle { public Rectangle() { System.out.println("from default constructor"); } public Rectangle(int x) { System.out.println("area with one parameter" + x * x); } public static void main(String[] args) { System.out.println("overloading constructors"); Rectangle rect1 = new Rectangle(); Rectangle rect2 = new Rectangle(5); } }


this() is allows us to invoke one constructor from another within the same class it is depending upon the parameters which we pass.

Constructor Chaining:

Constructor chaining occurs through the use of inheritance. A subclass constructor method’s first and most task is to invoke its super class constructor method. This declares us that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.

There could be any number of classes in an inheritance chain. In java each and every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class which is below will given as the chain for which winds back down to the original subclass. This phenomenon is called to be constructor chaining.

In the below code the Mammal class inherits the Animal class:

inheitance concept

When an instance of the mammal class is created the first action of this constructor is calling super class constructor i.e calling super(). In this case control goes to the Animal constructor.

Thumb rule is , If you want to create a instance for an object , first it should call parent class constructor before executing its constructor.


A variable is a container that can holds values that are used in a Java program. To be able to use as variable it needs to declared first before going to use. Declaring variables is normally the first and most thing that happens in every program which is following with java conventions.

Types of Variabls:

In java we will use two types of data members and variables. They are nothing but

  1. static Variables
  2. Non-static Variables ( instance Variables)

How to declare a Variable:-

Java is highly, strongly typed language. It will declares us that every variable must have a data type associated with it.

Ex:- int noOfDays;

In the above example , a variable called “noOfDays” has been declared with a data type int . The semicolon(;) tells the java compiler that the declaration is complete.

How to initialize a variable:

As we before going to use a variable it must be given an initial value this is called initializing the variable.

If we try to use a variable without first intializing its value:

public class Variable1 { public static void main(String[] args) { int noOfDays; noOfDays = noOfDays + 10; System.out.println(noOfDays); } }

In the above example gives “compile time error”. Variable noOfDays might not have been initialized.

public class Variable1 { public static void main(String[] args) { int noOfDays=7; noOfDays = noOfDays + 10; System.out.println(noOfDays); } }

In the above example it gives “17”

Reserved Keywords:-

There are some keywords that you cannot use as object or variable names in a java program. These words are known as “Reserved"keywords; they are key Words that are already used by the syntax of the Java programming language.

Following are the java keywords:

Reserved keywords in java


A constant is a variable whose values cannot change once it has been assigned.

In java the final keyword will be used with primitive data types and immutable objects to create constants.

final int DAYS_IN_JANUARY=31; final WEIGHT = 40;

Define a constant value and use it:

  • Using final keyword to declare a variable.
  • The final keyword specifies that the values of a variable is final and cannot be changed.
  • It is convention in java to write constants in uppercase letters.

// program for declaring constant variables

public class Constant { public static void main(String[] args) { final int DAYS_IN_JANUARY = 31; final double PI = 3.14; System.out.println(DAYS_IN_JANUARY); System.out.println(PI); } }



Instance Members:

  1. Instance fields are loaded into memory or memory will be allocated for them only after instance is created for a class.
  2. Each instance has their own values they do not share.
  3. If we want to create an instance first the program should be in memory.

    Student s= new Student();

  4. Compiler allocates memory for variables after creating instance.
  5. Instance members data won’t be shared across instances.
class Student { private int age; private String name; public String getName() { return name; } public void setName(String name) { = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class S { public static void main(String args[]) { Student s = new Student(); s.setName("geek"); s.setAge(20); // after the above statement given values are stored in memory } }


s.setage(20); // after this statement given values are stored in memory

Allocation of Memeory

Static Members:

  1. While loading the class itself it creates memory for variables.
  2. Non- static fields cannot be used in static methods.
  3. Non- static can access both static and non-static members.
  4. For every instance variable created the noc value changes in non-heap memory
public class Student { private int age; private String name; public static int count;// static variable public static int getCount{ return count; } public int getAge() { return age; } publc void setAge(int age){ this.age=age; }} public class StaticTest { public static void main(String args[]){ Student s= new Student (); Student s1= new Student (); s.count++; // But it’s a bad practice, here instance variable is using to access static variable, instead we should use class to access i.e Student.noc++. System.out.println(s1.count); //prints 1 here } }

‘count’ is a static variable and it will be loaded into memory when class is loaded, so static variables are ready to use when is class is loaded.

In this example when class ‘Student’ is loaded, memory will be created for ‘count’ and value will be assigned ‘0’.

When StaticTest is executed , we are creating two instances of Student class, both those instances share ‘count’ variable as it’s a static member. When we increment ‘count’ using variable ‘s’, ‘count’ will change to 1, and when ‘s1’ access ‘count’, it gets value as 1 as its shared variable, even though ‘s1’ is not incremented ‘count’.

Other example for static how to use non-static variables in static method.

public class StaticExample { int i; // non-static variable static int j; // static variable public static void main(String args[]) { System.out.println(i); // can’t use as it is nonstatic System.out.println(j); // works as it is static } }

We should not use non static members in static methods.

  • We have to create instance in order to access i.
  • As j is loaded with class and has memory for j (static) variable.
  • After creating instance we can access non-static members in static methods.

Static vs Instance:


  • Instance fields are loaded into memory or memory will be allocated for them only after instance is created for a class.
  • Each instance has their own values they do not share.
  • If we want to create an instance first the program should be in memory.

    Student s = new Student();

  • Memory for variables will allotted only after creating instance.
HTML Comment Box is loading comments...