Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

Java & C++ Interview

Java is a popular object-oriented programming language originally developed by Sun Microsystems. It can run on many platforms like Windows, Mac OS, and UNIX. The document then discusses key reasons for learning Java like its platform independence and security features. It also defines important Java concepts like the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK) and differences between them. The rest of the document discusses Java programming concepts like classes, objects, methods, variables, arrays, inheritance, and more.

Uploaded by

Ashirbad Nayak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Java & C++ Interview

Java is a popular object-oriented programming language originally developed by Sun Microsystems. It can run on many platforms like Windows, Mac OS, and UNIX. The document then discusses key reasons for learning Java like its platform independence and security features. It also defines important Java concepts like the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK) and differences between them. The rest of the document discusses Java programming concepts like classes, objects, methods, variables, arrays, inheritance, and more.

Uploaded by

Ashirbad Nayak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

JAVA

Java is a high-level programming language originally developed by Sun Microsystems and


released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX

Why to Learn java Programming?

 Object Oriented − In Java, everything is an Object. Java can be easily extended since
it is based on the Object model.
 Platform Independent − Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is distributed over the web
and interpreted by the Virtual Machine (JVM) on whichever platform it is being run
on.
 Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.

JVM- is a virtual machine that enables a computer to run java programs as well as programs
written in other languages and provides run time environment in which java byte code can be
executed.

JRE- Java runtime environment is a software bundle and allows java programs to run. It
provides class libraries and other resources tat a specific java program needs to run.
JDK- Java development kit is a software development kit for making java applications. JDK
Help java developers to code and run java programs.
Difference between JDK, JRE & JVM
 JDK is a software development kit, JRE is a software bundle that allows java program
to run, JVM is an environment for executing byte code.
 JDK is platform dependent, JRE is platform dependenr but JVM is platform
independent.
 JDK contains tools for developing and debugging, JRE contains class libraries and
other supporting files but JVM (see above defn)
Hello Program in Java
public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
}}
Class-The class is a group of similar entities. It is only a logical component and not the
physical entity. For example, if you had a class called “Expensive Cars” it could have objects
like Mercedes, BMW, Toyota, etc. Its properties (data) can be price or speed of these cars.
While the methods may be performed with these cars are driving, reverse, braking etc. A class
can be defined as a template/blueprint that describes the behavior/state that the object of
its type supports.

Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behavior such as wagging their tail, barking, eating. An object is an instance of a
class.

Methods − A method is basically a behavior. A class can contain many methods. It is in


methods where the logics are written, data is manipulated and all the actions are executed.

***In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

 Declaration − A variable declaration with a variable name with an object type.


 Instantiation − The 'new' keyword is used to create the object.
 Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Variables in class- are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in the memory. Therefore, by
assigning different data types to variables, you can store integers, decimals, or characters in
these variables.

Instance Variables –Defined within a class but outside any method. Each object has its
unique set of instance variables. An object's state is created by the values assigned to these
instance variables.

Local Variables- Defined inside method, constructors or blocks.

Class Variables/ Static variables- Declared within a class, outside any method with the static
keyword.

***Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name do not
match, your program will not compile).
Java Identifiers

All Java components require names. Names used for classes, variables, and methods are
called identifiers.

Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers −

 Access Modifiers − default, public , protected, private


 Non-access Modifiers − final, abstract, strictfp

Java Arrays-

Arrays are objects that store multiple variables of the same type or collection of similar type
of elements that have contiguous memory locations . However, an array itself is an object on
the heap.

Constructors-

Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor. Every class has a constructor. If we do not explicitly write a constructor for a
class, the Java compiler builds a default constructor for that class.

Parameterized Constructors- Constructor that accepts one or more parameters.

Copy Constructors- Constructor that executes a new object using an existing object of the
same class and initializes each instance variable of the newly created object with
corresponding instance variables of the existing object passed as argument.

Default constructor- If no constructor have been defined for the class java compiler inserts it.

***There are two data types available in Java −

 Primitive Data Types


 Reference/Object Data Types
Primitive Data Types

Primitive datatypes are predefined by the language and named by a keyword EX- byte, short,
int long, float, double, Boolean(true or false) , char

Reference Datatypes

 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under reference datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any
compatible type.
 Example: Animal animal = new Animal("giraffe");

