[go: up one dir, main page]

0% found this document useful (0 votes)
15 views55 pages

Unit-1 Oopj (A) PDF

Uploaded by

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

Unit-1 Oopj (A) PDF

Uploaded by

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

UNIT- 1st

Introduction

Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The history of Java
starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc. However, it was best suited for internet programming.
Later, Java technology was incorporated by Netscap.

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.

Java is an Object-Oriented programming language developed by James


Gosling in the early 1990s. The team initiated this project to develop a language
for digital devices such as set-top boxes, television, etc. Originally C++ was
considered to be used in the project but the idea was rejected for several
reasons(For instance C++ required more memory). Gosling endeavoured to alter
and expand C++ however before long surrendered that for making another stage
called Green.

History of Java

Over the period of nearly 30 years, Java has seen many minor and major versions.
Following is a brief explaination of versions of java till date.

Version Date Description


Sr.No.

JDK
1 1995 Initial Draft version
Beta

23
2 JDK 1.0 A stable variant JDK 1.0.2 was termed as JDK 1
Jan
1996

19
Major features like JavaBeans, RMI, JDBC, inner
3 JDK 1.1 Feb
classes were added in this release.
1997

Swing, JIT Compiler, Java


8 Dec
4 JDK 1.2 Modules, Collections were introduced to JAVA and
1998
this release was a great success.

8
HotSpot JVM, JNDI, JPDA, JavaSound and support
5 JDK 1.3 May
for Synthetic proxy classes were added.
2000

Image I/O API to create/read JPEG/PNG image were


6 Feb added. Integrated XML parser and XSLT processor
6 JDK 1.4
2002 (JAXP) and Preferences API were other important
updates.

JDK 1.5 30
Various new features were added to the language
7 or J2SE Sep
like foreach, var-args, generics etc.
5 2004

11 1. notation was dropped to SE and upgrades done to


JAVA
8 Dec JAXB 2.0, JSR 269 support and JDBC 4.0 support
SE 6
2006 added.

Support for dynamic languages added to JVM.


JAVA 7 Jul
9 Another enhancements included string in switch
SE 7 2011
case, compressed 64 bit pointers etc.

18 Support for functional programming added. Lambda


JAVA
10 Mar expressions,streams, default methods, new date-time
SE 8
2014 APIs introduced.

21
JAVA Module system introduced which can be applied to
11 Sep
SE 9 JVM platform.
2017

JAVA 20 Unicode language-tag extensions added. Root


12
SE 10 Mar certificates, threadlocal handshakes, support for heap
2018 allocation on alternate memory devices etc were
introduced.

Dynamic class-file constants,Epsilon a no-op


JAVA 5 Sep garbage collector, local-variable support in lambda
13
SE 11 2018 parameters, Low-overhead heap profiling support
added.

19 Experimental Garbage Collector,Shenandoah: A


JAVA
14 Mar Low-Pause-Time Garbage Collector,
SE 12
2019 Microbenchmark Suite, JVM Constants API added.

17
JAVA Feature added - Text Blocks (Multiline strings),
15 Sep
SE 13 Enhanced Thread-local handshakes.
2019

17 Feature added - Records, a new class type for


JAVA
16 Mar modelling, Pattern Matching for instanceof, Intuitive
SE 14
2020 NullPointerException handling.

15
JAVA Feature added - Sealed Classes, Hidden Classes,
17 Sep
SE 15 Foreign Function and Memory API (Incubator).
2020

16 Feature added as preview - Records, Pattern


JAVA
18 Mar Matching for switch, Unix Domain Socket Channel
SE 16
2021 (Incubator) etc.

Feature added as finalized - Sealed Classes, Pattern


14
JAVA Matching for instanceof, Strong encapsulation of
19 Sep
SE 17 JDK internals by default. New macOS rendering
2021
pipeline etc.

Feature added - UTF-8 by Default, Code Snippets in


22
JAVA Java API Documentation, Vector API (Third
20 Mar
SE 18 incubator), Foreign Function, Memory API (Second
2022
Incubator) etc.

JAVA 20 Feature added - Record pattern, Vector API (Fourth


21
SE 19 Sep incubator), Structured Concurrency (Incubator) etc.
2022

Feature added - Scoped Values (Incubator), Record


