0% found this document useful (0 votes)
79 views34 pages

C - Vs Java

The document discusses the key differences between C++ and Java. It provides introductions to both languages, outlining their origins and design goals. C++ was designed as an extension of C to support object-oriented programming and systems programming. Java was designed for general-purpose use and to be platform independent through use of a virtual machine. The document then covers some of the main features of each language, such as data types, variables, operators, and design aims.

Uploaded by

dihosid99
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
79 views34 pages

C - Vs Java

The document discusses the key differences between C++ and Java. It provides introductions to both languages, outlining their origins and design goals. C++ was designed as an extension of C to support object-oriented programming and systems programming. Java was designed for general-purpose use and to be platform independent through use of a virtual machine. The document then covers some of the main features of each language, such as data types, variables, operators, and design aims.

Uploaded by

dihosid99
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 34

C++ vs Java

Group members:

1. Rajan Ner              - 36
2. Hitashri Patil          - 42
3. Rohant Narang      - 51
4. Nupur Shinde        - 56
5. Srushti Shingade  - 57

Rajan: Introduction to C++


● C++ is a general-purpose programming language that was
developed as an enhancement of the C language to include an
object-oriented paradigm.

●  It is an imperative and a compiled language.

● It is a middle-level language, as it comprises a combination of both


high-level and low-level language features.

● The basic syntax and code structure of both C and C++ are the
same.

One of the most popular programming languages in a variety of fields


like Game engine, high frequency trading, etc. is C++. It is a semi object
oriented programming language which was developed by Bjarne
Stroustrup as an extension of the already existing programming
language C.

C++, also popularly known as ‘C with classes’, has evolved and


diversified a lot over the course of time and is implemented as a
compiled language. C++ has found its usage in a lot of big Software
Companies like Microsoft, IBM, etcetera and can be used to develop
desktop applications, video games, servers for instance, E-Commerce,
web search and databases, and high performance applications for
instance, telephone switches, space probes, etc.
C++ has support for a lot of features like object oriented principles, for
instance Inheritance, Encapsulation, Polymorphism (both static and
dynamic), etcetera. But a C++ code can be compiled even without
having classes or creating objects. Hence, it is rightly termed as a semi
object oriented language.

Sahil: Key features of C++


● C++ is a statically typed, compiled, general-purpose

● Case-sensitive 

● Free-form programming language that supports procedural, object-


oriented, and generic programming. 

● Complicated run-time libraries and virtual machines have


not traditionally been required for C++

● Compatibility with C libraries and traditional development tools is


emphasized
 
● The significance of the language is largely due to it being
extremely fast, supporting a variety of different coding styles.

● Giving the programmer low level access to the computer through


being a middle-level language.
 
● When dealing with large projects. The object-oriented principles
and C++ support is excellent for this.

Hitashri: Introduction to Java


● JAVA was developed by Sun Microsystems Inc in the year
1991, later acquired by Oracle Corporation.

●  It is a simple programming language. Java makes writing,


compiling, and debugging programming easy.

●  It helps to create reusable code and modular programs.

● Java is a class-based, object-oriented programming language and


is designed to have as few implementation dependencies as
possible.

●  A general-purpose programming language made for developers to


write once run anywhere that is compiled Java code can run on all
platforms that support Java. 

● Java applications are compiled to bytecode that can run on any


Java Virtual Machine.

Omkar: Key features of Java


● Object Oriented: In Java, everything is an Object. Java can be
easily extended as a result of the Object model.

● Platform independent: Unlike languages such as C++, when


Java is compiled, it is not compiled into platform specific
machine code, but rather into platform independent bytecode.

● Secure: With Java’s secure feature it allows for the


development of virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.

● Portable: Being architectural-neutral and having no


implementation dependent aspects makes Java portable. The
Java compiler is written in ANSI C with a clean portability
boundary which is a POSIX subset.

● Robust: Java makes an effort to eliminate error prone situations


by emphasizing mainly on compile time error checking and
runtime checking.

● Multithreaded: With Java’s multithreaded feature it is possible to


write programs that can do many tasks simultaneously. This
design feature allows developers to construct smoothly running
interactive applications.

● Interpreted: Java byte code is translated to native machine


instructions and is not stored anywhere. The development
process is more rapid and analytical since the linking is an
increment and light weight process.

Nupur: Data Types in Java and C++


Data type is an attribute associated with a piece of data that tells a
computer system how to interpret its value. Understanding data types
ensures that data is collected in the preferred format and the value of
each property is as expected.

Variables in Java and C++

A variable is a container which holds the value while the program is


executed. Also variable is a name of memory location.The name of a
variable can be composed of letters, digits, and the underscore
character.

Operators in Java and C++


Java :

There are many types of operators in Java which are given below:

● Unary Operator,
● Arithmetic Operator,
● Shift Operator,
● Relational Operator,
● Bitwise Operator,
● Logical Operator,
● Ternary Operator and
● Assignment Operator.

Java supports only method overloading.

C++ :

Operators in C++ can be classified into 5 types:

● Arithmetic Operators

● Assignment Operators

● Relational Operators
● Logical Operators

