Core Java document
Core Java document
https://www.javainterviewpoint.com/java-virtual-machine-
architecture-in-java/
JRE (Java Runtime Environment):
It is the environment provided for the java programs to get executed. It contains a JVM, class
libraries, and other supporting files. It does not contain any development tools such as compiler,
debugger and so on.
Developers use different editions of the Java platform to create Java programs that run on
desktop computers, web browsers, web servers, mobile information devices (such as feature
phones), and embedded devices (such as television set-top boxes).
Java Platform, Standard Edition (Java SE): The Java platform for developing applications,
which are stand-alone programs that run on desktops. Java SE is also used to develop applets,
which are programs that run in web browsers.
Java Platform, Enterprise Edition (Java EE): The Java platform for developing enterprise-
oriented applications and servlets, which are server programs that conform to Java EE’s Servlet
API. Java EE is built on top of Java SE.
Java Platform, Micro Edition (Java ME): The Java platform for developing MIDlets, which
are programs that run on mobile information devices, and Xlets, which are programs that run on
embedded devices.
JEE
Hibernate is a high-performance Object/Relational persistence and query service, which is
licensed under the open source GNU Lesser General Public License (LGPL) and is free to
download. Hibernate not only takes care of the mapping from Java classes to database tables
(and from Java data types to SQL data types), but also provides data query and retrieval
facilities. This tutorial will teach you how to use Hibernate to develop your database based web
applications in simple and easy steps.
Basic Important
Here every class is child of object class it has some methods so its methods should be
overridden
Main method is void because after the execution of the method the program execution ends
Here there is nothing to return in the method because method need not to expect any
return value at the end of the excecution.
Variables:
package VariablesMethods;
//****************IMPORTANT---------------------
//These variables should be inside the class and outside method I mean shouldn't be inside the method
int j =19;
//
//*******************Static variables
//***********************local variables
//variables which are declared inside the block are called local variables
//these variables cannot be static because scope is only inside the block
//example
//Parameters
//System.out.println(vm.j);
System.out.println();
int a = vm.j;
System.out.println(a);
System.out.println();
System.out.println(VariablesMethods.i);
System.out.println();
System.out.println(new VariablesMethods().i);
String:
package demoStrings;
import java.util.Arrays;
// Basically we can not assign values for the class without creating the object
//but incase of String we can assign and call directly this is different behaviour apart from all
things so it is called literal.
//1
//String s1 ="abhi";
//2
//Concate String
// System.out.println(s1);
// Here if we see both strings are equal then we will get error Because
// The Strings that created directly will store in the memory called string pool and
// The Strings created using object will store in the object memory so both are not same
// Basically when we directly compare the strings the java will compare strings memory
// So lets discuss their is two types of memory in the strings when we create object in java using
string that will be stored in heap memory even the strings contain same data both strings are not equal
//but coming to the string pool if the both strings contain the same data then the strings are equal
//Actually when we use the == the string address are compared but when we use the (.equals) it
compares the data
// if we want to ignore the case of the both data then we will go with the .equalsIgnoreCase
//The main thing is to know the return type of the methods in the strings in java so let us write
/*
* .equals
* .equalsIgnoreCase
* .contains
* .startsWith
* .endsWith
* .isEmpty
* .isBlank
*/
String s1 = "Abhi";
String s2 = "AbHi";
String s3 = "ashok";
//boolean b= false;
/*
*{
* System.out.println("false"); System.out.println();
* if(s1.equalsIgnoreCase(s2)) { System.out.println("true"); }
* if(s5.contains("Want")) { System.out.println(); }
*/
boolean a = s1.equals(s2);
System.out.println(a);
boolean b = s1.equalsIgnoreCase(s2);
System.out.println(b);
// Here equals ignore compare only data does not conclude either it is upper or lower case
System.out.println();
boolean c = s5.contains("want");
System.out.println(c);
//Here it checks the sequence of characters in the string if it contains then it says true if not it says
false
System.out.println();
boolean d = s5.startsWith("I want");// here we can enter either one character or sequence
System.out.println(d);
//Here it checks whether string is starting with the given char or not returns true if it is true
System.out.println();
boolean e = s5.endsWith("hi");
System.out.println(e);
// Here it checks whether string ends with ther given char return true if it ends
System.out.println();
boolean f = s6.isEmpty();
System.out.println(f);
//Here This method return4d true if the string is declareed but it has zero length
System.out.println();
boolean g = s6.isBlank();
System.out.println(g);
// Here the method returns true if the string has atleast some length but it is with empty spaces
System.out.println();
int h = s1.compareTo(s2);
System.out.println(h);
// we have done with the boolean methods now let us go with char methods
/*
* .charAt()
* .toCharArray()
*/
System.out.println();
char aa = s1.charAt(3);
System.out.println(aa);
// Here charAt method returns the character at the given index it is the character return type
System.out.println();
char[] bb = s2.toCharArray();
System.out.println(Arrays.toString(bb));
/*
* .compareTo
* .compareToIgnoreCase
* .indexOf
* .lastIndexOf
*
* .compareTo
* if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0
*/
System.out.println();
int cc = s1.compareTo(s2);
System.out.println(cc);
System.out.println();
int dd = s1.compareToIgnoreCase(s2);
System.out.println(dd);
//here it ignores case
System.out.println();
int ee = s5.indexOf('n');
System.out.println(ee);
//here it returns the first occurance of char in string
System.out.println();
int ff = s5.lastIndexOf("e");
System.out.println(ff);
//Here returns the last occurance of the string in java
System.out.println();
int gg = s5.length();
System.out.println(gg);
// Here it prints the length of the string
System.out.println();
//We have done with the integer methods lets go with the string methods
/*
* .toUpperCase
* .ToLowerCase
* .replace
* .replaceAll
* .split
* .trim
*/
System.out.println();
String i = s5.toUpperCase();
System.out.println(i);
// Here alll word are converted into the uppercase
System.out.println();
String j = s5.toLowerCase();
System.out.println(j);
//Here all converts into the lower case
System.out.println();
String k = s5.trim();
System.out.println(k);
//these removes the traling white spaces at first and last of the string
System.out.println();
String[] l = s5.split(" ");
System.out.println(Arrays.toString(l));
};
Variables:
Local variables declared inside the class (Scope is within a block)
Non static declared outside the method and inside the class (Scope is within a class like
object level)
Static variable declared same as a non-static variable
//We know that the class is the blueprint of the object which contains the methods states and behavior
//so, to execute anything I mean any class in the java memory should be allocated to the java
//We all know that the execution in the starts from the main class
//As I have said to execute main class also the memory should be allocated to the main class then only it is
executed
//we know object creation is way to allocate memory for the any class
//********************Just Static is another way of memory allocation in java without creation of object
//----------------------IMPORTANT------------------------------
//Java File (Create)---> .ClassFile (To Run/Execute)---> ClassLoader -->(Heap Memory and Method
Memory) Allocates memory in any one accordingly --->Execution engine executes the code
//Anything that is created using new keyword allocated in heap memory for each object each memory block
is created
//class loader identifies all static variables methods and creates the only one memory block for each class
//from these method memory execution engine access, the methods and variables and executes program
//As in method area only one block and one copy it is called shared memory
//----------------------------------------------------------------------------------------------------
package staticNonstatic;
import java.util.Random;
int a;
//Here I am creating three objects in heap memory using the random class
//obj 1
//obj2
//obj3
System.out.println(t1.a);
System.out.println(t2.a);
System.out.println(t3.a);
//These created three different numbers because each memory block is created for each object
right
Output:
-676908779
-821282432
-1769489197
package staticNonstatic;
import java.util.Random;
static int a;
//Here we get same number because only one memory block is created and in block only one copy
exists so
//so same variable overridden when we create each random variable using random class
//obj 1
//obj2
//obj3
System.out.println(t1.a);
System.out.println(t2.a);
System.out.println(t3.a);
}
Output:
-1512316220
-1512316220
-1512316220
Class 3: Some modifications in previous class
package staticNonstatic;
import java.util.Random;
static int b;
//Here we get same number because only one memory block is created and in block only one copy
exists so
//so same variable overriden when we create each random variable using random class
/*
*/
//As we create static variable itself creates memory in method memory no need to create object for
it we can call it using the class name
System.out.println(b);
System.out.println(b);
Output:
966137311
966137311
• KEY
• To execute any class (contains variables & methods) memory
should be allocated to class using object or static keyword
Data Hiding:
Basically we use getter and setters to give access to private variables in class.
If you want to give read and write access to administrative, then it is possible to getters
and setters.
Encapsulation:
▪ Binding data members and methods into single unit. (Purpose is security)
➢ All variables should have a private access
➢ Each private a variable should be manipulated by getters and setters
➢ Imp java.io.serialiazable inter
Abstraction:
▪ Don’t implement allow us to use services. (Purpose is Security)
➢ ATM is very good example for that we can use our services.
• Rules
➢ It can be implemented through abstract classes
➢ Before that we should know about the abstract methods.
➢ To declare abstract method, we should have abstract classes or interface.
➢ We cannot create object for the abstract class. (This cannot be instantiated) Q?
Because abstract class doesn’t have and behavior and implementation compiler says
where should I go.
➢ Basically, abstracted methods are overridden to use by child class.
➢ Least child class should not be abstract class in order to be used.
➢ Variable values can be changed.
Inheritance
➢ Reusing
➢ To achieve inheritance, we will use extends in java
➢ There are 5 types of inheritance.
Casting
➢ Upcasting
➢ Down casting
❖ Referring the child object with the parent ref in java so that we can play with
Interface
Interface class {
// allows only abstract methods
}
If we declare variables by default public variable and static and final value be assigned.
➢ Interface to class use Implements.
➢ Least child class should not be abstract.
➢ Main thing is multiple inheritance is possible by the using the interfaces.
OOPS
What is oops?
OOP is object-oriented programming language. (Everything should be treated as object)
Principals of oops?
Inheritance
Encapsulation
Polymorphism
Abstraction
Is java 100 percent object-oriented language?
No, Because of non-primitive types in in java we are not declaring them In the form of
object and static also this violates pure oops. In oops everything should be in the form of
object.
Is java object oriented or object-based language?
It is object oriented because languages that can inherit properties are called object oriented
which cant are object based.
Inheritance
What is inheritance?
It is mechanism of one class acquires the all the properties and behaviors of another class
with the specific relationship.
Code reusability.
Java only supports multi-level inheritance and multiple inheritance in classes is not
supported in java but in interfaces it is supported.
There is up casting and down casting in inheritance.
➢ Upcasting
❖ Referring the child object with the parent ref in java so that we can play with
Access modifiers
Public- Other classes, projects, and packages and in subclass (inherited classes).
Class can never be private (Because we can’t get access to it from the anywhere)
Private- that can be accessed only with in the same class.
Default – without no modifier it is called default (class and constructor can be default)
(with in same class and same package so it is called package private).
Protected same as default but it can be accessed in subclasses of other packages.
Interface
Interface is the blueprint of a class.
Interface has only definition no implementation.
Any interface that can be implemented only through the class.
Example interface:
public interface Laptop {
//before java 8 interface can only have the abstract classes means classes without implementation
display();
System.out.println("Possible only from java 8");
display();
//Here we got a issue that is code reusability because what if two or more methods have a same code
duplicate code occurs
// so they came with an solution that is private methods because this methods are accessible only in the
class and reduce code duplicity
//here we are good because by implementation in interface no other implementers will be affected because
this are soft rules if they don’t have also
//it is good but if they want to implement in their class they need to override it from interface
}
Class ex
package Interface;
@Override
System.out.println("Lenova Copy");
@Override
@Override
System.out.println("Lenova Cut");
}
@Override
System.out.println("Lenova Keyboard");
};
}
}
Driver class
package Interface;
ln.cut();
ln.cut();
ln.past();
System.out.println();
dl.copy();
dl.cut();
dl.past();
System.out.println();
ap.copy();
ap.cut();
ap.past();
///Up to here like untill java 7 interfces can have have only abstract classes but after java 8
//interface can also have the implementations but that can be possible only with default and static
key words
ln.Security();
ln.display();
}
Abstract Classes :
// we know that the interface is implemented by class then what is the challenge
//while implementing interface by normal class all methods should be overridden by class this is the rule
//so what if i know only few methods in the interface and i want to implement that interface
//Abstract classes can have the one or more abstract methods that can be decided by developer which
methods he know which methods he dont
//Abstract classes are inherited by another abstract class by situation then by class if all methods are
implemented
//Abstract classes are imp when java 8 came into game because their is no implementation in interface
before java 8
//Know I want to implement few methods in interface so i will use abstrat class
Abstract Class1:
package AbstractClass;
Abstract class2:
package AbstractClass;
@Override
@Override
Class that implements all methods of interface by using some abstract methods:
package AbstractClass;
Driver class:
package AbstractClass;
Polymorphism:
Ability of object to take on many forms
We have two types of polymorphism
1)compile time polymorphism :Static polymorphism & early binding
2)runtime polymorphism: dynamic polymorphism
Go through above to understand breifly
package Ploymorphism;
//Here the compile time polymorphism is achieved during the compilation time
//method overloading is have same method with different parameters or with different no of
parameters or with different datatypes
//Now lets see same data type with different variable name
/*
* public void add(int d, int f)
* { System.out.println(); }
*/
//This method shows error because when compiler looks for it it see same data types variables doesnt
matter here
//In overloading it should not have the same data types in same order while overloading
//You see this works because compiler looks for data type of parameter
System.out.println("Same as above");
//You see this works because compiler looks for data type of parameter
//@Override annotation is not mandatory but it is advised to used because it checks the overidden method
syntax
//Syntax is same as the parent class if not this annotation will throw error
ct.add();
ct.add(2.3);
ct.add(2);
ct.add(1.2, 2.3);
ct.add(4.5, 3);
ct.add(4, 4.4);
ct.add(0, 0);
ct.add(0, 0, 0);
Exception Handling:
package exceptionHandling;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//so here we got the exception at line 13 till line 13 execution is perfect
//The main thing we have to absorb is the programme is terminated after the te exception occured
//
//
int a =9;
int b =0;
//Here division is a event any event that stops the programme execution is called exception
System.out.println(result);
//compile-time exceptions
//runtime-exceptions
/*
* Java gives
* try
* catch
* finally
*stacktrace
*Exception name
*exception message
*Always deal exceptions from the last to first then it will be meaningfull
*try: The event which is causing the exception should be placed in the try block
*catch: then catch block is to catch the exception and show some message in the console without
stopping programme execution
*/
//we know
try {
result = a/b;
catch(ArithmeticException ae) {
System.out.println(ae.toString());
//Finally
finally {
System.out.println("Finally block");
//throws
System.out.println(fis);
Try{
Try{
}
catch(){
}catch(){
}
//After the exception here program exceution stops and throws the exception it
catch block
//so B is not printed
System.out.print("B");
}
catch(ArithmeticException ex)
{
//comes here and prints C
System.out.print("C");
}
catch(Exception ex)
{
//there is no further excution of program and no exception it not print D
System.out.print("D");
}
System.out.print("E");
}
File Handling :
package com.File.Handling;
import java.io.File;
import java.io.IOException;
//First we have to give the path where the file is or if we want to create file where
we want to create file
//Their are two types of paths in the Java
/*
* Full path
* relative path
*/
//Full path in the sense we have to give full path of the file
//Relative path in the sense just if you are working in some directory and you
want some file just type dot. then you will se all the files
/*
* And there is backslash and forwardslash that means their is no singleslash java
by default it takes double slash instead of the single slash
* these slashes are nothing but the separators of the path
* if you dont like double slash just change it to the backward slash both are same
*
*/
//By the File class just we have created a object if we want to perform operations
we should use that
//System.out.println(f.delete());
//Here we deleted a file using delete method
//System.out.println(f.createNewFile());
//Again we are creating
//System.out.println(f.exists());
//This method says does the file exist in the folder or not
/*
* if(f.exists()) { f.delete(); System.out.println(f.createNewFile()); }
*/
//If file exists then it deletes and creates the new one
/*
* System.out.println(f.canWrite());
*
* f.setWritable(true); System.out.println(f.canWrite());
*/