21
JAVA Patterns (Second Preview), Pattern Matching for
22 Mar
SE 20 switch (Fourth Preview),Foreign Function &
2023
Memory API (Second Preview) etc.

19 Feature added - String Templates (Preview),


JAVA
22 Sep Sequenced Collections, Generational ZGC, Record
SE 21
2023 Patterns, Pattern Matching for switch etc.

Java Applications

Java has become the most robust programming language because of its
amazing features. Some of its features are platform independence, high
performance, Object orientation, support for automatic garbage
management, and many more.

 Desktop GUI Applications


 Mobile Applications
 Artificial intelligence
 Web applications
 Big Data technology
 Gaming applications
 Business applications
 Embedded systems
 Cloud applications
 Scientific applications

1. Desktop GUI Applications

Desktop applications can be flawlessly designed using Java. APIs like


Swing, Abstract Windowing Toolkit (AWT), and JavaFX provide a
modern way to develop GUI applications. The use of java in desktop
applications offers some fantastic benefits like ease of learning, visual
feedback, simultaneous display of multiple instances, and many more.

2. Mobile Applications

Java is a cross-platform framework that is used to build applications


that run across smartphones and other small -screen devices. As per a
survey it is observed that Java is the second most widely used language
for mobile application development. Mobile applications that are
created using Java include some popular ones like Netflix, Twitter,
Spotify, and many more.
The reason why Java is used to build mobile apps are:
 Helps to write simple code
 Cross-platform functioning
 High compatibility with Kotlin
 High security

3. Artificial Intelligence

Java is one of the best languages for AI projects. Its infrastructure is


well embedded with intelligent software to enhance AI programming.
It has amazing features like better interaction with users, ease of
debugging, easy-to-code features, standard widget tools, and a lot
more. The use of Java just brings perfection to the Artificial
Intelligence process.

4. Web Applications

Java is just perfect for developing web applications because of its


ability to interact with a large number of systems. It allows us to create
dynamic web applications that interact with interfaces. The presence of
JSP, web servers, spring, and Hibernate provides feasibility in the web
development process. There are several advantages of using Java for
web development:
 Presence of a wide range of APIs
 Excellent IDEs and tools
 Reusability of code
 Enhanced security features
and many more.

5. Big Data Technology

It is a software utility designed to analyze and extract information from


complex data structures. It is widely used in other technologies like
deep learning, Machine learning, and Artificial learning. Java is a
viewpoint of Big data. Java is commonly used in ETL applications like
Apatar, Apache Camel, and Apache Kafka which are used to extract
complex information. Further use of Java provides distinguished
features like automatic garbage selection and stack provision system.
All these provide it an edge over other technology and hence Java is
widely used in Big Data Technology.

6. Gaming Applications

Java has proved to be the most desirable option for game development
because of the presence of a wide variety of open-source frameworks.
Popular games like Mission Impossible III, Minecraft, and Asphalt 6
are developed in Java. It supports Dalvik Virtual Machine and
jMonkeyEngine which provides an ace in building 2 Dimensional and
3 Dimensional android games.
7. Business Applications

Java helps us to develop robust applications for business requirements.


It can be used to develop from small-scale applications to big
enterprise solutions. The language is constantly growing and updating
to fulfill the latest business demands. It offers enhanced features like:
 Flexible integration
 Powerful performance in the management of big enterprise
workload
 Cross-platform compatibility
And many more. All these amazing features make Java the most suited
solution for enterprise development.

8. Embedded Systems

It refers to the combination of small units that combine to perform the


collective function for larger systems. Java has proved to be the best
solution to address increasing Software complexity. Today a large
number of developers use Java in embedded systems. Java has a wide
variety of libraries to simplify developers’ lives. These can be simply
reused by embedded applications which enhances productivity to great
extent. Further, the presence of Object -Oriented Programming makes it
easier to develop embedded systems even with minimal experience.
All these features of Java make it easier for developers to manage
complex systems.

9. Cloud Applications

Cloud Computing refers to the on-demand access to computer


resources without direct management by the user. Java has carved its
way into cloud applications. It provides a solution for IT infrastructure
at an affordable cost. Further, it serves as a platform for creating cloud
servers and applications.
10. Scientific Applications

