2. C++ vs Java
Comparison Index C++ Java
Platform-independent C++ is platform-dependent. Java is platform-independent.
Mainly used for C++ is mainly used for system programming. Java is mainly used for application
programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Goto C++ supports goto statement. Java doesn't support goto statement.
Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple
inheritance through class. It can be
achieved by interfaces in java.
Operator Overloading C++ supports operator overloading. Java doesn't support operator
overloading.
Pointers C++ supports pointers. You can write pointer
program in C++.
Java supports pointer internally. But
you can't write the pointer program
in java. It means java has restricted
pointer support in java.
Compiler and Interpreter C++ uses compiler only. Java uses compiler and interpreter
both.
Call by Value and Call by
reference
C++ supports both call by value and call by
reference.
Java supports call by value only.
There is no call by reference in java.
3. Structure and Union C++ supports structures and
unions.
Java doesn't support structures and
unions.
Thread Support C++ doesn't have built-in support
for threads. It relies on third-party
libraries for thread support.
Java has built-in thread support.
Documentation
comment
C++ doesn't support documentation
comment.
Java supports documentation
comment (/** ... */) to create
documentation for java source
code.
Virtual Keyword C++ supports virtual keyword so
that we can decide whether or not
override a function.
Java has no virtual keyword. We
can override all non-static methods
by default. In other words, non-
static methods are virtual by
default.
unsigned right shift >>> C++ doesn't support >>> operator. Java supports unsigned right shift
>>> operator that fills zero at the
top for the negative numbers. For
positive numbers, it works same
like >> operator.
Inheritance Tree C++ creates a new inheritance tree
always.
Java uses single inheritance tree
always because all classes are the
child of Object class in java. Object
class is the root of inheritance tree
in java.
4. Simple Program of Java
• We will learn how to write the simple program of java. We can write a simple
hello java program easily after installing the JDK.
• To create a simple java program, you need to create a class that contains main
method. Let's understand the requirement first.
• Requirement for Hello Java Example
• For executing any java program, you need to install the JDK if you don't have
installed it, download the JDK and install it.
• set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-
in-java
• create the java program
• compile and run the java program
5. Creating hello java example
• Let's create the hello java program:
class Simple{
public static void main(String args[])
{ System.out.println("Hello Java");
}
}
• Save this file as Simple.java
To compile: javac Simple.java
To execute: java Simple
Output: Hello Java
6. Understanding first java program
• Let's see what is the meaning of class, public, static, void,
main, String[], System.out.println().
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents
visibility, it means it is visible to all.
• static is a keyword, if we declare any method as static, it is
known as static method. The core advantage of static
method is that there is no need to create object to invoke
the static method. The main method is executed by the
JVM, so it doesn't require to create object to invoke the
main method. So it saves memory.
7. • void is the return type of the method, it means it
doesn't return any value.
• main represents startup of the program.
• String[] args is used for command line argument. We
will learn it later.
• System.out.println() is used print statement. We will
learn about the internal working of System.out.println
statement later.
8. To write the simple program, open notepad by start menu -> All Programs ->
Accessories -> notepad and write simple program as displayed below:
9.
10. How many ways can we write a java program
There are many ways to write a java program. The modifications that can be done
in a java program are given below:
1) By changing sequence of the modifiers, method prototype is not
changed.
– Let's see the simple code of main method.
static public void main(String args[])
2) subscript notation in java array can be used after type, before variable
or after variable.
– Let's see the different codes to write the main method.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
11. 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.
public static void main(String... args)
4) Having semicolon at the end of class in java is optional.
– Let's see the simple code.
class A{
static public void main(String... args){
System.out.println("hello java4");
}
};
12. Valid java main method signature
– public static void main(String[] args)
– public static void main(String []args)
– public static void main(String args[])
– public static void main(String... args)
– static public void main(String[] args)
– public static final void main(String[] args)
– final public static void main(String[] args)
Invalid java main method signature
– public void main(String[] args)
– static void main(String[] args)
– public void static main(String[] args)
– abstract public static void main(String[] args)
13. Resolving an error "javac is not recognized as an
internal or external command" ?
• If there occurs a problem like displayed in the below figure, you need to set path. Since
DOS doesn't know javac or java, we need to set path. Path is not required in such a case
if you save your program inside the jdk/bin folder. But its good approach to set path.
14. Internal Details of Hello Java Program
• In the previous slides, we have learned about the first program, how to compile and how to
run the first java program. Here, we are going to learn, what happens while compiling and
running the java program. Moreover, we will see some question based on the first program.
• What happens at compile time?
– At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
15. What happens at runtime?
At runtime, following steps are performed:
• Classloader: is the subsystem of
JVM that is used to load class files.
• Bytecode Verifier: checks the code
fragments for illegal code that can
violate access right to objects.
• Interpreter: read bytecode stream
then execute the instructions.
16. 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:
• To compile:javac Hard.java
• To execute:java Simple
17. JVM (Java Virtual Machine)
• JVM (Java Virtual Machine) is an abstract machine. It is a specification
that provides runtime environment in which java bytecode can be
executed.
• JVMs are available for many hardware and software platforms (i.e. JVM
is platform dependent).
• What is JVM?
– It is:
– A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.
– An implementation Its implementation is known as JRE (Java Runtime
Environment).
– Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.
18. What it does
• The JVM performs following operation:
– Loads code
– Verifies code
– Executes code
– Provides runtime environment
• JVM provides definitions for the:
– Memory area
– Class file format
– Register set
– Garbage-collected heap
– Fatal error reporting etc.
20. 1) Classloader
• Classloader is a subsystem of JVM that is used to load class
files.
2) Class(Method) Area
• Class(Method) Area stores per-class structures such as the
runtime constant pool, field and method data, the code for
methods.
3) Heap
• It is the runtime data area in which objects are allocated.
4) Stack
• Java Stack stores frames. It holds local variables and partial
results, and plays a part in method invocation and return. Each
thread has a private JVM stack, created at the same time as
thread. A new frame is created each time a method is invoked.
A frame is destroyed when its method invocation completes.
21. 5) Program Counter Register
• PC (program counter) register. It contains the address of the Java
virtual machine instruction currently being executed.
6) Native Method Stack
• It contains all the native methods used in the application.
7) Execution Engine
• It contains:
– 1) A virtual processor
– 2) Interpreter: Read bytecode stream then execute the instructions.
– 3) Just-In-Time(JIT) compiler: It is used to improve the performance. JIT
compiles parts of the byte code that have similar functionality at the same
time, and hence reduces the amount of time needed for compilation. Here
the term “compiler” refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.
22. Object-Oriented Programming
Concepts
• What Is an Object?
– An object is a software bundle of related state and
behaviour. Software objects are often used to model the
real-world objects that you find in everyday life.
– Real-world objects share two characteristics: They all
have state and behaviour.
Example:
Dogs have state (name, color, breed, hungry) and
behavior (barking, fetching, wagging tail).
Bicycles also have state (current gear, current pedal cadence,
current speed) and
behavior (changing gear, changing pedal cadence, applying
brakes).
23. A Software Object
• Software objects are conceptually similar to real-world objects:
they too consist of state and related behaviour.
• An object stores its state in fields (variables in some programming
languages) and exposes its behaviour through methods (functions
in some programming languages).
• Methods operate on an object's internal state and serve as the
primary mechanism for object-to-object communication.
• Hiding internal state and requiring all interaction to be performed
through an object's methods is known as data encapsulation — a
fundamental principle of object-oriented programming.
24. Consider a bicycle, for example:
Bundling code into individual software objects provides a number of
benefits, including:
– Modularity: The source code for an object can be written and
maintained independently of the source code for other objects.
Once created, an object can be easily passed around inside the
system.
– Information-hiding: By interacting only with an object's methods,
the details of its internal implementation remain hidden from the
outside world.
25. – Code re-use: If an object already exists (perhaps written by
another software developer), you can use that object in your
program. This allows specialists to implement/test/debug
complex, task-specific objects, which you can then trust to run
in your own code.
– Pluggability and debugging ease: If a particular object turns out
to be problematic, you can simply remove it from your
application and plug in a different object as its replacement. This
is analogous to fixing mechanical problems in the real world. If a
bolt breaks, you replace it, not the entire machine.
26. What Is a Class?
• A class is the blueprint from which individual
objects are created.
In our Bicycle example: There may be thousands of other bicycles in
existence, all of the same make and model. Each bicycle was built
from the same set of blueprints and therefore contains the same
components. In object-oriented terms, we say that your bicycle is
an instance of the class of objects known as bicycles.
28. Have you noticed that the Bicycle class does
not contain a main method.
That's because it's not a complete application; it's just the
blueprint for bicycles that might be used in an application. The
responsibility of creating and using new Bicycle objects
belongs to some other class in your application.
29. class BicycleDemo {
public static void main(String[] args)
{
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
30. What Is Inheritance?
• Different kinds of objects often have a certain amount in common
with each other.
Object-oriented programming allows classes to inherit commonly used state and
behaviour from other classes.
In this example, Bicycle now becomes the superclass of MountainBike, RoadBike,
and TandemBike.
In the Java programming language, each class is allowed to have one direct
superclass, and each superclass has the potential for an unlimited number
of subclasses.
31. • The syntax for creating a subclass is simple. At the beginning of your
class declaration, use the extends keyword, followed by the name
of the class to inherit from:
class MountainBike extends Bicycle {
// new fields and methods defining
// a mountain bike would go here
}
• This gives MountainBike all the same fields and methods as Bicycle,
yet allows its code to focus exclusively on the features that make it
unique.
32. What Is an Interface?
As we already learned, objects define their
interaction with the outside world through the
methods that they expose.
Methods form the object's interface with the outside
world.
For Example: the buttons on the front of your switch board, are
the interface between you and the electrical wiring on the other
side of its plastic casing. You press the "power" button to turn the
appliances on and off.
33. In its most common form, an interface is a group of related methods
with empty bodies. A bicycle's behaviour, if specified as an interface,
might appear as follows:
interface Bicycle {
// wheel revolutions per minute
void changeCadence (int newValue);
void changeGear (int newValue);
void speedUp (int increment);
void applyBrakes (int decrement);
}
34. To implement this interface, the name of your class would change (to a
particular brand of bicycle, for example, such as ATLASBicycle), and you'd use
the implements keyword in the class declaration:
class ATLASBicycle implements Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
// The compiler will now require that methods
// changeCadence, changeGear, speedUp, and applyBrakes
// all be implemented. Compilation will fail if those
// methods are missing from this class.
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement; }
void printStates() {
System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear);
} }
35. Types of inheritance in Java: Single,
Multiple, Multilevel & Hybrid
Single Inheritance: When a class extends another one class only
then we call it a single inheritance.
Here A is a parent class of B and B would be a child class of A.
36. Single Inheritance example program in Java
Class A {
public void methodA() {
System.out.println("Base class method");
}
}
Class B extends A {
public void methodB() {
System.out.println("Child class method");
}
public static void main(String args[]) {
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
37. Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits)
more than one base class.
The problem with “multiple inheritance” is that the derived class will have to
manage the dependency on two base classes.
Note: Most of the new OO languages like Small Talk, Java, C# do not
support Multiple inheritance. Multiple Inheritance is supported in C++.
38. Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology
where one can inherit from a derived class, thereby making this
derived class the base class for the new class. As you can see in
below flow diagram C is subclass or child class of B and B is a child
class of A.
39. Multilevel Inheritance example program in Java
Class X {
public void methodX() {
System.out.println("Class X
method");
}
}
Class Y extends X {
public void methodY() {
System.out.println("class Y
method");
}
}
Class Z extends Y {
public void methodZ() {
System.out.println("class Z method");
}
public static void main(String args[]) {
Z obj = new Z();
obj.methodX(); //calling grand parent
class method obj.methodY(); //calling
parent class method
obj.methodZ(); //calling local method
}
}
40. Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub
classes. In below example class B, C and D inherits the same class
A. A is parent class (or base class) of B, C & D.
41. Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination
of Single and Multiple inheritance. A typical flow diagram would look
like below. A hybrid inheritance can be achieved in the java in a same
way as multiple inheritance can be!!
By using interfaces you can have multiple as well as hybrid
inheritance in Java.
42. Example 1
Most of the times you will find the following explanation of
above error –
Multiple inheritance is not allowed in java so class D cannot
extend two classes(B and C).
But do you know why it’s not allowed?
In the above program class B and C both are extending class A
and they both have overridden the methodA(), which they
can do as they have extended the class A.
But since both have different version of methodA(), compiler
is confused which one to call when there has been a call
made to methodA() in child class D (child of both B and C, it’s
object is allowed to call their methods), this is a ambiguous
situation and to avoid it, such kind of scenarios are not
allowed in java. In C++ it’s allowed.
43. Example 2
Even though class D didn’t implement interface “A” still we have to
define the methodA() in it. It is because interface B and C extends
the interface A.
The above code would work without any issues and that’s how we
implemented hybrid inheritance in java using interfaces.
44. Basic But IMPORTANT things to
remember throughout JAVA
Default value of all Variables
Type of variable Default value
byte 0
short 0
int 0
long 0L
float 0f
double 0d
char null
boolean false
reference null
46. Backslash Character Constants
Constant Meaning
b back space
f form feed
n new line
r carriage return
t horizontal tab
' " single quote
' " ' double quote
' ' backslash
47. Arithmetic Operators
Operator Meaning
+ Addition or plus
- Subtraction or minus
* Multiplication
/ Division
% Modulo division
Relational Operators
Operator Meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.
If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.