0% found this document useful (0 votes)
3 views

DishuNotes

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability across platforms and robust security features. It is widely used for mobile, desktop, web applications, and more, supported by a large community of developers. Key features include simplicity, object-orientation, platform independence, and a rich set of libraries and frameworks.

Uploaded by

praveenmukati52
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DishuNotes

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability across platforms and robust security features. It is widely used for mobile, desktop, web applications, and more, supported by a large community of developers. Key features include simplicity, object-orientation, platform independence, and a rich set of libraries and frameworks.

Uploaded by

praveenmukati52
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

java

URL:- https://github.com/meanbypawan/ITEP-5.git

What is a Programming Language?


A programming language is a computer language that is used
by programmers (developers) to communicate with computers. It is a
set of instructions written in any specific language ( C, C++, Java, Python)
to perform a specific task.

What is Java?
Java is a high level, robust, object-oriented and secure and
simple programming language.

Java is a programming language and a platform.

Java was developed by Sun Microsystems (which is now the


subsidiary of Oracle) in the year 1995. James Gosling is known
as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his
team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a


program runs, is known as a platform. Since Java has a runtime
environment (JRE) and API, it is called a platform.

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!
java
Why Use Java?

 Java works on different platforms (Windows, Mac, Linux, Raspberry


Pi, etc.)
 It is one of the most popular programming language in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use.
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to
switch to Java or vice versa.

Features of Java
The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.
java

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10.Multithreaded
11.Distributed
12.Dynamic
java
C++ vs Java
dependent C++ is platform- Java is platform-independent.
dependent.

ainly used
r
C++ is mainly used for
system programming.
java
Java is mainly used for application programming. It is widely used
Windows-based, web-based, enterprise, and mobile applications.

esign Goal C++ was designed for Java was designed and created as an interpreter for printing system
systems and but later extended as a support network computing. It was design
applications to be easy to use and accessible to a broader audience.
programming. It was
an extension of the C
programming
language.

oto C++ supports Java doesn't support the goto statement.


the goto statement.

ultiple C++ supports multiple Java doesn't support multiple inheritance through class. It can
heritance inheritance. achieved by using interfaces in java.

perator C++ supports operator Java doesn't support operator overloading.


verloading overloading.

ointers C++ Java supports pointer internally. However, you can't write the point
supports pointers. You program in java. It means java has restricted pointer support in java.
can write a pointer
program in C++.

ompiler C++ uses compiler Java uses both compiler and interpreter. Java source code is converte
nd only. C++ is compiled into bytecode at compilation time. The interpreter executes th
terpreter and run using the bytecode at runtime and produces output. Java is interpreted that
compiler which why it is platform-independent.
converts source code
into machine code so,
C++ is platform
dependent.

all by Value C++ supports both call Java supports call by value only. There is no call by reference in java.
nd Call by by value and call by
ference reference.

ructure C++ supports Java doesn't support structures and unions.


nd Union structures and unions.

hread C++ doesn't have Java has built-in thread support.


upport built-in support for
threads. It relies on
third-party libraries for
thread support.

ocumentati C++ doesn't support Java supports documentation comment (/** ... */) to crea
n comment documentation documentation for java source code.
comments.
java
First Java Program
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Compilation Flow:

When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.

Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it is visible to
all.
o static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main() method is executed by the JVM, so it
doesn't require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class. We will
discuss the internal working of System.out.println() statement in the coming section.

What happens at compile time?


At compile time, the Java file is compiled by Java Compiler (It does not interact with
OS) and converts the Java code into bytecode.
java

What happens at runtime?


At runtime, the following steps are performed:

Classloader: It is the subsystem of JVM that is used to load class files.

Bytecode Verifier: Checks the code fragments for illegal code that can violate
access rights to objects.

Interpreter: Read bytecode stream then execute the instructions.


java
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.

A variable is the name of a reserved area allocated in memory

It is a combination of "vary + able" which means its value can be changed.

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even
aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared
among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.
java

Class :- class is a template used to create objects and to define object data
types and methods.
 Class is a user define type.
java
 Class is the collection of similar type of objects.
 Once we define a class then we create n number of object.
 Class is a blueprint of object.
Each and everything is a member of the class