● Bitwise Operators

● C++ supports method overloading as well as operator overloading.

Arithmetic Operators: Arithmetic operators are used to perform


arithmetic operations on variables and data.

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Assignment Operators: In C++, assignment operators are used to assign


values to variables.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;
Relational Operators: A relational operator is used to check the
relationship between two operands.

Operato Meaning Example


r

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal 3 >= 5 give us false


To

<= Less Than or Equal To 3 <= 5 gives us true

Logical Operators: Logical operators are used to check whether an


expression is true or false. If the expression is true, it returns 1 whereas
if the expression is false, it returns 0.

Oper Example Meaning


ator

&& expression1 && Logical AND.


expression2 True only if all the operands
are true.

|| expression1 || Logical OR.


expression2 True if at least one of the
operands is true.

! !expression Logical NOT.


True only if the operand is
false.
Bitwise Operators: In C++, bitwise operators are used to perform
operations on individual bits. They can only be used alongside char and
int data types.

Operator Description

& Binary AND

| Binary OR

^ Binary XOR

~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right

Sayantika, Shuham, Prajwal: Design aims


The differences between the programming languages C++ and Java can be
traced to their heritage, as they have different design goals.
C++ was designed for systems and applications programming (i.e.
infrastructure programming), extending the procedural programming language
C, which was designed for efficient execution. To C, C++ added support for
object-oriented programming, exception handling, lifetime-based resource
management (RAII), generic programming, template metaprogramming, and
the C++ Standard Library which includes generic containers and algorithms (the
Standard Template Library or STL), and many other general purpose facilities.
Java is a general-purpose, concurrent, class-based, object-oriented
programming language that is designed to minimize implementation
dependencies. It relies on a Java virtual machine to be secure and highly
portable. It is bundled with an extensive library designed to provide a full
abstraction of the underlying platform. Java is a statically typed object-oriented
language that uses a syntax similar to (but incompatible with) C++. It includes a
documentation system called Javadoc.
The different goals in the development of C++ and Java resulted in different
principles and design trade-offs between the languages.

The differences are as follows:

C++ Java

Extends C with object-oriented Strongly influenced by C++/C syntax.


programming and generic
programming. C code can most
properly be used.

Compatible with C source Provides the Java Native Interface and


code, except for a few corner recently Java Native Access as a way to
cases. directly call C/C++ code.

Write once, compile anywhere Write once, run anywhere/everywhere


(WOCA). (WORA/WORE).

Allows procedural Allows procedural programming, functional


programming, functional programming (since Java 8) and generic
programming, object-oriented programming (since Java 5), but strongly
programming, generic encourages the object-oriented
programming, and template programming paradigm. Includes support for
metaprogramming. Favors a creating scripting languages.
mix of paradigms.

Runs as native executable Runs on a virtual machine.


machine code for the target
instruction set(s).

Provides object types and type Is reflective, allowing metaprogramming and


names. Allows reflection via dynamic code generation at runtime.
run-time type information
(RTTI).

Has multiple binary Has one binary compatibility standard, cross-


compatibility standards platform for OS and compiler.
(commonly Microsoft (for
MSVC compiler) and
Itanium/GNU (for almost all
other compilers)).

Optional automated bounds All operations are required to be bound-


checking (e.g., the at() method checked by all compliant distributions of
in vector and string Java. HotSpot can remove bounds checking.
containers).

Native unsigned arithmetic Native unsigned arithmetic unsupported.


support. Java 8 changes some of this, but aspects are
unclear.[1]

Standardized minimum limits Standardized limits and sizes of all primitive


for all numerical types, but the types on all platforms.
actual sizes are
implementation-defined.
Standardized types are
available via the standard
library <cstdint>.

Pointers, references, and pass- All types (primitive types and reference
by-value are supported for all types) are always passed by value.[2]
types (primitive or user-
defined).

Memory management can be Automatic garbage collection. Supports a


done manually via new / non-deterministic finalize() method, use of
delete, automatically by scope, which is not recommended.[3]
or by smart pointers. Supports
deterministic destruction of
objects. Garbage collection ABI
standardized in C++11, though
compilers are not required to
implement garbage collection.

Resource management can be Resource management must generally be


done manually or by automatic done manually, or automatically via
lifetime-based resource finalizers, though this is generally
management (RAII). discouraged. Has try-with-resources for
automatic scope-based resource
management (version 7 onwards).

It can also be done using the internal API


sun.misc.Unsafe but that usage is highly
discouraged and will be replaced by a public
API in an upcoming Java version.

Supports classes, structs Classes are allocated on the heap. Java SE 6


(passive data structure (PDS) optimizes with escape analysis to allocate
types), and unions, and can some objects on the stack.
allocate them on the heap or
the stack.

Allows explicitly overriding Rigid type safety except for widening


types, and some implicit conversions.
narrowing conversions (for
compatibility with C).