Operators- Special type of symbols that is used to perform operations.

 Arithmetic Operators- Addition, Subtraction, Multiplication, Division, Increment,


decrement
 Relational Operators- == (equal to), != (not equal to), > (greater than), < (less than), >=
(greater than or equal to), <= (less than or equal to)
 Bitwise Operators- & (bitwise and), | (bitwise or), ^ (bitwise XOR), ~ (bitwise compliment)
 Logical Operators- && (logical and), || (logical or), ! (logical not)
 Assignment Operators- =, +=, -=, *=, /=, %=, &-, ^=, |=

A loop statement allows us to execute a statement or group of statements


multiple times. EX-

FOR LOOP- Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

WHILE LOOP- Repeats a statement or group of statements while a given condition is true.
It tests the condition before executing the loop body.

DO-WHILE LOOP- Like a while statement, except that it tests the condition at the end of
the loop body.

Decision making structures have one or more conditions to be evaluated or tested by


the program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
Nested IF ELSE- You can use one if or else if statement inside another if or else if
statement(s).
Method Overloading

When a class has two or more methods by the same name but different parameters, it is
known as method overloading.

Method Overriding
In overriding, a method has the same method name, type, number of parameters, etc. Declaring a
method in the sub class which is already present in the parent class.

Java – Inheritance

In Java, classes can be derived from classes. Basically, if you need to create a new class and
here is already a class that has some of the code you require, then it is possible to derive your
new class from the already existing code.

This concept allows you to reuse the fields and methods of the existing class without having
to rewrite the code in a new class. In this scenario, the existing class is called the superclass
and the derived class is called the subclass.

Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another class. The class which inherits the properties of other is known as
subclass (derived class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).

Extends Keyword

Extends is the keyword used to inherit the properties of a class.

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Single Inheritance: refers to a child and parent class relationship where a class extends the
another class.

Multilevel inheritance: refers to a child and parent class relationship where a class extends
the child class. For example class A extends class B and class B extends class C.

Hierarchical inheritance: refers to a child and parent class relationship where more than one
classes extends the same class. For example, class B extends class A and class C extends
class A.

Multiple Inheritance: refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. Java doesn’t support multiple inheritance,
What is object-oriented programming?
Object-oriented programming combines a group of variables (properties) and functions
(methods) into a unit called an object. These objects are organized into classes where
individual objects can be grouped together. OOP can help you consider objects in a program's
code and the different actions that could happen in relation to the objects. Object-oriented
programming System(OOPs) is a programming paradigm based on the concept of “objects”
that contain data and methods. OBJECT ORIENTED PROGRAMMING (OOP) is a
programming concept that works on the principles of abstraction, encapsulation, inheritance,
and polymorphism. It allows users to create the objects that they want and then, create
methods to handle those objects. The basic concept of OOPs is to create objects, re-use them
throughout the program, and manipulate these objects to get results.

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines. If you are creating class, you
are doing encapsulation i.e. a java class is the example of encapsulation.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing. For example, when you login to your bank
account online, you enter your user_id and password and press login, what happens when you
press login, how the input data sent to server, how it gets verified is all abstracted away from
the you.

In Java, we use abstract class and interface to achieve abstraction.

Inheritance

The process by which one class acquires the properties and functionalities of another class is
called inheritance. When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to


convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc. In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
TYPES OF POLYMERPHISM-

1) Static Polymorphism
2) Dynamic Polymorphism

Static Polymorphism:

Polymorphism that is resolved during compiler time is known as static polymorphism.


Method overloading can be considered as static polymorphism example.

Dynamic Polymorphism:

It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which


a call to an overridden method is resolved at runtime rather, that’s why it is called runtime
polymorphism.

Key Differences Between C++ Vs Java

#1) Platform Independence

C++ Java

C++ is a platform dependent language. Java is platform-independent.


The source code written in C++ needs to be Once compiled into byte code, it can be
compiled on every platform. executed on any platform.

#2) Compiler and Interpreter

C++ Java

C++ is a compiled language. Java is a compiled as well as an interpreted


The source program written language.
in C++ is compiled into an object code which can The compiled output of a Java source code is a
then be executed to produce an output. byte code which is platform-independent.

#3) Portability

C++ Java