Object
A Java object is a member of a Java class. Each object has an identity, a
behavior and a state. The state of an object is stored in fields (variables),
while methods (functions) display the object's behavior. Objects are
created at runtime

 Object is runtime entity.


 Each and every object belongs to the class/factory.
 Object is a real-world entity.
 Object may have certain number of properties or may have certain number
of behavior or may be both.
 If a thing is object, then it must be in existence.

Object which you want to manipulate first thing about that then identify
the properties of the object then identify the behavior of the object then
finally create a factory to form/represent the object.

Method:- A method is a block of code which only runs when it is called.


You can pass data, known as parameters, into a method. Methods are
used to perform certain actions, and they are also known as functions.

 Predefined methods: These are the methods that are already defined in
the Java class libraries and do not need to be created by the developer. For
example, the max() method is present in the Math class in Java.
 User-defined methods: These are the methods that are created by the
developer to perform certain actions according to the requirements. These
methods can have parameters, return values, access modifiers, and
exceptions.
java
Encapsulation
Encapsulation is a wrapping up data and function together into a single unit is
known as encapsulation.
Abstraction
Hiding the unnecessary information from the user and showing only essential
thing.
or
Use something without knowing its background details / functioning.
Inheritance
By using existing thing to develop something new but there should not be any
changes in existing thing.
Polymorphism
One thing has a different implementation is called polymorphism.
or
To achieve more thing from one thing is called polymorphism
java
Identifier Naming Rules Examples
s Type

Class It should start with the public


uppercase letter. class Employee
It should be a noun such {
as Color, Button, System, //code snippet
Thread, etc. }
Use appropriate words,
instead of acronyms.

Interface It should start with the interface Printable


uppercase letter. {
It should be an adjective //code snippet
such as Runnable, }
Remote, ActionListener.
Use appropriate words,
instead of acronyms.

Method It should start with class Employee


lowercase letter. { // method
It should be a verb such void draw()
as main(), print(), { //code snippet
println(). }}
If the name contains
multiple words, start it
with a lowercase letter
followed by an uppercase
letter such as
actionPerformed().

Variable It should start with a class Employee


lowercase letter such as {
java
id, name. // variable
It should not start with the int id;
special characters like & //code snippet
(ampersand), $ (dollar), _ }
(underscore).
If the name contains
multiple words, start it
with the lowercase letter
followed by an uppercase
letter such as firstName,
lastName.
Avoid using one-character
variables such as x, y, z.

Package It should be a lowercase //package


letter such as java, lang. package com.javatp
If the name contains oint;
multiple words, it should class Employee
be separated by dots (.) { //code snippet
such as java.util, }
java.lang.

Constant It should be in uppercase class Employee


letters such as RED, {
YELLOW. //constant
If the name contains static final
multiple words, it should int MIN_AGE = 18;
be separated by an //code snippet
underscore(_) such as }
MAX_PRIORITY.
It may contain digits but
not as the first letter.
java
Java Naming Convention

Java naming convention is a rule to follow as you decide what to


name your identifiers such as class, package, variable, constant,
method, etc.

But, it is not forced to follow. So, it is known as convention not


rule. These conventions are suggested by several Java
communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java


programming language are given according to the Java naming
convention. If you fail to follow these conventions, it may generate
confusion or erroneous code.

Advantage of Naming Conventions in Java

By using standard Java naming conventions, you make your code


easier to read for yourself and other programmers. Readability of
Java program is very important. It indicates that less time is spent
to figure out what the code does.

Naming Conventions of the Different Identifiers

The following table shows the popular conventions used for the
different identifiers.

CamelCase in Java naming conventions

Java follows camel-case syntax for naming the class, interface,


method, and variable.

If the name is combined with two words, the second word will start
with uppercase letter always such as actionPerformed(),
firstName, ActionEvent, ActionListener, etc.
java
Java Package

A java package is a group of similar types of classes, interfaces


and sub-packages.

Package in java can be categorized in two form, built-in package


and user-defined package.

There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using


user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so


that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


java

The package keyword is used to create a package in java.


Java provides two types of packages:

 Built-in packages (packages from the Java API)


 User-defined packages (create your own packages)