The C++ Standard Library was The standard library has grown with each
designed to have a limited release. By version 1.6, the library included
scope and functions, but support for locales, logging, containers and
includes language support, iterators, algorithms, GUI programming (but
diagnostics, general utilities, not using the system GUI), graphics, multi-
strings, locales, containers, threading, networking, platform security,
algorithms, iterators, introspection, dynamic class loading,
numerics, input/output, blocking and non-blocking I/O. It provided
random number generators, interfaces or support classes for XML, XSLT,
regular expression parsing, MIDI, database connectivity, naming services
threading facilities, type traits (e.g. LDAP), cryptography, security services
(for static type introspection) (e.g. Kerberos), print services, and web
and Standard C Library. The services. SWT offered an abstraction for
Boost library offers more platform-specific GUIs, but was superseded
functions including network by JavaFX in the latest releases, allowing for
I/O. graphics acceleration and CSS-themable UIs.
Although it doesn't support any kind of
A rich amount of third-party "native platform look" support.
libraries exist for GUI and
other functions like: Adaptive
Communication Environment
(ACE), Crypto++, various XMPP
Instant Messaging (IM)
libraries,[4] OpenLDAP, Qt,
gtkmm.

Operator overloading for most Operators are not overridable. The language
operators. Preserving meaning overrides + and += for the String class.
(semantics) is highly
recommended.

Single and multiple inheritance Only supports single inheritance of classes.


of classes, including virtual
inheritance.

Compile-time templates. Generics are used to achieve basic type-


Allows for Turing complete parameterization, but they do not translate
meta-programming. from source code to byte code due to the
use of type erasure by the compiler.

Function pointers, function Functions references, function objects and


objects, lambdas (in C++11), lambdas were added in Java 8. Classes (and
and interfaces. interfaces, which are classes) can be passed
as references as well through
SomeClass.class and someObject.getClass().
No standard inline Extensive Javadoc documentation standard
documentation mechanism. on all system classes and methods.
Third-party software (e.g.
Doxygen) exists.

const keyword for defining final provides a version of const, equivalent


immutable variables and to type* const pointers for objects and const
member functions that do not for primitive types. Immutability of object
change the object. Const-ness members achieved via read-only interfaces
is propagated as a means to and object encapsulation.
enforce, at compile-time,
correctness of the code with
respect to mutability of
objects (see const-
correctness).

Supports the goto statement. Supports labels with loops and statement
blocks. goto is a reserved keyword but is
marked as "unused" in the Java specification.

Source code can be written to Compiled into Java bytecode for the JVM.
be cross-platform (can be Byte code is dependent on the Java platform,
compiled for Windows, BSD, but is typically independent of operating
Linux, macOS, Solaris, etc., system specific features.
without modification) and
written to use platform-
specific features. Typically
compiled into native machine
code, must be recompiled for
each target platform.

Language features

Srushti: Syntax
● Java syntax has a context-free grammar that can be parsed by a
simple LALR parser. Parsing C++ is more complicated. For example,
Foo<1>(3); is a sequence of comparisons if Foo is a variable, but
creates an object if Foo is the name of a class template.
● C++ allows namespace-level constants, variables, and functions. In
Java, such entities must belong to some given type, and therefore
must be defined inside a type definition, either a class or an interface.
● In C++, objects are values, while in Java they are not. C++ uses value
semantics by default, while Java always uses reference semantics. To
opt for reference semantics in C++, either a pointer or a reference
can be used.

C++ Java

class Foo { // Declares class class Foo { // Defines class Foo


Foo private int x; // Member variable,
int x = 0; // Private normally declared
Member variable. It will // as private to enforce
// be initialized to 0, encapsulation
if the // initialized to 0 by default
// constructor would
not set it. public Foo() { // Constructor for
// (from C++11) Foo
public: } // no-arg constructor
Foo() : x(0) // Constructor supplied by default
for Foo; initializes
{} // x to 0. If the public int bar(int i) { // Member
initializer were method bar()
// omitted, the return 3*i + x;
variable would }
// be initialized to }
the value that
// has been given at
declaration of x.

int bar(int i) { // Member


function bar()
return 3*i + x;
}
};

Foo a; Foo a = new Foo();


// declares a to be a Foo object // declares a to be a reference to a new
value, Foo object
// initialized using the default // initialized using the default constructor
constructor.
// Another constructor can be used as
// Another constructor can be Foo a = new Foo(args);
used as
Foo a(args);
// or (C++11):
Foo a{args};

Foo b = a; // Foo b = a;
// copies the contents of a to a // would declare b to be reference to the
new Foo object b; object pointed to by a
// alternative syntax is "Foo Foo b = a.clone();
b(a)" // copies the contents of the object
pointed to by a
// to a new Foo object;
// sets the reference b to point to this
new object;
// the Foo class must implement the
Cloneable interface
// for this code to compile

a.x = 5; // modifies the object a a.x = 5; // modifies the object referenced


by a

std::cout << b.x << std::endl; System.out.println(b.x);


// outputs 0, because b is // outputs 0, because b points to
// some object other than a // some object other than a

Foo *c; Foo c;


// declares c to be a pointer to a // declares c to be a reference to a Foo
// Foo object (initially // object (initially null if c is a class
// undefined; could point member;
anywhere) // it is necessary to initialize c before use
// if it is a local variable)