Java has enhanced security features which makes it the best option for
the development of scientific applications. It has served as a powerful
tool in coding complex mathematical operations. The programs are
designed in a highly secure and efficient manner. Some of the most
widely used applications like MATLAB use Java as a component of
the core system.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification


that provides runtime environment in which java bytecode can be
executed.

What is JVM

It is:

1. A specification where working of Java Virtual Machine is


specified. But implementation provider is independent to choose
the algorithm. Its implementation has been provided by Oracle and
other companies.
2. An implementation Its implementation is known as JRE (Java
Runtime Environment).
3. Runtime Instance Whenever you write java command on the
command prompt to run the java class, an instance of JVM is
created.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader,
memory area, execution engine etc.

1) Classloader

Classloader is a subsystem of JVM which is used to load class files.


Whenever we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the


super class of Extension classloader. It loads the rt.jar file which
contains all class files of Java Standard Edition like java.lang
package classes, java.net package classes, java.util package
classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap
and parent classloader of System classloader. It loades the jar files
located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of
Extension classloader. It loads the classfiles from classpath. By
default, classpath is set to current directory. You can change the
classpath using "-cp" or "-classpath" switch. It is also known as
Application classloader.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime


constant pool, field and method data, the code for methods.

3) Stack

Java Stack stores frames. It holds local variables and partial results, and
plays a part in method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is


destroyed when its method invocation completes.

Java Runtime Environment (JRE)

Java Runtime Environment (JRE) is an open-access software


distribution that has a Java class library, specific tools, and a separate
JVM. In Java, JRE is one of the interrelated components in the Java
Development Kit (JDK). It is the most common environment available
on devices for running Java programs. Java source code is compiled
and converted to Java bytecode. If you want to run this bytecode on
any platform, you need JRE. The JRE loads classes check memory
access and get system resources. JRE acts as a software layer on top of
the operating system.

Working of JRE

Java Development Kit (JDK) and Java Runtime Environment (JRE)


both interact with each other to create a sustainable runtime
environment that enables Java-based applications to run seamlessly on
any operating system. The JRE runtime architecture consists of the
following elements as listed:
Now let us briefly about them as follows:
 ClassLoader: Java ClassLoader dynamically loads all the classes
necessary to run a Java program. Because classes are only loaded
into memory whenever they are needed, the JRE uses ClassLoader
will automate this process when needed. During the i nitialization of
the JVM, three classLoaders are loaded:
 Bootstrap class loader
 Extensions class loader
 System class loader

 Bytecode Verifier: The bytecode checker ensures the format and


precision of Java code before passing it to the interpreter. If the
code violates system integrity or access rights, the class is
considered corrupt and will not load.

 Interpreter: After loading the byte code successfully, the Java


interpreter creates an object of the Java virtual machine that allows
the Java program to run natively on the underlying machine.
Difference between JVM, JRE, and JDK
.
 JVM: JVM stands for Java Virtual Machine. JVM is used for
running Java bytecode.Java applications are called WORA (Write
Once Run Anywhere). This means a programmer can develop Java
code on one system and can expect it to run on any other Java-
enabled system without any adjustment. This is all possible because
of JVM.

 JRE: JRE stands for Java Runtime Environment. JRE is made up of


class libraries.

 JDK: JDK stands for Java Development Kit. JDK contains the JRE
with compiler, interpreter, debugger, and other tools. It provides
features to run as well as develop Java Programs.

Structure of Java Program


Java is an object-oriented programming, platform-
independent, and secure programming language that makes it popular.
Using the Java programming language, we can develop a wide variety of
applications. So, before diving in depth, it is necessary to understand
the basic structure of Java program in detail. In this section, we have
discussed the basic structure of a Java program. At the end of this
section, you will able to develop the Hello world Java program, easily.
o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors

Documentation Section

The documentation section is an important section but optional for a


Java program. It includes basic information about a Java program. The
information includes the author's name, date of creation, version,
program name, company name, and description of the program. It
improves the readability of the program.

Package Declaration

The package declaration is optional. It is placed just after the


documentation section. In this section, we declare the package name in
which the class is placed. Note that there can be only one
package statement in a Java program. It must be defined before any
class and interface declaration. It is necessary because a Java class can
be placed in different packages and directories based on the module they
are used

Import Statements

The package contains the many predefined classes and interfaces. If we