Built-in packages include java, lang, awt, javax, swing, net, io, util, sql etc 1
User-defined packages are created by developers to categorize their classes and
interfaces. The package statement should be the first statement in the source file.
Method in Java is a block of code or a collection of statements that performs a
specific task or operation1. A method in Java is also known as a function.

 Predefined methods: These are the methods that are already defined in the
Java class libraries and do not need to be created by the developer. For
example, the max() method is present in the Math class in Java.
java
 User-defined methods: These are the methods that are created by the
developer to perform certain actions according to the requirements. These
methods can have parameters, return values, access modifiers, and
exceptions.

Features of java

3) List the features of Java Programming language.

There are the following features in Java Programming Language.

o Simple: Java is easy to learn. The syntax of Java is based on


C++ which makes easier to write the program in it.

o Object-Oriented: Java follows the object-oriented paradigm


which allows us to maintain our code as the combination of
different type of objects that incorporates both data and
behavior.
java
o Portable: Java supports read-once-write-anywhere approach.
We can execute the Java program on every machine. Java
program (.java) is converted to bytecode (.class) which can be
easily run on every machine.

o Platform Independent: Java is a platform independent


programming language. It is different from other
programming languages like C and C++ which needs a
platform to be executed. Java comes with its platform on
which its code is executed. Java doesn't depend upon the
operating system to be executed.
o Secured: Java is secured because it doesn't use explicit
pointers. Java also provides the concept of ByteCode and
Exception handling which makes it more secured.
o Robust: Java is a strong programming language as it uses
strong memory management. The concepts like Automatic
garbage collection, Exception handling, etc. make it more
robust.
o Architecture Neutral: Java is architectural neutral as it is
not dependent on the architecture. In C, the size of data types
may vary according to the architecture (32 bit or 64 bit) which
doesn't exist in Java.
o Interpreted: Java uses the Just-in-time (JIT) interpreter along
with the compiler for the program execution.
o High Performance: Java is faster than other traditional
interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a
compiled language (e.g., C++).
o Multithreaded: We can write Java programs that deal with
many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy
java
memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
o Distributed: Java is distributed because it facilitates users to
create distributed applications in Java. RMI and EJB are used
for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any
machine on the internet.
o Dynamic: Java is a dynamic language. It supports dynamic
loading of classes. It means classes are loaded on demand. It
also supports functions from its native languages, i.e., C and
C++.
java
Statically Typed Programming Language
Java is an example of a statically typed programming language. In Java, you must
declare the data type of each variable before you can use it in your code.

Memory allocation: - Two type of memory allocation in java


Compile time memory allocation: - If the compiler is able to resolve how much
memory is required by the variable at the time of compilation is called compile
time memory allocation.
Run time memory allocation: -
Runtime memory allocation is the process of allocating memory for variables
and data structures during program execution. It is also known as dynamic
memory allocation or heap memory allocation.
Variable :-Variables are the data containers that save the data values
during Java program execution. Every Variable in Java is assigned a data
type that designates the type and quantity of value it can hold. A variable
is a memory location name for the data.
Type casting: - A process of converting one type of value into another type of
value is called type casting.

4) What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the


computer to run the Java program. JVM acts like a run-time engine
which calls the main method present in the Java code. JVM is the
specification which must be implemented in the computer system.
The Java code is compiled by JVM to be a Bytecode which is
machine independent and close to the native code.
java
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those
programs which are written in other languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK
are platform dependent because the configuration of each OS is different from
each other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing
Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other
files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides


Sun Micro Systems.
java
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.
java
6) How many types of memory areas are allocated by JVM?

Many types:

1. Class(Method) Area: Class Area stores per-class structures