c = new Foo; c = new Foo();


// c is set to the value of the // binds c to reference a new Foo object
address of the Foo object
created by operator new

Foo &d = *c; Foo d = c;


// binds d to reference the same // binds d to reference the same object as
object to which c points c

c->x = 5; c.x = 5;
// modifies the object pointed to // modifies the object referenced by c
by c
d.bar(5); // invokes Foo::bar() d.bar(5); // invokes Foo.bar() for a
for a c.bar(5); // invokes Foo.bar() for c
c->bar(5); // invokes Foo::bar()
for *c

std::cout << d.x << std::endl; System.out.println(d.x);


// outputs 5, because d // outputs 5, because d references the
references the // same object as c
// same object to which c points

● In C++, it is possible to declare a pointer or reference to a const


object in order to prevent client code from modifying it. Functions
and methods can also guarantee that they will not modify the object
pointed to by a pointer by using the "const" keyword. This enforces
const-correctness.
● In Java, for the most part, const-correctness must rely on the
semantics of the class' interface, i.e., it is not strongly enforced,
except for public data members that are labeled final.

C++ Java

const Foo *a; // it is not possible to final Foo a; // a declaration of a


modify the object "final" reference:
// pointed to by a through a // it is possible to modify the
object,
// but the reference will
constantly point
// to the first object assigned
to it

a = new Foo(); a = new Foo(); // Only in constructor


a->x = 5; a.x = 5;
// ILLEGAL // LEGAL, the object's members can
still be modified
// unless explicitly declared final in
the declaring class

Foo *const b = new Foo(); final Foo b = new Foo();


// a declaration of a "const" pointer // a declaration of a "final" reference
// it is possible to modify the object,
// but the pointer will constantly
point
// to the object assigned to it here

b = new Foo(); b = new Foo();


// ILLEGAL, it is not allowed to re- // ILLEGAL, it is not allowed to re-
bind it bind it

b->x = 5; b.x = 5;
// LEGAL, the object can still be // LEGAL, the object can still be
modified modified

● C++ supports goto statements, which may lead to spaghetti code


programming. With the exception of the goto statement (which is
very rarely seen in real code and highly discouraged), both Java and
C++ have basically the same control flow structures, designed to
enforce structured control flow, and relies on break and continue
statements to provide some goto-like functions. Some commenters
point out that these labelled flow control statements break the single
point-of-exit property of structured programming.[5]
● C++ provides low-level features which Java mostly lacks (one notable
exception being the sun.misc.Unsafe API for direct memory access
and manipulation). In C++, pointers can be used to manipulate
specific memory locations, a task necessary for writing low-level
operating system components. Similarly, many C++ compilers support
an inline assembler. Assembly language code can be imported to a C
program and vice versa. This makes the C language even faster. In
Java, such code must reside in external libraries, and can only be
accessed via the Java Native Interface, with a significant overhead for
each call.

Rajan, Sahil: Semantics