want to use any class of a particular package, we need to import that
class. The import statement represents the class stored in the other
package. We use the import keyword to import the class. It is written
before the class declaration and after the package statement.

Interface Section

It is an optional section. We can create an interface in this section if


required. We use the interface keyword to create an interface.
An interface is a slightly different from the class. It contains
only constants and method declarations. Another difference is that it
cannot be instantiated. We can use interface in classes by using
the implements keyword
Class Definition

In this section, we define the class. It is vital part of a Java program.


Without the class, we cannot create any Java program. A Java program
may conation more than one class definition. We use the class keyword
to define the class

Class Variables and Constants

In this section, we define variables and constants that are to be used


later in the program. In a Java program, the variables and constants are
defined just after the class definition. The variables and constants store
values of the parameters

Main Method Class

In this section, we define the main() method. It is essential for all Java
programs. Because the execution of all Java programs starts from the
main() method. In other words, it is an entry point of the class. It must
be inside the class. Inside the main method,

Methods and behavior

In this section, we define the functionality of the program by using


the methods. The methods are the set of instructions that we want to
perform. These instructions execute at runtime and perform the specified
task
Compilation and Execution of a Java Program

Java, being a platform-independent programming language, doesn’t


work on the one-step compilation. Instead, it involves a two-step
execution, first through an OS-independent compiler; and second, in a
virtual machine (JVM) which is custom-built for every operating
system.
The two principal stages are explained below:
1- Compilation
2- Execution

First, the source ‘.java’ file is passed through the compiler, which then
encodes the source code into a machine-independent encoding, known
as Bytecode. The content of each class contained in the source file is
stored in a separate ‘.class’ file. While converting the source code into
the bytecode.

The class files generated by the compiler are independent of the


machine or the OS, which allows them to be run on any system. To
run, the main class file (the class that contains the method main) is
passed to the JVM and then goes through three main stages before the
final machine code is executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
Class Loader

The main class is loaded into the memory bypassing its ‘.class’ file to
the JVM, through invoking the latter. All the other classes referenced
in the program are loaded through the class loader.

Bytecode Verifier

After the bytecode of a class is loaded by the class loader, it has to be


inspected by the bytecode verifier, whose job is to check that the
instructions don’t perform damaging actions. The following are some
of the checks carried out:
 Variables are initialized before they are used.
 Method calls match the types of object references.
 Rules for accessing private data and methods are not violated.
 Local variable accesses fall within the runtime stack.
 The run-time stack does not overflow.

Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is
to convert the loaded bytecode into machine code. When using a JIT
compiler, the hardware can execute the native code, as opposed to
having the JVM interpret the same sequence of bytecode repeatedly
and incurring the penalty of a relatively lengthy translation process.
Features of Java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are
also some excellent features which play an important role in the popularity of
this language. The features of Java are also known as Java buzzwords.

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

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
Simple

Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language

Object-oriented

Java is an object-oriented programming language. Everything in Java is


an object. Object-oriented means we organize our software as a
combination of different types of objects that incorporate both data and
behavior.

Platform Independent

Java is platform independent because it is different from other languages


like C, C++, etc. which are compiled into platform specific machines
while Java is a write once, run anywhere language. A platform is the
hardware or software environment in which a program runs.
Secured

Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

Portable

Java is portable because it facilitates you to carry the Java bytecode to


any platform. It doesn't require any implementation.

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++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++,
etc.

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.
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.

Types of Java Applications

There are four types of Java applications that can be created using Java
programming:

o Standalone Applications: Java standalone applications uses GUI


components such as AWT, Swing, and JavaFX. These components
contain buttons, list, menu, scroll panel, etc. It is also known as
desktop alienations.
o Enterprise Applications: An application which is distributed in
nature is called enterprise applications.
o Web Applications: An applications that run on the server is called
web applications. We use JSP, Servlet, Spring, and Hibernate
technologies for creating web applications.
o Mobile Applications: Java ME is a cross-platform to develop
mobile applications which run across smartphones. Java is a
platform for App Development in Android.
Java Fundamentals

Keywords

 Keywords are the reserved words which are having predefined


meaning in Java.
 All the keywords are defined in lower case and the meaning of
these keywords can’t be modified.
 We cannot use keywords as names for variables, classes, methods,