such as the runtime constant pool, field, method data, and the
code for methods.
2. Heap: It is the runtime data area in which the memory is
allocated to the objects
3. Stack: Java Stack stores frames. It holds local variables and
partial results, and plays a part in method invocation and
return. Each thread has a private JVM stack, created at the
same time as the thread. A new frame is created each time a
method is invoked. A frame is destroyed when its method
invocation completes.
4. Program Counter Register: PC (program counter) register
contains the address of the Java virtual machine instruction
currently being executed.
5. Native Method Stack: It contains all the native methods
used in the application.
java
Member
1 static 2. instance
Data member and method
Note:-
Static member can be call with the help of class means there is no need to create
the object to call the static member.
But on the other hand object is required to call the instance member of the class.
Lang – System – out – printStream – println()
Sytem.out.println();
class System {
public static PrintStream out;

}
Class PrintStream {
Public void println()
{

}
java
Concept of OOPs

 Abstraction: It means hiding lower-level details and exposing only the


essential and relevant details to the users. For example, when you drive a
car, you don’t need to know how the engine works internally, you only need
to know how to use the steering wheel, the pedals, and the gear.
 Encapsulation: It means wrapping data and methods into a single unit or
class. It also means restricting access to some of the object’s components by
using access modifiers. For example, a car class can have private fields like
engine, wheels, brakes, etc., and public methods like start(), stop(),
accelerate(), etc.
 Inheritance: It means creating new classes from existing ones by inheriting
their properties and methods. It also allows for code reuse and
polymorphism. For example, a dog class can inherit from an animal class and
have additional properties like breed, color, etc., and methods like bark(),
fetch(), etc.
 Polymorphism:

Same name different parameter is called polymorphism.

It means the ability of an object to take different forms depending on the


context. It can be achieved by using method overriding or overloading. For
example, an animal class can have a method called makeSound(), which can
be overridden by different subclasses like dog, cat, lion, etc., to produce
different sounds.
A Java first program is usually a simple program that prints "Hello, World!" on the
screen. It is often used to introduce the basic syntax and structure of Java and to
test the installation and configuration of Java on your system. Here is an example
of a Java first program with explanation:
// Your First Program
class HelloWorld {
public static void main(String[] args)
{
java
System.out.println("Hello, World!");
}
}
Data type in java application
java
A simple definition of data type is:
A data type is a category of values that can be stored in a variable or an object in a
computer program. It defines the size, range, and operations that can be
performed on the values123. For example, a data type can be a number, a text, a
boolean, or a character123.

Datatype A datatype in Java is a way of specifying the size and type of variable
values. There are two types of datatypes in Java: primitive and non-primitive.
Primitive datatypes are the basic types of data that have no additional
methods. They include boolean, char, byte, short, int, long, float and double. Each
of these types has a different size and range of values.
Non-primitive datatypes are the types of data that are derived from primitive
types or defined by the programmer. They include String, Arrays and Classes. Non-
primitive datatypes can have methods to perform certain operations on their
values.
operator variable constant compilation
java
Int data range (-128 to 127)
java
Operator
(i) Associativity (ii) Precedence (Priority)
L R RL
Operators are used to perform operations on variables and values.

Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.

Operato Name Description Example


r

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from x-y


another

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x / y

% Modulus Returns the division x%y


remainder

++ Increment Increases the value of a ++x


variable by 1

-- Decrement Decreases the value of a --x


variable by 1

Assignment Operators (= += -=)


Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example int x = 10;
java
Logical Operators (&& || !)
Logical operators are used to determine the logic between variables or values:
These operators are used to combine two or more conditions and perform a
logical operation based on the result of the conditions. They are used in decision-
making statements like if-else statements and loops

Operator Name Description Example

&& Logical and Returns true if both statements are x < 5 && x <
true 10

|| Logical or Returns true if one of the statements x < 5 || x < 4


is true

! Logical not Reverse the result, returns false if the !(x < 5 && x <
result is true 10)

Comparison Operators (Relational operator)


Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions.

In Java, operators that perform comparisons of two operands are called Relational
operators. There are a total of six of them:

 == : Compares two operands for equality, e.g., x == y.


 != : Compares two operands for inequality, e.g., x != y.
 >: Checks if one operand is greater than the other, e.g., x > y.
 < : Checks if one operand is less than the other, e.g., x < y.
 = >: Checks if one operand is greater than or equal to the other, e.g., x >= y.
 <= : Checks if one operand is less than or equal to the other, e.g., x <= y.

Java AND Operator Example: Logical && and Bitwise &


java
The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is
true or false.
java
Bitwise Operator
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by
bit OR of input values, i.e., if either of the bits is 1, it gives 1, else
it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)
This operator is a binary operator, denoted by ‘&.’ It returns bit by
bit AND of input values, i.e., if both bits are 1, it gives 1, else it
shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)
java
This operator is a binary operator, denoted by ‘^.’ It returns bit
by bit XOR of input values, i.e., if corresponding bits are different,
it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
java
Bitwise XOR Operation of 5 and 7
0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)
This operator is a unary operator, denoted by ‘~.’ It returns the
one’s complement representation of the input value, i.e., with all
bits inverted, which means it makes every 0 to 1, and every 1 to
0.
Example:
a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)
java
 Unary operator (- ++ -- ~)
 Binary (+ - * / …)
 Ternary (conditional operator)
