Professional Documents
Culture Documents
Foundation of Programing: Object
Foundation of Programing: Object
Note: Multiple inheritance is not supported in java through class. When a class extends multiple
classes i.e. known as multiple inheritance. For Example:
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there
will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error
if you inherit 2 classes. So whether you have same method or different, there will be
compile time error now.
4) Polymorphism:
Example-2:
If a & b are int then in a+b “+ sign” act as addition, in other hand if a & b are strings then it will
act as concatenation.
Programming: “Programming is a set of instructions”
PROGRAMMING LANGUAGE:
A vocabulary and set of grammatical rules for instructing a computer to perform specific
tasks.
The term programming language usually refers to high-level languages, such as Java, C,
and C++.
Each language has a unique set of keywords (words that it understands) and a special
syntax for organizing program instructions.
3) High-level language:
So, this is why programing languages were invented because The CPU (Hardware) doesn’t
understand any of the Programming languages like assembly, high level. It can only understand
is Machine Code or Machine language.
1) Compiler: It scans entire program & translate it as a whole into machine code,
i.e. into executable file. So that we can share only executable file & keep safe our
source code
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates it
time. as a whole into machine code.
It takes less amount of time to analyze It takes large amount of time to analyze
the source code but the overall execution the source code but the overall execution
time is slower. time is comparatively faster.
Generates intermediate object code
No intermediate object code is
which further requires linking, hence
generated, hence are memory efficient.
requires more memory.
Continues translating the program until It generates the error message only after
the first error is met, in which case it scanning the whole program. Hence
stops. Hence debugging is easy. debugging is comparatively hard.
Programming language like Python, Programming language like C, C++ use
Ruby, Java use interpreters. compilers.
Suppose if you want to tell the computer to add two number (1+2) which is represented by some
binary numbers (10000011), how are you going to tell the computer? Yes, we going to use
assembly language to get our code executed.
With advancement in software development languages, this entire assembly code could shrink
into just one line print f 1+2 A with the help of software called COMPILER. It is used to convert
your c language code into assembly code, and the assembler converts it into corresponding
machine code, and this machine code will be transmitted to the processor. The most common
processor used in PC or Computers are Intel processor.
Though present day compilers come bundled with assembler can directly convert your higher
language code into machine code.
Now, suppose Windows operating system is running on this Intel processor, a combination of
Operating System plus the processor is called the PLATFORM. The most common platform
in the world is the Windows and Intel called the Wintel Platform. The other popular platforms are
AMD and Linux, Power PC, and Mac OS X.
Now, with a change in processor, the assembly instructions will also change. For example the
And obviously with a change in Operating System, the level and nature of O.S level calls will also
change.
By using Java Virtual Machine, these problem can be solved. But how it works on different
processors and O.S. Let's understand this process step by step.
Step 1) The code to display addition of two numbers is System.out.println(1+2), and saved as
.java file
Step 2) Using the java compiler (javac) the code is converted into an intermediate code called
the bytecode. The output is a .class file.
Step 3) this code is not understood by any platform, but only a virtual platform called the Java
Virtual Machine
Step 4) This Virtual Machine resides in the RAM of your operating system. When the Virtual
Machine is fed with this bytecode, it identifies the platform it is working on and java interprets the
bytecode (line by line) into the native machine code
In fact, while working on your PC or browsing the web whenever you see either of these icons be
assured the java virtual machine is loaded in your RAM. But what makes java lucrative is that
code once compiled can run not only on all PC platforms but also mobiles or other electronic
gadgets supporting java
Bytecode is computer object code that is processed by a program, usually referred to as a virtual
machine, rather than by the "real" computer machine, the hardware processor. The virtual
machine converts each generalized machine instruction into a specific machine instruction or
instructions that this computer's processor will understand. Bytecode is the result of compiling
source code written in a language that supports this approach.
Using a language that comes with a virtual machine for each platform, your source language
statements need to be compiled only once and will then run on any platform.
Rather than being interpreted one instruction at a time, Java bytecode can be recompiled at each
particular system platform by a just-in-time compiler. JIT used to speed up the execution time
by interpreting part of byte code that has similar functionality at same time. Usually, this will enable
the Java program to run faster. In Java, bytecode is contained in a binary file with a .CLASS suffix.
In order to write and execute a software program you need the following
1) Editor – To type your program into, a notepad could be used for this
2) Compiler – To convert your high language program into native machine code
3) Linker – To combine different program files reference in your main program together.
4) Loader – To load the files from your secondary storage device like Hard Disk, Flash Drive, CD
into RAM for execution. The loading is automatically done when your execute your code.
5) Execution – Actual execution of the code which is handled by your OS & processor.
C code Compilation and Execution process
Suppose in the main, you have called two function f1 and f2. The
main function is stored in file a1.c.
Function f2 is stored
Function f1 is stored in a
in a file a3.c
file a2.c
All these files, i.e., a1.c, a2.c, and a3.c, is fed to the compiler. Whose output is the corresponding
object files which is the machine code.
The next step is integrating all these object files into a single .exe file with the help of linker. The
linker will club all these files together and produces the .exe file.
During program run a loader program will load a.exe into the
RAM for the execution.
Let's look at the process for JAVA. In your main you have two
methods f1 and f2.
What is JVM?
JVM stands for Java Virtual Machine. It is the engine that drives the Java Code. It converts Java
bytecode into machines language.
In other programming language, the compiler produces code for a particular system. But
Java compiler produces code for a Virtual Machine.
In JVM, Java code is compiled into bytecode. This bytecode gets interpreted on different
machines
Between host system and Java source, Bytecode is an intermediary language.
JVM is responsible for allocating a memory space.
A compiler is a program which converts a program from one level of language to another.
Example conversion of C++ program into machine code.
The java compiler is a convert's high level java code into bytecode (which is also a type of
machine code).
An interpreter is a program which converts a program at one level to another
programming language at the same level. Example conversion of Java program into C++
In Java, the Just In Time Code generator converts the bytecode into the native machine
code which are at the same programming levels.
Hence java is both compiled as well as interpreted language.
Why is Java slow?
Summary:
JVM or Java Virtual Machine is the engine that drives the Java Code. It converts
Java bytecode into machines language.
In JVM, Java code is compiled to bytecode. This bytecode gets interpreted on
different machines
JIT or Just-in-time compiler is the part of the Java Virtual Machine (JVM). It is used
to speed up the execution time
In comparison to other compiler machine, Java may be slow in execution.
Hence, JRE is only used by them who only wants to run the Java
Programs i.e. end users of your system.
JVM: - Java Virtual machine (JVM) is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever java program you run using JRE or JDK goes into JVM and
JVM is responsible to execute the java program line by line hence it is also known as
interpreter(we will discuss about interpreter later) . Hence you don’t need to install JVM separately
into your machine because it is inbuilt into your JDK or JRE installation package. We’ll explore
more about JVM soon.
Java is −
Object Oriented − In Java, everything is an Object. Java can be easily extended since it
is based on the Object model.
Platform Independent − unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and interpreted
by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master. Also syntax is similar to c, c++
Secure − With Java's secure feature it enables
to develop virus-free, tamper-free systems.
Bytecode must run inside JVM, & cannot
access system directly. But in C language,
executable file is directly accessed by system
so, more possibility to make malicious
programs.
Robust – Java helps you to write robust code which is non breaking.
The command line argument is the argument passed to a program at the time when you run it.
To access the command-line argument inside a java program is quite easy, they are stored as
string in String array passed to the args parameter of main() method.
There are many ways to write a java program. The modifications that can be done in a java program are
given below:
2) Subscript notation in java array can be used after type, before variable or after variable.
3) You can provide var-args support to main method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in main method. We will learn about var-args later in Java
New Features chapter.
1. class A{
2. static public void main(String... args){
3. System.out.println("hello java4");
4. }
5. };
Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Can you have multiple classes in a java source file?
Yes, like the figure given below illustrates:
Basic Syntax
Class Names − for all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Method Names − All method names should start with a Lower Case letter. If several words
are used to form the name of the method, then each inner word's first letter should be in
Upper Case.
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are called
identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There
are two categories of modifiers −
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
fields
methods
constructors
blocks
nested class and interface
A class describe Object i.e. its properties and behavior. Below e.g. explains how Ball class is
created from Simple English phrase to programming language
Objects Objects
reference
variable
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
1) Local Variables
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap, a slot for each instance variable value
is created.
Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers, the default value is 0, for Booleans
it is false, and for object references it is null. Values can be assigned during the declaration
or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. ObjectReference.VariableName.
Class/Static Variables
Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program
stops.
Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally, values can be assigned in special
static initializer blocks.
Static variables can be accessed by calling with the class name
ClassName.VariableName.
When declaring class variables as public static final, then variable names (constants) are
all in upper case. If the static variables are not public and final, the naming syntax is the
same as instance and local variables.
Here, value of i changes to 1 every time you called setInfo() method, but not j.
Methods
type name(parameter-list) {
// body of method
return value;
JAVA STATIC METHOD: static methods in Java can be called without creating an object of
class. Have you noticed why we write static keyword when defining main it's because program
execution begins from main and no object has been created yet. Consider the example below to
improve your understanding of static methods.
Instance method requires an object of its class to be created before it can be called while static
method doesn't require object creation.
Using static method of another classes
If you wish to call static method of another class then you have to write class name while calling static
method as shown in example below.
Access Modifiers in java ( Note: A class cannot be private or protected except nested class.)
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient
etc.
1) Private access modifier : The private access modifier is accessible only within class.
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile
time error.
2) Default access modifier: If you don't use any modifier, it is
treated as default by default. The default modifier is accessible
only within package.
Example of default access modifier
In this example, we have created two packages pack and
mypack. We are accessing the A class from outside its package,
since A class is not public, so it cannot be accessed from outside
the package.
In the this example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
If you apply static keyword with any method, it is known as static method.
“Garbage Collection” as the name suggests is used to remove the objects that are no longer
needed by the Java application. The Java Garbage Collector will identify those objects and
remove those from the memory thereby freeing the memory for the new objects.
Note: Try to make Data members as Private & Methods as public so that others cannot
change your data members i.e. using encapsulation. (i.e. always instantiate date members
through methods or constructors not by reference
variable.)
For E.g.
String color;
String Brand;
setInfo(String colour,String brand)
Ball b= new Ball();
b.setInfo(red, Nike);
Else, Hacker can set any false value if instantiated by reference variable as follows
b.color=Nike; b.Brand=Red;
3) Initialization through constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of new object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
1) Default Constructor:
If there is no constructor in a class, compiler
automatically creates a default constructor.
Default constructor provides the default values to the
object like 0, null etc. depending on the type.
2) Basic Constructor: A constructor that have no parameter is known as default constructor.
Output
3) Parameterized constructor:
A constructor that have parameters is known as parameterized constructor.
Parameterized constructor is used to provide different values to the distinct objects.
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
In java, Method Overloading is not possible by changing the return type of the method only.
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance
for calling methods.
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
Q) Why Method Overloading is not possible by changing the return type of method
only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time
error if you declare the same method having same parameters.
Runtime and compile time are programming terms that refer to different stages of software
program development. In order to create a program, a developer first writes source code, which
defines how the program will function. Small programs may only contain a few hundred lines of
source code, while large programs may contain hundreds of thousands of lines of source code.
The source code must be compiled into machine code in order to become and executable
program. This compilation process is referred to as compile time.
A compiled program can be opened and run by a user. When an application is running, it
is called runtime.
The terms "runtime" and "compile time" are often used by programmers to refer to different types
of errors. A compile time error is a problem such as a syntax error or missing file reference that
prevents the program from successfully compiling. The compiler produces compile time errors
and usually indicates what line of the source code is causing the problem.
If a program's source code has already been compiled into an executable program, it may still
have bugs that occur while the program is running. Examples include features that don't work,
unexpected program behavior, or program crashes. These types of problems are called runtime
errors since they occur at runtime.
Method Overloading and Type Promotion
1) Example of Method Overloading with Type 2) Example of Method Overloading with Type Promotion
Promotion if matching found
3) Example of Method Overloading with Type Promotion in case of ambiguity:If there are no
matching type arguments in the method, and each method promotes similar number of arguments,
there will be ambiguity.
Anonymous object
For example:
c.fact(5);
new Calculation().fact(5);
Initialization of reference variables: Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
Real World Example: Account
File: TestAccount.java
Summary of all above Terms
Output
JAVA NATIVE METHODS
The ability to write just one set of code in Java and have it run on every system with a Java run-
time is one of Java's primary strengths. But this platform independence has one key drawback:
What do we do with the vast amount of existing code? The trick is to use the so-called native
method interface.
Writing native methods involves importing C code into your Java application.
The method is implemented in "native" code. That is, code that does not run in the JVM. It's
typically written in C or C++. Native methods are usually used to interface with system calls or
libraries written in other programming languages.
We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:
Let's prove that this keyword refers to the current class instance variable. In this program, we are
printing the reference variable and this, output of both variables are same.