● C++ allows default values for arguments of a function/method. Java
does not. However, method overloading can be used to obtain similar
results in Java but generate redundant stub code.
● The minimum of code needed to compile for C++ is a function, for
Java is a class.
● C++ allows a range of implicit conversions between native types
(including some narrowing conversions), and also allows defining
implicit conversions involving user-defined types. In Java, only
widening conversions between native types are implicit; other
conversions require explicit cast syntax.
○ A result of this is that although loop conditions (if, while and
the exit condition in for) in Java and C++ both expect a
boolean expression, code such as if(a = 5) will cause a
compile error in Java because there is no implicit narrowing
conversion from int to boolean, but will compile in C++. This
is handy if the code was a typo and if(a == 5) was intended.
However, current C++ compilers will usually generate a
warning when such an assignment is performed within a
conditional expression. Similarly, standalone comparison
statements, e.g. a==5;, without a side effect usually lead to
a warning.
● For passing parameters to functions, C++ supports both pass-by-
reference and pass-by-value. In Java, primitive parameters are always
passed by value. Class types, interface types, and array types are
collectively called reference types in Java and are also always passed
by value.
● Java built-in types are of a specified size and range defined by the
language specification. In C++, a minimal range of values is defined
for built-in types, but the exact representation (number of bits) can
be mapped to whatever native types are preferred on a given
platform.
○ For instance, Java characters are 16-bit Unicode characters,
and strings are composed of a sequence of such characters.
C++ offers both narrow and wide characters, but the actual
size of each is platform dependent, as is the character set
used. Strings can be formed from either type.
○ This also implies that C++ compilers can automatically select
the most efficient representation for the target platform
(i.e., 64-bit integers for a 64-bit platform), while the
representation is fixed in Java, meaning the values can
either be stored in the less-efficient size, or must pad the
remaining bits and add code to emulate the reduced-width
behavior.
● The rounding and precision of floating point values and operations in
C++ is implementation-defined (although only very exotic or old
platforms depart from the IEEE 754 standard). Java provides an
optional strict floating-point model (strictfp) that guarantees more
consistent results across platforms, though at the cost of possibly
slower run-time performance. However, Java does not comply strictly
with the IEEE 754 standard. Most C++ compilers will, by default,
comply partly with IEEE 754 (usually excluding strict rounding rules
and raise exceptions on NaN results), but provide compliance options
of varied strictness, to allow for some optimizing.[9][10] If we label
those options from least compliant to most compliant as fast,
consistent (Java's strictfp), near-IEEE, and strict-IEEE, we can say that
most C++ implementations default to near-IEEE, with options to
switch to fast or strict-IEEE, while Java defaults to fast with an option
to switch to consistent.
● In C++, pointers can be manipulated directly as memory address
values. Java references are pointers to objects.[11] Java references do
not allow direct access to memory addresses or allow memory
addresses to be manipulated with pointer arithmetic. In C++ one can
construct pointers to pointers, pointers to ints and doubles, and
pointers to arbitrary memory locations. Java references only access
objects, never primitives, other references, or arbitrary memory
locations. In Java, memory can be read and written by arbitrary
values using the sun.misc.Unsafe API, however it is deprecated and
not recommended.
● In C++, pointers can point to functions or member functions (function
pointers). The equivalent mechanism in Java uses object or interface
references.
● Via stack-allocated objects, C++ supports scoped resource
management, a technique used to automatically manage memory
and other system resources that supports deterministic object
destruction. While scoped resource management in C++ cannot be
guaranteed (even objects with proper destructors can be allocated
using new and left undeleted) it provides an effective means of
resource management. Shared resources can be managed using
shared_ptr, along with weak_ptr to break cyclic references. Java
supports automatic memory management using garbage collection
which can free unreachable objects even in the presence of cyclic
references, but other system resources (files, streams, windows,
communication ports, threads, etc.) must be explicitly released
because garbage collection is not guaranteed to occur immediately
after the last object reference is abandoned.
● C++ features user-defined operator overloading. Operator
overloading allows for user-defined types to support operators
(arithmetic, comparisons, etc.) like primitive types via user-defined
implementations for these operators. It is generally recommended to
preserve the semantics of the operators. Java supports no form of
operator overloading (although its library uses the addition operator
for string concatenation).
● Java features standard application programming interface (API)
support for reflection and dynamic loading of arbitrary new code.
● C++ supports static and dynamic linking of binaries.
● Java has generics, whose main purpose is to provide type-safe
containers. C++ has compile-time templates, which provide more
extensive support for generic programming and metaprogramming.
Java has annotations, which allow adding arbitrary custom metadata
to classes and metaprogramming via an annotation processing tool.
● Both Java and C++ distinguish between native types (also termed
fundamental or built-in types) and user-defined types (also termed
compound types). In Java, native types have value semantics only,
and compound types have reference semantics only. In C++ all types
have value semantics, but a reference can be created to any type,
which will allow the object to be manipulated via reference
semantics.
● C++ supports multiple inheritance of arbitrary classes. In Java a class
can derive from only one class, but a class can implement multiple
interfaces (in other words, it supports multiple inheritance of types,
but only single inheritance of implementation).
● Java explicitly distinguishes between interfaces and classes. In C++,
multiple inheritance and pure virtual functions make it possible to
define classes that function almost like Java interfaces do, with a few
small differences.
● Java has both language and standard library support for multi-
threading. The synchronized keyword in Java provides simple and
secure mutex locks to support multi-threaded applications. Java also
provides robust and complex libraries for more advanced
multithreading synchronization. Only as of C++11 is there a defined
memory model for multi-threading in C++, and library support for
creating threads and for many synchronizing primitives. There are
also many third-party libraries for this.
● C++ member functions can be declared as virtual functions, which
means the method to be called is determined by the run-time type of
the object (a.k.a. dynamic dispatching). By default, methods in C++
are not virtual (i.e., opt-in virtual). In Java, methods are virtual by
default, but can be made non-virtual by using the final keyword (i.e.,
opt-out virtual).
● C++ enumerations are primitive types and support implicit conversion
to integer types (but not from integer types). Java enumerations can
be public static enum{enumName1,enumName2} and are used like
classes. Another way is to make another class that extends
java.lang.Enum<E>) and may therefore define constructors, fields,
and methods as any other class. As of C++11, C++ also supports
strongly-typed enumerations which provide more type-safety and
explicit specification of the storage type.
● Unary operators '++' and '--': in C++ "The operand shall be a
modifiable lvalue. [skipped] The result is the updated operand; it is
an lvalue...",[12] but in Java "the binary numeric promotion mentioned
above may include unboxing conversion and value set conversion. If
necessary, value set conversion {and/or [...] boxing conversion} is
applied to the sum prior to its being stored in the variable.",[13] i.e. in
Java, after the initialization "Integer i=2;", "++i;" changes the
reference i by assigning new object, while in C++ the object is still the
same.
Nupur

Resource management

❖ Java offers automatic garbage collection, which may be bypassed in