1. Arithmetic operator(+ - / * %)
2. Relational operator ( < > = <= >= ~=)
3. Logical operator (&& || !)
4. Increment operator(++ --)
5. Assignment (=)
6. Bitwise (& | ! << >> ^ ~)
7. Conditional operator(? :)
8. Shorthand operator (+= -= *= ……)
9. Instance operator
Error : - Exception in thread “main” java.lang.AithmeticException: / by zero at
Test.main(file.java linenumber) runtime error
Floating point divided by zero = infinity

7/2: 3
2/7: 0
-7/2 :-3
7/-2 : -3
7%2 : 1
-7%-2 : -1
2%7 : 2
7.5 %2 : 1.5
7.5/0 : infinity
-7.5/0 : -infinity
7.5%0 : naN

Scanner:-
java
Control Statements In Java, control statements are used to control the flow of a
program. Control statements can be divided into three categories: selection
statements, iteration statements, and jump statements1.

Selection statements execute a piece of code based on some condition. The most
common selection statement is the if statement which determines whether a code
should be executed based on the specified condition2.

Iteration statements execute a piece of code repeatedly until a condition becomes


false. The most common iteration statement is the for loop which executes a block
of code repeatedly for a fixed number of times3.

Jump statements transfer control to another part of the program. The most
common jump statement is the break statement which terminates the loop or
switch statement and transfers control to the statement immediately following the
loop or switch4

Loops in Java

The Java for loop is used to iterate a part of the program several
times. If the number of iteration is fixed, it is recommended to use
for loop.

There are three types of for loops in Java.


java
java
Array :- Array is a collection of similar day type
java
java
Color Color Background
Name code Background Color Color code