C++ code is not portable. Java, however, translates the code into byte code.
It must be compiled for each This byte code is portable and can be executed on any
platform. platform.

#4) Memory Management


C++ Java

Memory management in C++ is manual.


In Java the memory management is
We need to allocate/deallocate memory manually using the
system-controlled.
new/delete operators.

#5) Multiple Inheritance

C++ Java

C++ supports various types of inheritances including single


and multiple inheritances. Java, supports only single inheritance.
Although there are problems arising from multiple Effects of multiple inheritance can be
inheritances, C++ uses the virtual keyword to resolve the achieved using the interfaces in Java.
problems.

#6) Overloading

C++ Java

In Java, only method overloading is


In C++, methods and operators can be overloaded. This is static allowed.
polymorphism. It does not allow operator
overloading.

#7) Pointers

C++ Java

Java has limited support for pointers.


C++ is all about pointers. Initially, Java was completely without pointers
As seen in tutorials earlier, C++ has strong support for but later versions started providing limited
pointers and we can do a lot of useful programming support for pointers.
using pointers. We cannot use pointers in Java as leisurely as we
can use in C++.

Java is mainly used for application


Mainly used C++ is mainly used for system programming. It is widely used in window,
for programming. web-based, enterprise and mobile
applications.
C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java
compiled and run using the source code is converted into bytecode at
Compiler and
compiler which converts source compilation time. The interpreter executes
Interpreter
code into machine code so, C++ is this bytecode at runtime and produces output.
platform dependent. Java is interpreted so platform independent

C++
Why to Learn C++?

 C++ is very close to hardware, so you get a chance to work at a low level which gives
you lot of control in terms of memory management, better performance and finally a
robust software development.
 C++ programming gives you a clear understanding about Object Oriented
Programming. You will understand low level implementation of polymorphism when
you will implement virtual tables and virtual table pointers, or dynamic type
identification.
 C++ is one of the every green programming languages and loved by millions of
software developers. If you are a great C++ programmer then you will never sit
without work and more importantly you will get highly paid for your work.
 C++ is the most widely used programming languages in application and system
programming. So you can choose your area of interest of software development.
 C++ really teaches you the difference between compiler, linker and loader, different
data types, storage classes, variable types their scopes etc.

***There are 1000s of good reasons to learn C++ Programming. But one thing for sure,
to learn any programming language, not only C++, you just need to code, and code and
finally code until you become expert.

#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}

C++ is regarded as a middle-level language, as it comprises a combination of both high-level


and low-level language features. C++ is a superset of C, and that virtually any legal C
program is a legal C++ program.

<iostream>

This file defines the cin, cout, cerr and clog objects, which correspond to the standard input
stream, the standard output stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.

Object-Oriented Programming

C++ fully supports object-oriented programming, including the four pillars of object-oriented
development −

 Encapsulation
 Data hiding
 Inheritance
 Polymorphism
***The line int main() is the main function where program execution begins. The next
line return 0; terminates main( ) function and causes it to return the value 0 to the calling
process.

Local Variables

Variables that are declared inside a function or block are local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own.

Global Variables

Global variables are defined outside of all the functions, usually on top of the program. The
global variables will hold their value throughout the life-time of your program. A global
variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration.

A function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.

A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.

A C++ function definition consists of a function header and a function body. Here are
all the parts of a function −

 Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the parameters
of a function. Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define
what the function does.

While calling a function, there are two ways that arguments can be passed
to a function −

Call by value- This method copies the actual value of an argument into the formal parameter
of the function. In this case, changes made to the parameter inside the function have no effect
on the argument.

Call by pointer- This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
Call by reference- This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual argument used in the
call. This means that changes made to the parameter affect the argument.

***By default, C++ uses call by value to pass arguments. In general, this means that
code within a function cannot alter the arguments used to call the function and above
mentioned example while calling max() function used the same method.

What are Pointers?

A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a
pointer variable declaration is −

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you
use for multiplication. However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration −

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

Structure- is another user defined data type which allows you to combine data items of
different kinds.

Structures are used to represent a record, suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book −

 Title
 Author
 Subject
 Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member, for your program.

The keyword public determines the access attributes of the members of the class that follows
it. A public member can be accessed from outside the class anywhere within the scope of the
class object. You can also specify the members of a class as private or protected which we
will discuss in a sub-section.

You might also like