Comparison Metric | C++ | Java |
---|---|---|
Domain and Usage | C++ is mainly used for system programming. | Java is used for mainly used for building desktop, web and Mobile Applications. |
Compiler and Interpreter | In C++ program is only compiled and converted into machine code. That is why it is platform dependent. | In Java , program once compiled converted into bytecode ,then interpreter read the bytecode stream to execute line by line through JVM. That is why it is platform independent. |
Pointers | C++ supports pointers for memory allocation , You can write pointer programs. | Java supports pointer internally , however you can not write pointer programs. |
Structure and Union |
C++ have Structures and Unions. |
Java don’t have these , however you can implement this using classes. |
Thread Support | C++ don’t have inbuilt thread support , you have to use third party library. |
Java has built in thread support. |
Documentation Comment | C++ don’t have documentation comment. | Java have documentation comment , which is useful for maintaining the code. |
Call by value and reference | C++ supports both call by value and call by reference. | Java supports only call by value. |
Operator Overloading | C++ supports operator overloading. | Java don’t have support for operator overloading. |
First Program - "Hello World"
The below-given program is the simplest program of Java printing "Hello World" to the screen. Let us try to understand every bit of code step by step.Hello, World
main
method and source code comments. The following explanation will provide you with a basic understanding of the code:class HelloWorldHelloWorld is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace { and the closing curly brace } .
main
method whose signature is:public static void main(String[] args)Like in C/C++, main method is the entry point for your application and will subsequently invoke all the other methods required by your program.
public: So that JVM can execute the method from anywhere.
static: Main method is to be called without object.
The modifiers public and static can be written in either order.
void: The main method doesn't return anything.
main(): Name configured in the JVM.
String[]: The main method accepts a single argument:
an array of elements of type String.
System.out.println("Hello, World");This line outputs the string "Hello, World" followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. System is a predefined class that provides access to the system, and out is the variable of type output stream that is connected to the console.
/* This is a simple Java program.This is a multiline comment. This type of comment must begin with /* and end with */. For single line you may directly use // as in C/C++.
Call this file "HelloWorld.java". */
Java Basic Console Input/Output
1.Using Buffered Reader Class
This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.GeekOutput:
Geek
2. Using Scanner Class
This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it is also can be used to read input from the user in the command line.GeeksforGeeksOutput:
12
3.4
You entered integer 12
Enter a float
You entered float 3.4
3. Using Console Class
It has been becoming a preferred way for reading user’s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()).Java Identifiers
In programming languages, identifiers are used for identification purpose. In Java, an identifier can be a class name, method name, variable name or a label. For example :public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
MyVariableExamples of invalid identifiers :
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
My Variable // contains a spaceReserved Words
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
How to declare variables?
We can declare variables in java as follows://Declaring float variable
float simpleInterest;
//Declaring and Initializing integer variable
int time = 10, speed = 20;
// Declaring and Initializing character variable
char var = 'h';
Types of variables
There are three types of variables in Java:Student age is : 5In the above program the variable age is local variable to the function StudentAge(). If we use the variable age outside StudentAge() function, the compiler will produce an error as shown in below program.
error: cannot find symbol
" + age);
Marks for first object:As you can see in the above program the variables, engMarks , mathsMarks , phyMarksare instance variables. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of instance variable.
50
80
90
Marks for second object:
80
60
85
class_name.variable_name;
Variables Declaration's rating:4.5
Instance variable Vs Static variable
class Example
{
static int a; //static variable
int b; //instance variable
}
Java Data Types
There are majorly two types of languages. First one is Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types.Example: C,C++, Java. Other, Dynamically typed languages: These languages can receive different data types over time. Ruby, PythonPrimitive data
Primitive data are only single values; they have no special capabilities. There are 8 primitive data typesType | Description | Default | Size | Examples |
---|---|---|---|---|
boolean | true or false | false | 1 bit | true, false |
byte | two's complement integer | 0 | 8 bits | (none) |
char | unicode character | \u0000 | 16 bits | 'a','\n','\u0041' |
short | two's complement integer | 0 | 16 bits | (none) |
int | two's complement integer | 0 | 32 bits | -1,0,1 |
long | two's complement integer | 0 | 64 bits | -1L,0L,1L |
float | IEEE 754 floating point | 0.0 | 32 bits | -1.23e100f,2.45e100f |
double | IEEE 754 floating point | 0.0 | 64 bits | -3.45e300d,4.56e245d |
Hi Geek
126
127
-128
-127
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
a+b = 30
a-b = 10
x+y = ThankYou
a*b = 200
a/b = 2
a%b = 0
Value of c (++a) = 21
Value of c (b++) = 10
Value of c (--d) = 19
Value of c (e--) = 40
Value of !condition =false
variable = value;In many cases assignment operator can be combined with other operators to build a shorter version of statement called Compound Statement. For example, instead of a = a+5 , we can write a += 5.
int a = 5;
a += 5; //a = a+5;
Value of c =10
a,b,e,f = 21,9,20,2
a,b,e,f (using shorthand operators)= 21,9,20,2
variable relation_operator valueSome of the relational operators are-
a == b :false
a < b :false
a <= b :false
a > b :true
a >= b :true
a != b :true
x == y : false
condition==true :true
Enter username:Sher
Enter password:Locked
Welcome user.
condition ? if true : if falseThe above statement means that if the condition evaluates to true, then execute the statements after the '?' else execute the statements after the ':'.
Max of three numbers = 30
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
number shift_op number_of_places_to_shift;
a2 = 1
b>>>2 = 1073741821
Precedence and Associativity of Operators
Precedence and associative rules are used when dealing with hybrid equations involving more than one type of operator. In such cases, these rules determine which part of equation to consider first as there can be many different valuations for the same equation. The below table depicts the precedence of operators in decreasing order as magnitude with top representing the highest precedence and bottom shows lowest precedence.Operators | Associativity | Type |
---|---|---|
++,-- | Right to Left | Unary Postfix |
++,--,+,-,! | Right to Left | Unary Prefix |
/,*,% | Left to Right | Multiplicative |
+,- | Left to Right | Additive |
<,<=,>,>= | Left to Right | Relational |
==,!= | Left to Right | Equality |
/,*,% | Left to Right | Multiplicative |
& | Left to Right | Boolean Logical AND |
^ | Left to Right | Boolean Logical XOR |
| | Left to Right | Boolean Logical OR |
&& | Left to Right | Conditional AND |
|| | Left to Right | Conditional OR |
?: | Right to Left | Conditional |
=,+=,-=,*=,/=,%= | Right to Left | Assignment |
Interesting Questions on Operators
a+b/d = 20
a+b*d-e/f = 219
Value of a(b+c),b(b+1),c = 10,11,0
Concatenation (x+y)= 58
Addition (x+y) = 13
Character p changed to: P
Character P changed to: p
47 deg Celsius in Fahrenheit: 116.6
29 deg Celsius in Fahrenheit: 84.2
24.00
Min. notes to get a sum of 253: 6
if(condition)Here, condition after evaluation will be either true or false. if statement accepts boolean values - if the value is true then it will execute the block of statements under it.
{
// Statements to execute if
// condition is true
}
if(condition)Flow chart:
statement1;
statement2;
// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.
I am Not in if
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
i is smaller than 15
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
i is 20
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
i is greater than 2.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop.i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
Using break as a Form of Goto
Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. Java uses label. A Label is use to identifies a block of code.label:Now, break statement can be use to jump out of target block.
{
statement1;
statement2;
statement3;
.
.
}
break label;Example:
Before the break.
This is after second block.
1 3 5 7 9
Before the return.
while (boolean condition)
{
loop statements...
}
Value of x:1
Value of x:2
Value of x:3
Value of x:4
for (initialization condition; testing condition;Flowchart:
increment/decrement)
{
statement(s)
}
Value of x:2
Value of x:3
Value of x:4
Enhanced For loop
Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in a sequential manner without knowing the index of the currently processed element.for (T element:Collection obj/array)
{
statement(s)
}
Ron
Harry
Hermoine
doFlowchart:
{
statements..
}
while (condition);
Value of x: 21
for (type var : array)is equivalent to:
{
statements using var;
}
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
The highest score is 132
Pitfalls of Loops
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at article.Integer1.main(Integer1.java:9)
Method Declaration
In general, method declarations has six components :max(int x, int y)
Calling a method
The method needs to be called for using its functionality. There can be three situations when a method is called:Sum of two integer values :3
12
30.00
string kayak is a palindrome
string kappa is not a palindrome
11101
Creating, Initializing, and Accessing an Array
type var-name[];An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like array of int type, we can also create an array of other primitive data types like char, float, double..etc or user defined data type(objects of a class).Thus, the element type for the array determines what type of data the array will hold.
OR
type[] var-name;
// both are valid declarationsAlthough the above first declaration establishes the fact that intArray is an array variable, no array actually exists. It simply tells to the compiler that this(intArray) variable will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray.
int intArray[];
or int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
// an array of references to objects of
// the class MyClass (a class created by
// user)
MyClass myClassArray[];
Object[] ao, // array of Object
Collection[] ca; // array of Collection
// of unknown type
Instantiating an Array in Java
When an array is declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:The general form of new as it applies to one-dimensional arrays appears as follows:var-name = new type [size];Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of array variable that is linked to the array. That is, to use new to allocate an array, you must specify the type and number of elements to allocate.
int intArray[]; //declaring arrayOR
intArray = new int[20]; // allocating memory to array
int[] intArray = new int[20]; // combining both statements in one
Array Literal
In a situation, where the size of the array and variables of array are already known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.Implementation:
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
Element at index 0 : 10You can also access java arrays using foreach loops
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.The studentArray contains seven memory spaces each of size of student class in which the address of seven Student objects can be stored.The Student objects have to be instantiated using the constructor of the Student class and their references should be assigned to the array elements in the following way.
Student[] arr = new Student[7]; //student is a user-defined class
Student[] arr = new Student[5];
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
What happens if we try to access element outside the array size?
Compiler throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an illegal index. The index is either negative or greater than or equal to size of array.Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2Output:
at GFG.main(File.java:12)
10
20
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples:int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
2 7 9
3 6 1
7 4 2
Passing Arrays to Methods
sum of array values : 15
Returning Arrays from Methods
As usual, a method can also return an array. For example, below program returns an array from method m1.1 2 3
Cloning of arrays
false
1 2 3
false
true
true
String stringVariableName = "sequence_of_characters";
String str = "Geeks";
String str = "Geeks";
String s = GeeksforGeeks
String s1 = GeeksforGeeks
Creating a String
There are two ways to create string in Java:String s = “GeeksforGeeks”;
String s = new String (“GeeksforGeeks”);
StringBuffer s = new StringBuffer("GeeksforGeeks");
StringBuilder str = new StringBuilder();
str.append("GFG");
public StringJoiner(CharSequence delimiter)
Compare two Strings in Java
Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
str1.equals(str2);
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: false
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : false
Comparing Geeksforgeeks and Geeks : false
str2.equalsIgnoreCase(str1);
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: true
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : true
Comparing Geeksforgeeks and Geeks : false
public static boolean equals(Object a, Object b)
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: null
Input 2: null
Output: true
Comparing Geeksforgeeks and Geeks : false
Comparing Geeks and Geeks : true
Comparing Geeksforgeeks and null : false
Comparing null and null : true
int str1.compareTo(String str2)
Input 1: GeeksforGeeks
Input 2: Practice
Output: -9
Input 1: Geeks
Input 2: Geeks
Output: 0
Input 1: GeeksforGeeks
Input 2: Geeks
Output: 8
Comparing Geeksforgeeks and Practice : -9
Comparing Geeks and Geeks : 0
Comparing Geeksforgeeks and Geeks : 8
Why not to use == for comparison of Strings?
In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two:false
true
Before discussing the concept of string immutability, let's just take a look into the String
class and its functionality a little before coming to any conclusion.
This is how String
works:
String str = "knowledge";
This, as usual, creates a string containing "knowledge"
and assigns it a reference str
. Simple enough? Lets perform some more functions:
// assigns a new reference to the
// same string "knowledge"
String s = str;
Let's see how the below statement works:
str = str.concat(" base");
This appends a string " base"
to str
. But wait, how is this possible, since String
objects are immutable? Well to your surprise, it is.
When the above statement is executed, the VM takes the value of String str
, i.e. "knowledge"
and appends " base"
, giving us the value "knowledge base"
. Now, since String
s are immutable, the VM can't assign this value to str
, so it creates a new String
object, gives it a value "knowledge base"
, and gives it a reference str
.
An important point to note here is that, while the String
object is immutable, its reference variable is not. So that's why, in the above example, the reference was made to refer to a newly formed String
object.
At this point in the example above, we have two String
objects: the first one we created with value "knowledge"
, pointed to by s
, and the second one "knowledge base"
, pointed to by str
. But, technically, we have three String
objects, the third one being the literal "base"
in the concat
statement.
Important Facts about String and Memory usage
What if we didn't have another reference s
to "knowledge"
? We would have lost that String
. However, it still would have existed, but would be considered lost due to having no references.
Look at one more example below
s1 refers to java
What's happening:
String
"java"
and refer s1
to it.String
"java rules"
, but nothing refers to it. So, the second String
is instantly lost. We can't reach it.The reference variable s1
still refers to the original String
"java"
.
Almost every method, applied to a String
object in order to modify it, creates new String
object. So, where do these String
objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.
As applications grow, it's very common for String
literals to occupy large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the "String constant pool".
When the compiler sees a String
literal, it looks for the String
in the pool. If a match is found, the reference to the new literal is directed to the existing String
and no new String
object is created. The existing String
simply has one more reference. Here comes the point of making String
objects immutable:
In the String
constant pool, a String
object is likely to have one or many references. If several references point to same String
without even knowing it, it would be bad if one of the references modified that String
value. That's why String
objects are immutable.
Well, now you could say, what if someone overrides the functionality of String
class? That's the reason that the String
class is marked final
so that nobody can override the behavior of its methods.
2432902008176640000
int a, b;
BigInteger A, B;
a = 54;
b = 23;
A = BigInteger.valueOf(54);
B = BigInteger.valueOf(37);
A = new BigInteger(“54”);
B = new BigInteger(“123456789123456789”);
A = BigInteger.ONE;
// Other than this, available constant are BigInteger.ZERO
// and BigInteger.TEN
int c = a + b;
BigInteger C = A.add(B);
String str = “123456789”;
BigInteger C = A.add(new BigInteger(str));
int val = 123456789;
BigInteger C = A.add(BigIntger.valueOf(val));
int x = A.intValue(); // value should be in limit of int xComparison:
long y = A.longValue(); // value should be in limit of long y
String z = A.toString();
if (a < b) {} // For primitive intActually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values.
if (A.compareTo(B) < 0) {} // For BigInteger
if (A.equals(B)) {} // A is equal to B
// Creating generic integer ArrayList
ArrayList<Integer> arrli = new ArrayList<Integer>();
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5