\
BLACK u001B[30 BLACK_BACKGROUND \u001B[40m
m

\
RED u001B[31 RED_BACKGROUND \u001B[41m
m

\
GREEN u001B[32 GREEN_BACKGROUND \u001B[42m
m

\
YELLOW_BACKGROUN
YELLOW u001B[33 \u001B[43m
D
m

\
BLUE u001B[34 BLUE_BACKGROUND \u001B[44m
m

\
PURPLE u001B[35 PURPLE_BACKGROUND \u001B[45m
m

\
CYAN u001B[36 CYAN_BACKGROUND \u001B[46m
m

WHITE \ WHITE_BACKGROUND \u001B[47m


u001B[37
java
Color Color Background
Name code Background Color Color code

m
java
Constructor :-

Constructor is the special member of class.


Constructor is responsible to initialize the object.
Constructor is automatically called when object is created.

Super Keyword in Java


The super keyword in Java is a reference variable which is used to
refer immediate parent class object.
Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super
reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance
variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class
constructor.

1) super is used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of
parent class. It is used if parent class and child class have same
fields.
java
Static:-
The static keyword in Java is used for memory management
mainly. We can apply static keyword with variables, methods,
blocks and nested classes. The static keyword belongs to the class
than an instance of the class.

Where static is used


used
 Variable (class level)
 Methods
 Blocks
 Inner class
 Nested class
Not used
 Local variable
 Outside class
Static variable belongs to the class not object
We can access static variable through the class we do not need to the create
object.
Why we use static variable
Static variable is used for memory management.
The static variable gets memory only once in the class area at the time of class
loading.
When a variable is declared as static, then a single copy of variable is created and
shared among all objects at class level.
Class members
 Class related / static (main method)
 Object related / non static
main method can be access without creating object.
java
Final Keyword In Java
The final keyword in java is used to restrict the user. The java
final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final
variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be
initialized in the static block only. We will have detailed learning of
these. Let's first learn the basics of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example of final variable

There is a final variable speedlimit, we are going to change the


value of this variable, but It can't be changed because final
variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
java
Abstract class in Java

A class which is declared with the abstract keyword is known as an


abstract class in Java. It can have abstract and non-abstract
methods (method with the body).

Before learning the Java abstract class, let's understand the


abstraction in Java first.

Abstraction is a process of hiding the implementation details and


showing only functionality to the user.

Inheritance
By using existing thing to develop something new but there should not any
change in existing thing.
Object of one class acquire the properties of another object is called inheritance.
Java using extends keyword to inherent property of another class.
There are three types of inheritance
 Single
 Multilevel
 Hierarichal
Why Code reusability
Interface in Java
An interface in Java is a blueprint of a class. It has static
constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There
can be only abstract methods in the Java interface, not method
body. It is used to achieve abstraction and multiple inheritance in
Java.
In other words, you can say that Java Interface also represents
the IS-A relationship.
java
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an
interface.
Since Java 9, we can have private methods in an interface.
Why use Java interface?
There are mainly three reasons to use interface. They are given
below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple
inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides
total abstraction; means all the methods in an interface are
declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2. // declare constant fields
3. // declare methods that abstract
4. // by default.
5. }
interfaces can have abstract methods and variables. It cannot
have a method body.
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class,
an interface extends another interface, but a class implements
an interface.
java
Java Interface Example
In this example, the Printable interface has only one method, and
its implementation is provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print()
6. {
7. System.out.println("Hello");
8. }
9. public static void main(String args[]){
10. A6 obj = new A6();
11. obj.print(); } }

Anonymous Inner Class


A class can contain another class known as nested class. It's possible to
create a nested class without giving any name. A nested class that doesn't
have any name is known as an anonymous class.
An anonymous class must be defined inside another class. Hence, it is also
known as an anonymous inner class. Its syntax is:

class outerClass {

// defining anonymous class


object1 = new Type(parameterList) {
// body of the anonymous class
};
}

Example 1: Anonymous Class Extending a Class


class Polygon {
java
public void display() {
System.out.println("Inside the Polygon class");
}
}

class AnonymousDemo {
public void createClass() {

// creation of anonymous class extending class


Polygon
Polygon p1 = new Polygon() {
public void display() {
System.out.println("Inside an anonymous
class.");
}
};
p1.display();
}
}

class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}

Java Lambda Expressions


Lambda Expressions were added in Java 8.
A lambda expression is a short block of code which takes in
parameters and returns a value. Lambda expressions are similar
to methods, but they do not need a name and they can be
implemented right in the body of a method.
Syntax
java
The simplest lambda expression contains a single parameter and
an expression:
parameter -> expression

Expressions are limited. They have to immediately return a value,


and they cannot contain variables, assignments or statements
such as if or for. In order to do more complex operations, a code
block can be used with curly braces. If the lambda ex+pression
needs to return a value, then the code block should have
a return statement.
java
Exception Handling in Java is one of the effective means to
handle runtime errors so that the regular flow of the application
can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
What are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which
occurs during the execution of a program, i.e. at run time, that
disrupts the normal flow of the program’s instructions. Exceptions
can be caught and handled by the program. When an exception
occurs within a method, it creates an object. This object is called
the exception object. It contains information about the exception,
such as the name and description of the exception and the state
of the program when the exception occurred.
Major reasons why an exception Occurs
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual
machine (JVM) running out of memory, memory leaks, stack
overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we
should not try to handle errors.
Difference between Error and Exception
Let us discuss the most important part which is the differences
between Error and Exception that is as follows:
 Error: An Error indicates a serious problem that a
reasonable application should not try to catch.
 Exception: Exception indicates conditions that a
reasonable application might try to catch.
Exception Hierarchy
java
All exception and error types are subclasses of the
class Throwable, which is the base class of the hierarchy. One
branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. NullPointerException
is an example of such an exception. Another branch, Error is
used by the Java run-time system(JVM) to indicate errors having
to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.

Java Exception Hierarchy

Types of Exceptions
Java defines several types of exceptions that relate to its various
class libraries. Java also allows users to define their own
exceptions.
java
Exceptions can be categorized in two ways:
1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as
follows:
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java
libraries. These exceptions are suitable to explain certain error
situations.
 Checked Exceptions: Checked exceptions are called
compile-time exceptions because these exceptions are
checked at compile-time by the compiler.
 Unchecked Exceptions: The unchecked exceptions are
just opposite to the checked exceptions. The compiler will
not check these exceptions at compile time. In simple
words, if a program throws an unchecked exception, and
even if we didn’t handle or declare it, the program would
not give a compilation error.
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to
describe a certain situation. In such cases, users can also create
exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling
Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Keyword Description

try The "try" keyword is used to specify a block where


we should place an exception code. It means we
java
can't use try block alone. The try block must be
followed by either catch or finally.
catch The "catch" block is used to handle the exception.
It must be preceded by try block which means we
can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the
necessary code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an
exception.
throws The "throws" keyword is used to declare
exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an
exception. It is always used with method
signature.

IO Or File Handling
In Java, with the help of File Class, we can work with files. This File
Class is inside the java.io package. The File class can be used by
creating an object of the class and then specifying the name of
the file.
Why File Handling is Required?
 File Handling is an integral part of any programming language
as fi2153le handling enables us to store the output of any
particular program in a file and allows us to perform certain
operations on it.
 In simple words, file handling means reading and writing data
to a file.
java
// Importing File Class

import java.io.File;

class GFG {

public static void main(String[] args)

// File name specified

File obj = new File("myfile.txt");

System.out.println("File Created!");

Output
File Created!

File Handling : - File handling defines how we can

Stream :- It is basically sequence of data.


java
Data can be of two types 1) byte 2)Character(unicode).
Java perfoms input and output throw this stream.
It is just abstraction that java provides.
How java implements this streams ?
Java implements there within class heirarchiies in java.io.package.

Difference between object and class

There are many differences between object and class. A list of


differences between object and class are given below:

No Object Class
.

1) Object is an instance of a Class is a blueprint or


java
class. template from which
objects are created.

2) Object is a real world Class is a group of


entity such as pen, laptop, similar objects.
mobile, bed, keyboard,
mouse, chair etc.

3) Object is a physical entity. Class is a logical entity.

4) Object is created Class is declared


through new using class keyword e.g.
keyword mainly e.g. class Student{
Student s1=new Student(); }

5) Object is created many Class is declared once.


times as per requirement.

6) Object allocates memory Class doesn't allocated


when it is created. memory when it is
created.

7) There are many ways to There is only one way to


create object in java such define class in java using
as new keyword, class keyword.
newInstance() method,
clone() method, factory
method and
deserialization.
java
Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction


where we can declare the abstract methods. Abstract class and
interface both can't be instantiated.

But there are many differences between abstract class and


interface that are given below.

Abstract class Interface

1) Abstract class can have Interface can have only


abstract and non- abstract methods. Since Java
abstract methods. 8, it can have default and
static methods also.

2) Abstract class doesn't Interface supports multiple


support multiple inheritance.
inheritance.

3) Abstract class can have Interface has only static and


final, non-final, static final variables.
and non-static variables.

4) Abstract class can Interface can't provide the


provide the implementation of abstract
implementation of class.
interface.

5) The abstract The interface keyword is


