Core Java Basics
Core Java Basics
Basics:
There are so many companies who are manufacturing the processors, some of
the company names are INTEL, SUN, AMD and etc. the processors are responsible to
execute the programs. We have developed a ‘C’ program to add the numbers. The ‘C’
program developed high level language.
Ex:
void main(){
int a = 10;
int b = 20;
a + b = a;
}
If we would like to run this program. We need to compile the program. It is the
responsibility of compiler to convert High level language into machine level language.
The ‘C’ compiler generates an .exe file. Inside the exe file the ‘C’ compiler has placed
the processor dependent instructions. This ‘C’ compiler is installed on INTEL processor.
We have taken the same .exe file and try to run it on sun processor, but we are failed to
execute the program. This is because sun processor cannot execute the “INTEL
PROCESSOR” instructions.
If we got the requirement to run the ‘C’ program on all the processors we need to
recompile the same program on different processor.
When develop a JAVA program to add the numbers we can not run the directly on any
computer.
2
By taking the help of JAVA compiler we have converted .java programming to .class file.
If we would like to run the java application we need to give .class file as Input to JVM.
It is the responsibility of JVM to convert java instructions into processor dependent
instructions.
To see what is available in a .class file, we can take the help of java profiler command.
When we use the javap command we have observe the following code in Add.class.
If we want to see all the instructions also we have to use an option “-c”
Ex: Javap –c Add
We can invoke (call) the JVM by using the command java. When we invoke the
JVM it searches for appropriate .class file. If the class file is available Class Loader
loads the class into JVM’s memory. If the class is not available JVM throws an
Exception java.lang.NoclassDefFoundError: sub.
After the class is loaded JVM checks for main method. If it is available JVM starts the
execution from main method. If the main method is not available JVM throws an
Exception NoSuchMethodFoundError: main
3
When the complier will add the constructor?
When the programmer provides constructor in the java programmer the compiler will
not add default constructor other wise compiler will Add default constructor.
Ex: public class Add{
public Add(){
}
} // save Add.java
When the compiler will add the code to inherit properties of java.lang.object?
When the class is not Inheritance the properties of any other class then the compiler
will try to inherit the properties of java.lang.object class
In the following code the compiler try’s to inherit the properties of java.lang.object
Ex: public class Cone { } // save Cone.java
In the following example java compiler will not inherit the properties of java.lang.object
Ex: Public class Ctwo extends Cone { } //save Ctwo.java
We can compile and run the java programs using the following commands :
Compile : javac –g programname.java
Run : java –Djava.compiler=NONE programname (or)
java –Djava.compiler=none programname (or)
java –Djava.compiler programname
When ever we call the JVM , operating system loads the JVM program into RAM. Now
the operating system allocates default memory (256mb) to JVM in a RAM.
After the program execute is finished, memory will be cleared from the RAM.
As start of the JVM we have a program class loader. It is the responsibility of a class
loader to load the class into JVM’s memory.
When ever JVM’s starts the execution of a method it allocates two memory blocks.
They are 1) Stack and 2) Method area
Stack is mainly used to perform any operations. Stack is a temporary memory
location. If we want to the data permanently, We store the data in method area.
JVM’s removes stack, method area after finishing the execution of method.
This is the Java Instructions for “Add.class” , Command is javap –c add
public class Add extends java.lang.object{
public Add();
code:
4
0: aload-0
1: invoke special #1;//Method java/lang/object.”<init>”()u
4: return
public static void main(java.lang.String[]);
code:
0: bipush 10
2: istore-1
3: bipush 20
5: istore-2
6: iload-1
7: iload-2
8: iadd
9: istore-1
10: return
}
The variables which are declared in side a method are called as local variables.
The method parameters are also called as local variables.
Ex:
public class One{
int a;
//Instance Variables
int b; Static Variables
static int aa;
public void methodOne(int d, int e){
int x;
//Local Variables
int y;
}
}
5
We have developed a class Cone with two Instance Variables as shown below.
Ex: public class Cone {
int a;
int b;
} //Cone.java
We have developed a reusable components Cone. Any body can use it by creating
object to Cone class.
Ex: Public class MyApp {
Public static void main(String[] args) {
Cone c1 = new Cone();
}
} // MyApp.java
When we execute the above java program it will divided creation of object line into two
parts, they are
Cone c1; part1 (c1 = Reference Variable)
c1 = new Cone(); part2 (c1 create object to Cone class)
When the part1 line is executed JVM allocates memory for c1 Reference Variable
inside the Stack (c1 Reference (local variable)).
1. JVM checks for Cone.class and try to load Cone.class files into JVM’s memory.
2. Now JVM opens Cone.class and check for no of Instance variables in a Cone.class
3. Now the JVM calculates the required memory for the Instance variables.
4. Now the JVM’s checks where the suficiant free space is available to allocated the
memory for instance variables in JVM’s Heap memory.
5. After the memory is allocate , JVM place the starting address of object into c1
Reference variable.
Note:
As the c1 variable is hold the address of object of Cone,then we call c1 as Reference
variable.
6
When ever we create object or Instance for ever copy it contains one copy of variables.
In java all the local variable must be initializing with some values, without initialize the
local variables when we try to compilation a program we get a compilation error.
Ex: Public class MyApp{
Public static void main(String[] args){
int a;
System.out.println(a);
}
} // MyApp.java
All the instance variables are initializing with default values when the object is
created.
7
}
} // MyApp.java
It is always recommended to create object to sub class. By using sub class object we can
access the methods of that class as well as super class of that class.
8
From the above diagram we have understand that ‘C’ is reference variable is hold in
Ctwo class.
When JVM execute it creates reference variable C and Ctwo class object.
When JVM executes Step-2 JVM executes C reference variable is holding which class
object JVM finds that C reference variable is holding Ctwo class object.
9
Now the JVM open Ctwo class object and check method one() is available as part of
Ctwo class or not. If available in Ctwo class JVM executes it. If it is not available JVM
checks whether Ctwo class is inheriting the properties of any other class.
In our example Ctwo class is inheriting the properties of Cone class. Now the JVM
open’s Cone class and check whether methodOne() is available in Cone class. JVM
executes methodOne() Cone class.
In java we can achieve polymorphism by using inheritance.
What is polymorphism?
When we got an error message like javaC is not recognized as internal or external
commands we can resolve the problem by setting path and environment variable in the
command prompt.
Ex: Set PATH=c:\program files\java\jdk1.6_29\bin
If a super class reference variable can holds sub class object, by reference variable we
can access the methods of that class or super class.
A reference variable can hold an object. By using a method getClass() we can find which
class object is holed by the reference variable.
Ex: Cone c1 = new Cone();
System.out.println(c1.getClass());
10
A reference variable can hold the address of another object.
Ex: public class MyApp{
public static void main(String[] args){
Cone c1 = new Cone();
Cone c2 = new Cone();
c1.x = 10;
c1.y = 20;
c2.x = 60;
c2.y = 70;
System.out.println(c1.x);
System.out.println(c1.y);
System.out.println(c2.x);
System.out.println(c2.y);
c1 = c2;
System.out.println(c1.x);
System.out.println(c1.y);
System.out.println(c2.x);
System.out.println(c2.y);
}
}
A super class reference variable can hold sub class object. By using the super class
reference variable we can access the methods of that class only.
But we can’t access the specific methods of sub class , to access the specific methods
of sub class we must type cast super class reference variables into sub class.
Ex: public class MYApp {
public static void main(String args[]){
Object o = new Ctwo();
Cone c1 = (cone)o;
Ctwo c2 = (ctwo)o;
c2.methodTwo();
}
}
11
public void mehodTwo{
System.out.println(“we are in Cone methodTwo()”);
}
}
In the main() we have create object to Ctwo class and call methodOne()
public class MyApp{
public static void main(String[] args){
Ctwo c = new Ctwo();
c.methodOne();
} // Step 1
}
When we execute the above program JVM checks which class object is holed by the
reference variable ‘C’.
Now the JVM opens that reference variable and check for methodOne(). In our example
‘C’ reference variable is holding Ctwo class object.
Now the JVM checks mehtodOne() is available in Ctwo class or not. If it is not available
JVM has checks the super class Cone. Now the JVM executes methodOne() of Cone
class.
The internal code of methodOne() calling methodTwo(). Now the JVM checks whether
methdTwo() is available in the current object or not , in our example in current object is
Ctwo so the JVM open Ctwo class object and check for methodTwo(). If it is available it
will execute or it go to super class of Cone and check for methodTwo().
To an interface we can create the reference variable the reference variable holds an
object of a class which provides the implementation of a interface.
We cannot create object to any abstract class. We can create only reference variable.
We can declare of abstract if we don’t allow any body to create object to a class.
Ex: public abstract class Cone{
public void methodOne(){
}
Public abstract void methodTwo();
}
In the above ApBill.java, we are calculating ElecBill by using an object ‘e’ we are using
‘w’ to calculate WaterBill.
As we are using two different objects to calculate ElecBill as well as WaterBill, we
cannot call this program as polymorphism.
The following example demonstrates how you achieve polymorphism for the same
above project. To achieve polymorphism we take the help of interface will force every
developer to provide the implementation to that interface.
public Interface Bill{
public void calBill(){
}
}
public class ElecBill implements Bill {
public void calBill(int units) {
double bamount = units * 2;
System.out.println(“ElecBill amount is:” + bamount);
}
} //ElecBill.java
In the above APBill.java the object ‘b’ is used to calculate both ElecBill as well as
WaterBill. Because of this reasons we calAPBill.java as polymorphism code.
MRF guys are any other fellows how want to a manufacture a car they engine the
properties of MRF as shown below.
16
}
} //Mar.java
We would like to develop 3 java programs in src folders and compile and placed .class
files in the bin folder. If we would like to place the .class files into a specific folders we
use an option ‘-d’ for javac command.
Ex: Javac –d <destination-folders> sourcefileName
Javac –d d:\work\bms\bin welcome.java
If always recommended to create the java program with packages. It is not at all
recommended to create the java programs with out packages.
To create the packages every company follows their own procedures. Some of the
company users the following pattern.
Package domain.companyname.projectname.module (Or)
Package companyname.projectname.modulename
To deliver the project to the customer we can use any of the following.
1. JAR(javar a relive)
2. WAR(web a relive)
3. EAR (enterprise a relive)
We deliver the software in the form of jar if it’s corejava related projects.
All the web based applications (servlets, jsp, structs) will release in the form of WAR
files.
The enterprise applications like EJB’s will release in the from of EAR files.
We have only one file or command JAR.EXE to create jar file or war file or ear files.
17
D:\> javac –d
*Environment Variables:
18
These are the variables which will be created for us to create Environment variable.
We use keyword set.
Eg: D:\>work>set ONE = 1
To see all the environment variables of our computer we use a keyword “set”.
To check the value of environment variable we use a command echo
Ex: echo% one %
When we run above command. If environment variable one is available we get value of
it, if it is not available we get the value as % one %
Set one = 1;2;3 one is Variable name
Echo % one %
1;2;3
C:\> set one = 1
E:\> echo % one %
Set one = % one % 4,5;6;7
Echo % one % 1; 2; 3; 4; 5; 6; 7
Set one = % one % ;3;4;5
Echo % one % 1; 2; 3; 4; 5
Set one = 0; % one %
Echo % one % 0; 1; 2; 3; 4; 5
To append new value to the existing environment variable he will use following
command.
Scope:
Where we can access variable is scope by default the scope of environment
variable is until we close session (close the window) procedure to set the environment
variable is until permanently.
1. Computer Right click -> properties -> Advanced system settings.
2. Choose an option advanced -> environment variables.
3. In system variables select new button and enter variable name and value.
If we want operating system to search for some files we use an environment variable
path.
Ex: set PATH=C:\programfiles\java\jdk1.6.0_29\bin
Path environment variable environment variable is used to search for the files. This
variable is used by operating system.
19
We use the class path environment variable to search for the .class files this
environment variable to search for the .class files this environment variable is used by
JVM.
\bin>jar –CVF MyProject.jar
C:\> set CLASSPATH=C:\MyProject.jar;.;
C:\> java info.inetsolv.jee.mb.welcome
package info.inetsolv.jee.mb
javac –d d:\work\bin
D:\work\lic\src *.java
java info.inetsolv.jee.mb.welcome
set CLASSPATH=D:\work\lib\bin;.;
java info.inetsolv.jee.mb.welcome
When we deliver jar file to customer. He set CLASSPATH to jar file & execute it.
Ex:
C:\> set CLASSPATH=C:\MyProject.jar;.; .cmd file
C:\> java info.inetsolv.jee.mb.welcome .b (or)
C:\>pause sh for unix
To release project to customers we create jar file if we give only jar file customer is
responsible to set the CLASSPATH and type the commands to run the project. To
resolve this problem we develop a CMD file or data file. In this we supply all the DOS
commands.
set CLASSPATH=c:\MyProject.jar;.;
java info.inetsolv.jee.mb.welcome
pause //run.cmd
creating an object’s INSTANCE
*static variables:
In a class we can declare static variables , for the static variables memory
will be allocated only once. This allocation will happen at the time of loading the class
into JVM’s memory.
When ever we create object the class is loaded into JVM’s memory.
Public class Cone{
static int a;
public void methodOne(){
a = 10;
}
Static{
System.out.println(a);
20
}
Memory Allocation
Local Stack
Instance Heap (one copy is created) variables
Static Memory is not allocated to every object only one copy is allocated.
When class is loaded in JVM’s memory, memory is allocated.
public class Cone{
static int a;
public static void methodOne(){
a = 10;
}
Static {
System.out.println(a);
}
}
When we run above Cone.java by using java Cone, JVM loads Cone.class into JVM’s
memory.
When the class is loaded JVM checks for static variables JVM allocates the memory for
all the static variables and these variables are initialized with default values.
Now the JVM checks are there any static methods are available. If they are available it
will allocate memory to all the static methods. How the JVM checks are there any
static blocks are available. If they are available JVM allocates memory to static blocks.
21
Cone c2 = new Cone();
}
} // save MyApp.java
Memory for static variables will be allocated only once when class is loaded into JVM’s
memory.
22
public static void main(String[] args){
Cone c1 = new Cone();
Cone c2 = new Cone();
c1.a = 10;
c1.b = 99;
c2.a = 20;
System.out.println(c1.a);
System.out.println(c1.b);
System.out.println(c2.a);
System.out.println(c2.b);
}
} // save MyApp.java
*Hard coding:
Fixing the value to a variable is called as hard coding.
Ex: public class MyApp{
public static void main(String[] args){
int a = 10;
System.out.println(a);
}
} // save MyApp.java
In the above program ‘a’ variable value is hard coded with a value ‘10’.
When we remove the hard coding project will be flexible. In a project it is not at all
recommended to hard code the values we can use any of the following two techniques
to remove hard coding. They are two types
1. Command line arguments
2. System properties
To run the above java program we are using the following command.
23
>java MyApp blue 13
The disadvantage of above approach is if we inter change the values the project will be
failed to resolve this problem. We use System properties.
*System properties:
public class MyApp{
public static void main(String[] args){
String color = System.getProperty(“c1”);
int font = Integer.parseInt(System.getProperty(“f”));
System.out.println(color);
System.out.println(font);
}
}
To run the above program we use the following command.
Ex: >java –D cl = green –DF =12 MyApp
Define Value
System variable name
*class.forName():
All ways recommended handling the checked Exception by using any of the following
two techniques.
24
1. try catch block
2. by using throws
When ever we use class.forName() to load the class we must specify fully qualified
name or absolute class name (class name with package).
Ex: public class MyApp{
public static void main(String[] args)throws classNotFoundException{
class.forName(“java.lang.String”);
}
}
class.forName return class object this object contains two information they are
1. Name of the loaded class and its package.
2. We can get this information by using a methods like getName() get package();
Ex: class MyApp{
public static void main(String[] args)throws classNotFoundException{
class c = class.forName(“java.lang.Object”);
System.out.println(c.getName());
System.out.println(c.getPackage());
}
}
Get package method returns null value if the class does not contain package.
Develop a java program to create object to a class without using new operator.
Sun micro system as released JSE API. This is a public API released by sun micro system.
26