or as any other identifiers.
 const & goto are the keywords but no implementation available in
Java. You cannot use in Java.
Identifiers

 By the name, it is clear that identifiers are used for identification


purpose.
 Identifiers can be a class name, method name, variable name, or a
label name

Data Types

Data types represent the type of data you want to use and memory
required for that data.
There are two types of data:

 Primitive Data Type


 Non-P rimitive Data Type

Variables

Variable holds the user data. The memory will be allocated for the
variables according to the data type. Value of the variable can be
changed any number of times during the program execution.
Syntax: <data type><var name>; or <data type><var
name>=<value>;
Example: int a; int b=10; String s=”name”; String st; There are two
types of variables based on the data types used to declare the variable:

 Primitive variables
 Reference Variable
OPERATORS

Operators are the symbols that perform the operation on values. These
values are known as operands. There are three types of operators
depending on the number of operands required:

 Unary Operator: Only one operand is required.


 Binary Operator: Two operands required.
 Ternary Operator: Three operands required.

(Programming Structures in Java)

Defining Classes in Java

Java provides a reserved keyword class to define a class. The keyword


must be followed by the class name. Inside the class, we declare
methods and variables.

In general, class declaration includes the following in the order as it


appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter
(capitalized by convention).
4. Superclass (if any): The name of the class's parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
5. Interfaces (if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.

Java Objects

An object in Java is a basic unit of Object-Oriented Programming and


represents real-life entities. Objects are the instances of a class that are
created to use the attributes and methods of a class. A typical Java
program creates many objects, which as you know, interact by
invoking methods. An object consists of :

1. State: It is represented by attributes of an object. It also reflects the


properties of an object.

2. Behavior: It is represented by the methods of an object. It also


reflects the response of an object with other objects.

3. Identity: It gives a unique name to an object and enables one object


to interact with other objects.
Difference between Java Class and Objects

The differences between class and object in Java are as follows:


Class Object

Class is the blueprint of an


An object is an instance of the
object. It is used to create
class.
objects.

No memory is allocated when a Memory is allocated as soon as an


class is declared. object is created.

A class is a group of similar An object is a real-world entity


objects. such as a book, car, etc.

Class is a logical entity. An object is a physical entity.

A class can only be declared Objects can be created many times


once. as per requirement.

An example of class can be a Objects of the class car can be


car. BMW, Mercedes, Ferrari, etc.
Java Constructors

In Java, a constructor is a block of codes similar to the method. It is


called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one
constructor is called.

It calls a default constructor if there is no constructor available in the


class. In such case, Java compiler provides a default constructor by
default.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor
2. Parameterized constructor
1. Default Constructor
A constructor that has no parameters is known as default the
constructor. A default constructor is invisible. And if we write a
constructor with no arguments, the compiler does not create a default
constructor. It is taken out. It is being overloaded and called a
parameterized constructor. The default constructor changed into the
parameterized constructor. But Parameterized constructor can’t change
the default constructor.

1. //Java Program to create and call a default constructor


2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10.}

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized


constructor. If we want to initialize fields of the class with our own
values, then use a parameterized constructor.

1. //Java Program to demonstrate the use of the parameterized constructor.


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21.}

Method in Java
A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. It is used to
achieve the reusability of code. We write a method once and use it
many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding
or removing a chunk of code. The method is executed only when we call
or invoke it.

The method in Java or Methods of Java is a collection of statements


that perform some specific tasks and return the result to the caller. A
Java method can perform some specific tasks without returning
anything. Java Methods allows us to reuse the code without retyping
the code. In Java, every method must be part of some class that is
different from languages like C, C++, and Python.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method
Predefined Method

In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some
pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
When we call any of the predefined methods in our program, a series of
codes related to the corresponding method runs in the background that is
already stored in the library.

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }

User-defined Method

The method written by the user or programmer is known as a user-


defined method. These methods are modified according to the
requirement.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }

Difference Between the Constructor and the Method in Java

Constructors Methods

A Constructor is a block of code A Method is a collection of


that initializes a newly created statements which returns a value
object. upon its execution.

A Constructor can be used to A Method consists of Java code


initialize an object. to be executed.

A Constructor is invoked A Method is invoked by the


implicitly by the system. programmer.

A Constructor is invoked when a