keyword is used to declare used to declare interface.
abstract class.

6) An abstract class can An interface can extend


extend another Java class another Java interface only.
java
and implement multiple
Java interfaces.

7) An abstract class can An interface can be


be extended using keyword implemented using keyword
"extends". "implements".

8) A Java abstract Members of a Java interface


class can have class are public by default.
members like private,
protected, etc.

9)Example: Example:
public abstract class public interface Drawable{
Shape{ void draw();
public abstract void draw(); }
}
java
Difference between method overloading and method overriding in java

There are many differences between method overloading and


method overriding in java.

No Method Overloading Method Overriding


.

1) Method overloading is Method overriding is


used to increase the used to provide the specific
readability of the implementation of the
program. method that is already
provided by its super class.

2) Method overloading is Method overriding occurs in


performed within class. two classes that have IS-A
(inheritance) relationship.

3) In case of method In case of method


overloading, parameter overriding, parameter must
must be different. be same.

4) Method overloading is the Method overriding is the


example of compile time example of run time
polymorphism. polymorphism.

5) In java, method Return type must be same


overloading can't be or covariant in method
performed by changing overriding.
return type of the method
only. Return type can be
same or different in
java
method overloading. But
you must have to change
the parameter.
java
2) What are the differences between C++ and Java?
The differences between C++ and Java are given in the following
table.
Comparison Index C++ Java