specific circumstances via the Real time Java specification. Memory
management in C++ is usually done via constructors, destructors, and
smart pointers. The C++ standard permits garbage collection, but
does not require it. Garbage collection is rarely used in practice.
❖ C++ can allocate arbitrary blocks of memory. Java only allocates
memory via object instantiation. Arbitrary memory blocks may be
allocated in Java as an array of bytes.
❖ Java and C++ use different idioms for resource management. Java
relies mainly on garbage collection, which can reclaim memory, while
C++ relies mainly on the Resource Acquisition Is Initialization (RAII)
idiom. This is reflected in several differences between the two
languages:
➢ In C++ it is common to allocate objects of compound types as local
stack-bound variables which are destroyed when they go out of
scope. In Java compound types are always allocated on the heap
and collected by the garbage collector (except in virtual machines
that use escape analysis to convert heap allocations to stack
allocations).
Hitashri:

➢ C++ has destructors, while Java has finalizers. Both are invoked
before an object's deallocation, but they differ significantly. A C++
object's destructor must be invoked implicitly (in the case of stack-
bound variables) or explicitly to deallocate an object. The
destructor executes synchronously just before the point in a
program at which an object is deallocated. Synchronous,
coordinated uninitializing and deallocating in C++ thus satisfy the
RAII idiom. In Java, object deallocation is implicitly handled by the
garbage collector. A Java object's finalizer is invoked
asynchronously some time after it has been accessed for the last
time and before it is deallocated. Very few objects need finalizers.
A finalizer is needed by only objects that must guarantee some
cleanup of the object state before deallocating, typically releasing
resources external to the JVM. Additionally, finalizers come with
severe performance penalties and significantly increase the time it
takes for objects to be deallocated, so their use is discouraged and
deprecated in Java 9.
➢ With RAII in C++, one type of resource is typically wrapped inside a
small class that allocates the resource upon construction and
releases the resource upon destruction, and provides access to
the resource in between those points. Any class that contains only
such RAII objects does not need to define a destructor since the
destructors of the RAII objects are called automatically as an
object of this class is destroyed. In Java, safe synchronous
deallocation of resources can be performed deterministically using
the try/catch/finally construct.
➢ In C++, it is possible to have a dangling pointer, a stale reference
to an object that has already been deallocated. Attempting to use
a dangling pointer typically results in program failure. In Java, the
garbage collector will not destroy a referenced object.
➢ In C++, it is possible to have uninitialized primitive objects. Java
enforces default initialization.
➢ In C++, it is possible to have an allocated object to which there is
no valid reference. Such an unreachable object cannot be
destroyed (deallocated), and results in a memory leak. In contrast,
in Java an object will not be deallocated by the garbage collector
until it becomes unreachable (by the user program). (Weak
references are supported, which work with the Java garbage
collector to allow for different strengths of reachability.) Garbage
collection in Java prevents many memory leaks, but leaks are still
possible under some circumstances.

Omkar: Libraries
● C++ provides cross-platform access to many features typically
available in platform-specific libraries. Direct access from Java to
native operating systems and hardware functions requires the use of
the Java Native Interface.
Runtime
C++ Java

C++ is compiled directly to machine Java is compiled to byte-code which


code which is then executed the Java virtual machine (JVM) then
directly by the central processing interprets at runtime. Actual Java
unit. implementations do just-in-time
compilation to native machine code.
Alternatively, the GNU Compiler for
Java can compile directly to machine
code.

● Due to its unconstrained expressiveness, low level C++ language


features (e.g. unchecked array access, raw pointers, type punning)
cannot be reliably checked at compile-time or without overhead at
run-time. Related programming errors can lead to low-level buffer
overflows and segmentation faults. The Standard Template Library
provides higher-level RAII abstractions (like vector, list and map) to
help avoid such errors. In Java, low level errors either cannot occur or
are detected by the Java virtual machine (JVM) and reported to the
application in the form of an exception.
● The Java language requires specific behavior in the case of an out-of-
bounds array access, which generally requires bounds checking of
array accesses. This eliminates a possible source of instability but
usually at the cost of slowing execution. In some cases, especially
since Java 7, compiler analysis can prove a bounds check unneeded
and eliminate it. C++ has no required behavior for out-of-bounds
access of native arrays, thus requiring no bounds checking for native
arrays. C++ standard library collections like std::vector, however,
offer optional bounds checking. In summary, Java arrays are "usually
safe; slightly constrained; often have overhead" while C++ native
arrays "have optional overhead; are slightly unconstrained; are
possibly unsafe."

Shubham, Sayantika, Prajwal:Templates vs. generics


Both C++ and Java provide facilities for generic programming, templates and
generics, respectively. Although they were created to solve similar kinds of
problems, and have similar syntax, they are quite different.
C++ Templates Java Generics

Classes, functions, aliases and variables Classes and methods can


can be templated. be genericized.

Parameters can be variadic, of any type, Parameters can be any


integral value, character literal, or a class reference type, including
template. boxed primitive types
(i.e. Integer, Boolean...).

Separate instantiations of the class or One version of the class


function will be generated for each or function is compiled,
parameter-set when compiled. For class works for all type
templates, only the member functions parameters (via type-
that are used will be instantiated. erasure).

Objects of a class template instantiated Type parameters are