A Method is invoked through
object is created using the
method calls.
keyword new.

A Constructor doesn’t have a A Method must have a return


return type. type.

A Constructor initializes a object A Method does operations on an


Constructors Methods

that doesn’t exist. already created object.

A Constructor’s name must be A Method’s name can be


same as the name of the class. anything.

A class can have many A class can have many methods


Constructors but must not have but must not have the same
the same parameters. parameters.

A Constructor cannot be A Method can be inherited by


inherited by subclasses. subclasses.

Access Modifiers in Java

in Java, Access modifiers help to restrict the scope of a class,


constructor, variable, method, or data member. It provides security,
accessibility, etc to the user depending upon the access modifier used
with the element. Let us learn about Java Access Modifiers, their
types, and the uses of access modifiers in this article.

Types of Access Modifiers in Java


There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class


contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-time
error.

1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

2) Default

If you don't use any modifier, it is treated as default by default. The


default modifier is accessible only within package. It cannot be accessed
from outside the package. It provides more accessibility than private.
But, it is more restrictive than protected, and public.

1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

3) Protected

The protected access modifier is accessible within package and outside


the package but through inheritance only.

The protected access modifier can be applied on the data member,


method and constructor. It can't be applied on the class.
It provides more accessibility than the default modifer.

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }

4) Public

The public access modifier is accessible everywhere. It has the widest


scope among all other modifiers.

1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Static Keyword in Java

The static keyword in Java is mainly used for memory management.


The static keyword in Java is used to share the same variable or
method of a given class. The users can apply static keywords with
variables, methods, blocks, and nested classes. The static keyword
belongs to the class than an instance of the class. The static keyword is
used for a constant variable or a method that is the same for every
instance of a class.

The static keyword is a non-access modifier in Java that is


applicable for the following:

1. Blocks
2. Variables
3. Methods
4. Classes
Static blocks
If you need to do the computation in order to initialize your static
variables, you can declare a static block that gets executed exactly
once, when the class is first loaded.
Consider the following java program demonstrating the use of static
blocks.

Static variables

When a variable is declared as static, then a single copy of the variable


is created and shared among all objects at the class level. Static
variables are, essentially, global variables. All instances of the class
share the same static variable.

Static methods

When a method is declared with the static keyword, it is known as the


static method. The most common example of a static method is
the main( ) method. As discussed above, Any static member can be
accessed before any objects of its class are created, and without
reference to any object. Methods declared as static have several.

Static Classes
A class can be made static only if it is a nested class. We cannot
declare a top-level class with a static modifier but can declare nested
classes as static. Such types of classes are called Nested static classes.
Nested static class doesn’t need a reference of Outer class. In this case,
a static class cannot access non-static members of the Outer class.
Final Members/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.

Comments in Java

In a program, comments are like indents one makes, they are used so
that it is easier for someone who isn’t familiar with the language to be
able to understand the code. It will also make the job easier for you, as
a coder, to find errors in the code since you will be easily able to find
the location of the bug. Comments are ignored by the compiler while
compiling a code, which makes the job more complex in the long run
when they have to go through so much code to find one line .

In Java there are three types of comments:

1. Single-line comments.
2. Multi-line comments.
3. Documentation comments.
1) Java Single Line Comment

The single-line comment is used to comment only one line of the code.
It is the widely used and easiest way of commenting the statements.

Single line comments starts with two forward slashes (//). Any text in
front of // is not executed by Java.

1. public class CommentExample1 {


2. public static void main(String[] args) {
3. int i=10; // i is a variable with value 10
4. System.out.println(i); //printing the variable i
5. }
6. }
2) Java Multi Line Comment

The multi-line comment is used to comment multiple lines of code. It


can be used to explain a complex code snippet or to comment multiple
lines of code at a time (as it will be difficult to use single-line comments
there).

Multi-line comments are placed between /* and */. Any text between /*
and */ is not executed by Java.

1. public class CommentExample2 {


2. public static void main(String[] args) {
3. /* Let's declare and
4. print variable in java. */
5. int i=10;
6. System.out.println(i);
7. /* float j = 5.9;
8. float k = 4.4;
9. System.out.println( j + k ); */
10. }
11. }

3) Java Documentation Comment

Documentation comments are usually used to write large programs for a