Platform- C++ is platform- Java is platform-


independe dependent. independent.
nt

Mainly C++ is mainly used Java is mainly used for


used for for system application
programming. programming. It is
widely used in window,
web-based, enterprise
and mobile
applications.

Design C++ was designed for Java was designed and


Goal systems and created as an
applications interpreter for printing
programming. It was systems but later
an extension of C extended as a support
programming network computing. It
language. was designed with a
goal of being easy to
use and accessible to a
broader audience.

Goto C++ supports Java doesn't support


the goto statement. the goto statement.

Multiple C++ supports Java doesn't support


inheritanc multiple inheritance. multiple inheritance
e through class. It can be
java
achieved by interfaces
in java.

Operator C++ Java doesn't support


Overloadi supports operator operator overloading.
ng overloading.

Pointers C++ Java supports pointer


supports pointers. You internally. However,
can write pointer you can't write the
program in C++. pointer program in
java. It means java has
restricted pointer
support in Java.

Compiler C++ uses compiler Java uses compiler and


and only. C++ is compiled interpreter both. Java
Interprete and run using the source code is
r compiler which converted into
converts source code bytecode at
into machine code so, compilation time. The
C++ is platform interpreter executes
dependent. this bytecode at
runtime and produces
output. Java is
interpreted that is why
it is platform
independent.
java
Comparison C++ Java
Index

Call by Value C++ supports Java supports call by


and Call by both call by value value only. There is no
reference and call by call by reference in java.
reference.

Structure C++ supports Java doesn't support


and Union structures and structures and unions.
unions.

Thread C++ doesn't have Java has built-


Support built-in support for in thread support.
threads. It relies
on third-party
libraries for thread
support.

Documentati C++ doesn't Java supports


on comment support documentation
documentation comment (/** ... */) to
comment. create documentation
for java source code.

Virtual C++ supports Java has no virtual


Keyword virtual keyword so keyword. We can
that we can override all non-static
decide whether or methods by default. In
not override a other words, non-static
function. methods are virtual by
default.

unsigned C++ doesn't Java supports unsigned


java
right shift support >>> right shift >>> operator
>>> operator. that fills zero at the top
for the negative
numbers. For positive
numbers, it works same
like >> operator.

Inheritance C++ creates a Java uses a single


Tree new inheritance inheritance tree always
tree always. because all classes are
the child of Object class
in java. The object class
is the root of
the inheritance tree in
java.

Hardware C++ is nearer to Java is not so interactive


hardware. with hardware.

Object- C++ is an object- Java is also an object-


oriented oriented oriented language.
language. However, everything
However, in C (except fundamental
language, single types) is an object in
root hierarchy is Java. It is a single root
not possible. hierarchy as everything
gets derived from
java.lang.Object.
java
35) What are the differences between the constructors and methods?

There are many differences between constructors and methods.


They are given below.

Java Constructor Java Method

A constructor is used to A method is used to expose


initialize the state of an the behavior of an object.
object.
A constructor must not have A method must have a return
a return type. type.
The constructor is invoked The method is invoked
implicitly. explicitly.
The Java compiler provides a The method is not provided
default constructor if you by the compiler in any case.
don't have any constructor
in a class.
The constructor name must The method name may or
be same as the class name. may not be same as class
name.

47) What is the difference between static (class) method and instance
method?

static or class method instance method

1)A method that is declared A method that is not declared


as static is known as the as static is known as the
static method. instance method.
2)We don't need to create The object is required to call
java
the objects to call the static the instance methods.
methods.
3)Non-static (instance) Static and non-static variables
members cannot be both can be accessed in
accessed in the static instance methods.
context (static method,
static block, and static
nested class) directly.
4)For example: public static For example: public void
int cube(int n){ return msg(){...}.
n*n*n;}
java
java

You might also like