with different parameters will have erased when compiled;
different types at run time (i.e., distinct objects of a class with
template instantiations are distinct different type
classes). parameters are the same
type at run time. It
causes a different
constructor. Because of
this type erasure, it is
not possible to overload
methods using different
instantiations of the
generic class.

Implementation of the class or function Signature of the class or


template must be visible within a function from a
translation unit in order to use it. This compiled class file is
usually implies having the definitions in
the header files or included in the sufficient to use it.
header file. As of C++11, it is possible to
use extern templates to separate
compiling of some instantiations.

Templates can be specialized—a Generics cannot be


separate implementation could be specialized.
provided for a particular template
parameter.

Template parameters can have default Generic type parameters


arguments. Pre-C++11, this was allowed cannot have default
only for template classes, not functions. arguments.

Wildcards unsupported. Instead, return Wildcards supported as


types are often available as nested type parameter.
typedefs. (Also, C++11 added keyword
auto, which acts as a wildcard for any
type that can be determined at compile
time.)

No direct support for bounding of type Supports bounding of


parameters, but metaprogramming type parameters with
provides this "extends" and "super"
for upper and lower
bounds, respectively;
allows enforcement of
relationships between
type parameters.

Allows instantiation of an object with Precludes instantiation


the type of the parameter type. of an object with the
type of the parameter
type (except via
reflection).

Type parameter of the class template Type parameter of


can be used for static methods and generic class cannot be
variables. used for static methods
and variables.

Static variables unshared between Static variables shared


classes and functions of different type between instances of
parameters. classes of different type
parameters.

Class and function templates do not Generic classes and


enforce type relations for type functions can enforce
parameters in their declaration. Use of type relationships for
an incorrect type parameter results in type parameters in their
compiling failure, often generating an declaration. Use of an
error message within the template code incorrect type parameter
rather than in the user's code that results in a type error
invokes it. Proper use of templated within the code that
classes and functions is dependent on uses it. Operations on
proper documentation. parameterized types in
Metaprogramming provides these generic code are only
features at the cost of added effort. allowed in ways that can
There was a proposition to solve this be guaranteed to be safe
problem in C++11, so-called Concepts; it by the declaration. This
is planned for the next standard. results in greater type
safety at the cost of
flexibility.

Templates are Turing-complete Generics are also Turing-


complete

/* Miscellaneous
● Java and C++ use different means to divide code into multiple source
files. Java uses a package system that dictates the file name and path
for all program definitions. Its compiler imports the executable class
files. C++ uses a header file source code inclusion system to share
declarations between source files.
● Compiled Java code files are generally smaller than code files in C++
as Java bytecode is usually more compact than native machine code
and Java programs are never statically linked.
● C++ compiling features an added textual preprocessing phase, while
Java does not. Thus some users add a preprocessing phase to their
build process for better support of conditional compiling.
● The sizes of integer types are defined in Java (int is 32-bit, long is 64-
bit), while in C++ the size of integers and pointers is compiler and
application binary interface (ABI) dependent within given constraints.
● Thus a Java program will have consistent behavior across platforms,
whereas a C++ program may require adapting for some platforms,
but may run faster with more natural integer sizes for the local
platform.

Language specification

The C++ language is defined by ISO/IEC 14882, an ISO standard, which is


published by the ISO/IEC JTC1/SC22/WG21 committee. The latest, post-
standardization draft of C++17 is available as well.
The C++ language evolves via an open steering committee called the C++
Standards Committee. The committee is composed of the creator of C++ Bjarne
Stroustrup, the convener Herb Sutter, and other prominent figures, including
many representatives of industries and user-groups (i.e., the stake-holders).
Being an open committee, anyone is free to join, participate, and contribute
proposals for upcoming releases of the standard and technical specifications.
The committee now aims to release a new standard every few years, although
in the past strict review processes and discussions have meant longer delays
between publication of new standards (1998, 2003, and 2011).
The Java language is defined by the Java Language Specification, a book which
is published by Oracle.
The Java language continuously evolves via a process called the Java
Community Process, and the world's programming community is represented
by a group of people and organizations - the Java Community members—
which is actively engaged into the enhancement of the language, by sending
public requests - the Java Specification Requests - which must pass formal and
public reviews before they get integrated into the language.
The lack of a firm standard for Java and the somewhat more volatile nature of
its specifications have been a constant source of criticism by stake-holders
wanting more stability and conservatism in the addition of new language and
library features. In contrast, the C++ committee also receives constant
criticism, for the opposite reason, i.e., being too strict and conservative, and
taking too long to release new versions.

Trademarks

"C++" is not a trademark of any company or organization and is not owned by


any individual. "Java" is a trademark of Oracle Corporation.*/

Completed by me ……don’t repeat


sahil 1 point bolne de muje then tu khatam kkar reply if u read yessssss
Rajan, Sahil: C++ and Java: The Similarities
Java and C++ are similar in their type of programming language, use, and
complexity. Java and C++ can be used to create applications, operating
systems, web browsers, and parts of websites.

They also have a similar syntax, meaning the way they are written is
comparable. Think of this like Portuguese and Spanish – different languages
with some similarities. Java and C++ use the same primitive data types and
many of their keywords are the same, too.