project or software application as it helps to create documentation API.
These APIs are needed for reference, i.e., which classes, methods,
arguments, etc., are used in the code.

To create documentation API, we need to use the javadoc tool. The


documentation comments are placed between /** and */.
Data Types in Java
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean,


char, byte, short, int, long, float and double.

2. Non-primitive data types: The non-primitive data types


include Classes, Interfaces, and Arrays.
Variable

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


words, it is a name of the memory location. It is a combination of "vary
+ able" which means its value can be changed.

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


program is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of


variables in java: local, instance and static.

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.
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example:
+, -, *, / etc.

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

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

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof


equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Control Flow in Java

Java compiler executes the code from top to bottom. The statements in
the code are executed according to the order in which they appear.
However, Java provides statements that can be used to control the flow
of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow
of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop

3. Jump statements
o break statement
o continue statement

Decision-Making statements
As the name suggests, decision-making statements decide which
statement to execute and when. Decision-making statements evaluate the
Boolean expression and control the program flow depending upon the
result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of


the program is diverted depending upon the specific condition. The
condition of the If statement gives a Boolean value, either true or false.
In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java.
It evaluates a Boolean expression and enables the program to enter a
block of code if the expression evaluates to true.

2) if-else statement

The if-else statement is an extension to the if-statement, which uses


another block of code, i.e., else block. The else block is executed if the
condition of the if-block is evaluated as false.

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple


else-if statements. In other words, we can say that it is the chain of if-
else statements that create a decision tree where the program may enter
in the block of code where the condition is true. We can also define an
else statement at the end of the chain.

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-


else statement inside another if or else-if statement.
Switch Statement
In Java, Switch statements are similar to if-else-if statements. The switch
statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched. The switch statement
is easier to use instead of if-else-if statements. It also enhances the readability
of the program.

Loop Statements
In programming, sometimes we need to execute the block of code
repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated order.
The execution of the set of instructions depends upon a particular
condition.

In Java, we have three types of loops that execute similarly. However,


there are differences in their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }
while loop
The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it is
recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop statement in while
loop.

1. while(condition){
2. //looping statements
3. }

do-while loop
The do-while loop checks the condition at the end of the loop after executing
the loop statements. When the number of iteration is not known and we have
to execute the loop at least once, we can use do-while loop.

1. do
2. {
3. //statements
4. } while (condition);

Jump Statements
Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the
execution control to the other part of the program. There are two types
of jump statements in Java, i.e., break and continue .
break statement
As the name suggests, the break statement is used to break the current flow
of the program and transfer the control to the next statement outside a loop
or switch statement. However, it breaks only the inner loop in the case of the
nested loop.

continue statement

Unlike break statement, the continue statement doesn't break the loop,
whereas, it skips the specific part of the loop and jumps to the next iteration
of the loop immediately.

String Array in Java


An Array is an essential and most used data structure in Java. It is one of
the most used data structure by programmers due to its efficient and
productive nature; The Array is a collection of similar data type
elements. It uses a contiguous memory location to store the elements.

A String Array is an Array of a fixed number of String values. A


String is a sequence of characters. Generally, a string is an immutable
object, which means the value of the string can not be changed. The
String Array works similarly to other data types of Array.

Consider the below points about the String Array:

o It is an object of the Array.


o It can be declared by the two methods; by specifying the size or
without specifying the size.
o It can be initialized either at the time of declaration or by
populating the values after the declaration.
o The elements can be added to a String Array after declaring it.
o The String Array can be iterated using the for loop.
o The searching and sorting operation can be performed on the
String Array.

Adding Elements to a String Array

We can easily add the elements to the String Array just like other data
types. It can be done using the following three methods:

o Using Pre-Allocation of the Array


o Using the Array List
o By creating a new Array

Using Pre-Allocation of the Array:

In this method, we already have an Array of larger size. For example, if


we require to store the 10 elements, then we will create an Array of size
20. It is the easiest way to expand the Array elements.

Using ArrayList:

The ArrayList is a fascinating data structure of the Java collection


framework. We can easily add elements to a String Array using an
ArrayList as an intermediate data structure.
By Creating a New Array:

In this method, we will create a new Array with a larger size than the
initial Array and accommodate the elements in it. We will copy all the
elements to the newly added Array.

You might also like