Both C++ and Java are object oriented programming languages. This is a
modular approach to programming that supports:

● Inheritance of objects in classes

● Polymorphism (programs that use a function for more than one


purpose)

● Abstraction (the ability to represent essential features without having to


include background details)

● Encapsulation (allows data and functions to be wrapped into a single


unit)

Shubham, Sayantika: How is Java actually used by


Developers?

Java can be used for a variety of high-level applications. Java is most popularly
used for games, websites, and apps. Across the globe, Java is powering millions
of mobile phones, televisions, enterprise applications, and more.

With Java, you can create:

● Mobile applications, both on Android and Google OS


● Internet of Things (IoT) devices – Java connects devices like mobile
phones, televisions, computers, or tablets to appliances or machines at
home or in industries like healthcare, security, utilities, supply-chain
management, and more.

● Cloud applications, such as storage, file-sharing, virtual machines, sales


software, email, messengers, and more.

● Secure, scalable web applications

● Chatbots

● Internet and Android games, such as Minecraft

● Enterprise applications, such as employee management, reservations,


data storage, file sharing, and more.

● Scientific applications, such as healthcare and research computation,


automation, and data storage.

Nupur, Hitashri: How is C++ Used in the Real World?


From game development to scientific applications and everything in between,
C++ is secretly powering millions of devices we use every day. From computers
to cell phones, video games to space research, you’ll find C++ just about
everywhere.

C++ is used to create:

● Operating systems – MacOS, Windows, iOS

● Game development, such as World of Warcraft, Counter-strike, and


StarCraft.

● Game engines, such as Unreal Engine, Xbox, Playstation, Nintendo


Switch.

● Internet of Things (IoT) devices, such as televisions, cars, smartwatches,


medical devices, appliances, and more.
● Databases, such as MySQL and MongoDB

● Web browsers, such as Google Chrome, Mozilla Firefox, Safari, and


Opera

● Machine learning, such as TensorFlow

● Virtual Reality (VR), such as Unreal Engine

● Scientific research, such as NASA and CERN

● Financial technology, such as trading, banking, financial modeling, etc.

● Flight software, such as military aircraft and commercial jets

● Google Search Engine

● Medical technology, such as MRI machines and data modeling

● Telecommunications, such as telephone, internet, and telecom


infrastructure

● Movie production, such as special effects

Srushti: Should I Learn Java or C++ first?


Most programmers agree that Java is easier to learn first. Java’s syntax is
usually easier for new programmers to understand. The syntax requirements in
C++ are very strict. It is difficult to write C++ in a readable way and making a
single mistake can set off a chain of errors.

Since Java is more versatile, there are many Java job opportunities including
Software Developer, Android Developer, and Web Developer. With
cybersecurity becoming a major concern, learning Java may also be more
relevant to your career goals. Learning C++ is great if you want to become a
Software Developer.

Omkar: The Disadvantages of Java


Java is an incredibly versatile and secure programming language, but, like
every programming language, Java still has some downfalls. For one, Java is not
suitable for low-level programming. Java is also memory-consuming and can be
slower than C++. While C++ works natively (with the language the computer
speaks), Java has to be compiled to be interpreted by the computer.

Java performs automatic garbage collection, meaning the memory is controlled


by the system. While automatic garbage collection can help memory and
redundancy, it does consume more CPU time which can slow the application
down. Along this same vein, Java does not backup data.

For these reasons, Java requires a significant amount of memory and requires
a longer runtime. That can mean that it’s slower. However, if it’s used
appropriately with these hindrances in mind, it can run quickly and efficiently.

Prajwal: The Disadvantages of C++


C++ is great for low-level programming, but C++ also has its own downsides.
Firstly, C++ is not well-suited for larger or high-level programs. Unlike Java, C++
does not support garbage collection (automatic memory management) and
dynamic memory allocation. C++’s lack of support for garbage collection can
result in redundant data storage and an increase in memory use. However,
some applications, like games, need this feature to avoid losing stored states.
C++ is also 8-bit which can save memory and improve speed.

C++ is not secure; pointers are what makes C++ insecure. Improper use of
pointers can easily result in system failure or memory corruption. Debugging
pointers is one of the most difficult aspects of learning C++.

Rajan: Conclusion
So, in conclusion,we would like to mention that both the languages are used by
a plethora of big Software Companies and therefore, learning both of them
could prove to be extremely useful.

For people looking forward to taking a job in the Software Industry, or already
have a Software Engineering Job, it is better to learn more about Java because
of the diversity and flexibility it provides. However, for people looking to work
on building operating systems, gaming engines, etc. where high performance is
needed, C++ can turn out to be a better programming language than Java as it
is way faster than Java.

Reference
● https://www.softwaretestinghelp.com/cpp-applications/
● https://techvidvan.com/tutorials/applications-of-java/
● https://techwelkin.com/difference-between-java-and-cpp
● https://hackr.io/blog/cpp-vs-java
● https://dare2compete.com/blog/difference-between-cpp-and-java
● https://www.javatpoint.com/java-variables
● https://amplitude.com/blog/data-types
● https://www.javatpoint.com/operators-in-java

You might also like