0% found this document useful (0 votes)
16 views90 pages

Java Unit 1

The document provides a comprehensive overview of the history, features, and applications of the Java programming language, originally developed by James Gosling and his team in the early 1990s. It details the evolution of Java, its object-oriented programming concepts, and its various platforms, including Java SE, EE, ME, and JavaFx. Additionally, it explains key OOP principles such as encapsulation, inheritance, and abstraction, as well as the significance of Java in modern programming and its widespread use across different applications.

Uploaded by

Manesh Patel
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)
16 views90 pages

Java Unit 1

The document provides a comprehensive overview of the history, features, and applications of the Java programming language, originally developed by James Gosling and his team in the early 1990s. It details the evolution of Java, its object-oriented programming concepts, and its various platforms, including Java SE, EE, ME, and JavaFx. Additionally, it explains key OOP principles such as encapsulation, inheritance, and abstraction, as well as the significance of Java in modern programming and its widespread use across different applications.

Uploaded by

Manesh Patel
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/ 90

MANESH PATEL

PRESIDENT INSTITUTE OF COMPUTER APPLICAION COLLEGE, SHAYONA CAMPUS, KADI

BCA SEM: 3 JAVA - Unit – 1 JAVA

History of Java
 The history of Java is very interesting.
 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.
 It was best suited for internet programming.
 Later, Java technology was incorporated by Netscape.
 The principles for creating Java programming were "Simple, Robust,
Portable, Platform-independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic".
 Java was developed by James Gosling, who is known as the father of
Java, in 1995.
 James Gosling and his team members started the project in the early '90s.

 Java is used in internet programming, mobile devices, games, e-business


solutions, etc.
 Following are given significant points that describe the history of Java.

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

PREPARED BY: PATEL MANESH - M.Sc(CA & IT) Contact: 90165 17796 1
PATEL MANESH

2) Initially it was designed for small, embedded systems in electronic appliances


like set-top boxes.

3) Firstly, it was called "Greentalk" (language)by James Gosling, and the file
extension was .gt.

4) After that, it was called Oak (Language) and was developed as a part of the

Green project.
Why Java was named as "Oak"?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by


Oak Technologies.

Why Java Programming named "Java"?


7) Why had they chose the name Java for Java language?

 The team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc.
 They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to
say.

According to James Gosling, "Java was one of the top choices along
with Silk". Since Java was so unique, most of the team members preferred
Java than other names.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 2
PATEL MANESH

8) Java is an island in Indonesia where the first coffee was produced (called Java
coffee). Java name was chosen by James Gosling while having a cup of coffee
nearby his office.

9) Notice that Java is just a name, not an acronym.


10) Initially developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996.

Java Version History


1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (March 2022)
21. Java SE 19 (September 2022)
22. Java SE 20 (March, 21st 2023)
23. Java SE 21 (September, 19th 2023)
24. Java SE 22 (March, 19th 2024)
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 3
PATEL MANESH

 Since Java SE 8 release, the Oracle Corporation follows a


pattern in which every even version is release in March month and
an odd version released in September month.

Java is open source and free language.


What is Java and why we use Java Language
 Java is a popular programming language, created in 1995.
 Java is a widely-used programming language for coding web applications.
 James Gosling and his team developed the Java platform at Sun
Microsystems, and the Oracle Corporation later acquired it.
 Java is a programming language and a platform.
 Java is a high level, robust, secured and object-oriented programming
language.
 Platform: Any hardware or software environment in which a program runs,
is known as a platform.
 Since Java has its own runtime environment (JRE) and API, it is called
platform.
 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
 Java is an object oriented language which gives a clear structure to
programs and allows code to be reused.
 As Java is close to C++ and C#, it makes it easy for programmers to switch
to Java or vice versa

Where it is used?
 There are many devices where Java is currently used.
 Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus etc.


2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 4
PATEL MANESH

4. Mobile Application
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

Java Platforms / Editions


There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

 It is a java programming platform.


 It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc.
 It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection etc.

2) Java EE (Java Enterprise Edition)

 It is an enterprise platform which is mainly used to develop web and enterprise


applications.
 It is built on the top of Java SE platform.
 It includes topics like Servlet, JSP, Web Services, EJB, JPA etc.

3) Java ME (Java Micro Edition)

 It is a micro platform which is mainly used to develop mobile applications.

4) JavaFx

 It is used to develop rich internet applications.


 It uses light-weight user interface API.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 5
PATEL MANESH

 Simple Java Program

 To create a simple java program, you need to create a class that contains
main method.
 Let's understand the requirement first.

 Requirement for Hello Java Example


For executing any java program, you need to
o create the java program
o compile and run the java program

Creating hello java example


Let's create the hello java program:

import java.io.*; //import statement

class Demo // class name


{
public static void main(String a[]) // main Method
{
System.out.println("Hello Java"); // println method
}
}

Save this file as Demo.java

To Compile: javac Demo.java

To Run: java Demo

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 6
PATEL MANESH

Java OOPs Concepts


 Object-Oriented Programming is a paradigm that provides many concepts,
such as class, Object, inheritance, data binding, polymorphism,
Abstraction, Encapsulation etc.
 The programming paradigm where everything is represented as an object is
known as a truly object-oriented programming language.
 Smalltalk is considered the first truly object-oriented programming
language.
 The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
 The main aim of object-oriented programming is to implement real-world
entities, for example, object, classes, abstraction, inheritance,
polymorphism, etc.

OOPs (Object-Oriented Programming System)


 Object means a real-world entity such as a pen, chair, table, computer,
watch, etc.
 Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
 It simplifies software development and maintenance by providing some
concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Apart from these concepts, there are some other terms which are used in Object-
Oriented design:

o Coupling
o Cohesion
o Association
o Aggregation
o Composition
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 7
PATEL MANESH

Object
 Object-oriented programming revolves around data.
 The main programming unit of OOP is the object.
 An object is a representation of a real-time entity and consists of data and
methods or functions that operate on data.
 This way, data, and functions are closely bound and data security is ensured.
 In OOP, everything is represented as an object and when programs are
executed, the objects interact with each other by passing messages.
 An object need not know the implementation details of another object for
communicating.
 Any entity that has state and behavior is known as an object. For example, a
chair, pen, table, keyboard, bike, etc. It can be physical or logical.
 An Object can be defined as an instance of a class.
 An object contains an address and takes up some space in memory.
 Objects can communicate.
 The only necessary thing is the type of message accepted and the type of
response returned by the objects.
 Example: A dog is an object because it has states like color, name, breed, etc.
as well as behaviors like wagging the tail, barking, eating, etc.

Class
 Collection of objects is called class. It is a logical entity.
 Class is a combination of data member and member function.
 A class can also be defined as a blueprint from which you can create an
individual object.
 Class doesn't consume any space.
 A class is a blueprint of the object.
 An object can be defined as an instance of a class.
 A class contains a skeleton of the object and does not take any space in the
memory.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 8
PATEL MANESH

Encapsulation
 Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
 For example, a capsule, it is wrapped with different medicines.
 Java class is the example of encapsulation.
 Class is a combination of data member and member function into a single
unit.
 It provides security from unauthorised object.

Abstraction
 Abstraction is the process of hiding irrelevant information from the user.
 Hiding internal details and showing functionality is known as abstraction.
 For example phone call, we don't know the internal processing.
 Using abstraction in programming, we can hide unnecessary details from the
user.
 By using abstraction in our application, the end user is not affected even if we
change the internal implementation.

Inheritance
 We can create a new class from the old class and access all the functionalities
from the parent class to child class, that knowns as inheritance.
 Using inheritance, object of one class can inherit the properties of the object
of another class.
 Inheritance provides reusability of code.
 As such we can design a new class by inherit the properties and functionality
of another class and in this process, we need not modify the functionality of
the parent class.
 We only add new functionality to the class.
 Inheritance is a mechanism of driving a new class from an existing class.
 The existing (old) class is known as base class or super class or parent class.
 The new class is known as a derived class or sub class or child class.
 It allows us to use the properties and behavior of one class (parent) in another
class (child).
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 9
PATEL MANESH

Types of Inheritance
Java supports four types of inheritance:
1. Single inheritance
2. Hierarchical inheritance
3. Multilevel inheritance
4. Hybrid inheritance

Note: Java does not support multiple inheritance.


Interface concept come in Java instead of multiple inheritance.

Why multiple inheritance is not supported in java?


 To reduce the complexity and simplify the language, multiple inheritance is
not supported in java.
 Consider a scenario where A, B, and C are three classes.
 The C class inherits A and B classes.
 If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
 Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes.
 So whether you have same method or different, there will be compile time
error.

Coupling
 Coupling refers to the knowledge or information or dependency of another
class.
 It arises when classes are aware of each other.
 If a class has the details information of another class, there is strong
coupling.
 In Java, we use private, protected, and public modifiers to display the
visibility level of a class, method, and field.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 10
PATEL MANESH

Association
 Association represents the relationship between the objects.
 Here, one object can be associated with one object or many objects.
 There can be four types of association between the objects:

1. One to One
2. One to Many
3. Many to One, and
4. Many to Many

Aggregation
 Aggregation is a way to achieve Association.
 Aggregation represents the relationship where one object contains other
objects as a part of its state.
 It represents the weak relationship between objects.
 It is also termed as a has-a relationship in Java.
 Like, inheritance represents the is-a relationship.
 It is another way to reuse objects.

Composition
 The composition is also a way to achieve Association.
 The composition represents the relationship where one object contains
other objects as a part of its state.
 There is a strong relationship between the containing object and the
dependent object.
 It is the state where containing objects do not have an independent
existence.
 If you delete the parent object, all the child objects will be deleted
automatically.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 11
PATEL MANESH

Features of Java
 There is given many features of java.
 They are also known as java buzzwords.
 The Java Features given below are simple and easy to understand.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 12
PATEL MANESH

Simple
 According to Sun, Java language is simple because:
 syntax is based on C++ (so easier for programmers to learn it after C++).
 removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
 No need to remove unreferenced objects because there is Automatic
Garbage Collection in java.

Object-oriented
 Object-oriented means we organize our software as a combination of
different types of objects that incorporates both data and behaviour.
 Object-oriented programming(OOPs) is a methodology that simplify
software development and maintenance by providing some rules.

Basic concepts of OOPs are:


1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent
 A platform is the hardware or software environment in which a program
runs.
 There are two types of platforms software-based and hardware-based. Java
provides software-based platform.
 The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based
platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 13
PATEL MANESH

 Java code can be run on multiple platforms e.g. Windows, Linux, Sun
Solaris, Mac/OS etc.
 Java code is compiled by the compiler and converted into bytecode.
 This bytecode is a platform-independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere (WORA).

Secured
Java is secured because:
 No explicit pointer
 Java Programs run inside virtual machine sandbox

 Classloader: adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
 Bytecode Verifier: checks the code fragments for illegal code that can
violate access right to objects.
 Security Manager: determines what resources a class can access such as
reading and writing to the local disk.

 These security are provided by java language.


 Some security can also be provided by application developer through SSL,
JAAS, and Cryptography etc.

Robust
 Robust simply means strong.
 Java uses strong memory management.
 There are lack of pointers that avoids security problem.
 There is automatic garbage collection in java.
 There is exception handling and type checking mechanism in java.
 All these points makes java robust.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 14
PATEL MANESH

Architecture-neutral
 There is no implementation dependent features e.g. size of primitive types
is fixed.
 In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture.
 But in java, it occupies 4 bytes of memory for both 32 and 64 bit
architectures.

Portable
 We may carry the java bytecode to any platform.

High-performance
 Java is faster than traditional interpretation since byte code is "close" to
native code still somewhat slower than a compiled language (e.g., C++)

Distributed
 We can create distributed applications in java.
 RMI and EJB are used for creating distributed applications.
 We may access files by calling the methods from any machine on the
internet.

Multi-threaded
 A thread is like a separate program, executing concurrently.
 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 memory for
each thread.
 It shares a common memory area.
 Threads are important for multi-media, Web applications etc.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 15
PATEL MANESH

C++ v/s Java


 There are many differences and similarities between C++ programming
language and Java.
 A list of top differences between C++ and Java are given below:

Comparison C++ Java


Index

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


independent dependent. independent.
Mainly used for C++ is mainly used for Java is mainly used for
system programming. application programming. It
is widely used in Windows-
based, web-based,
enterprise, and mobile
applications.
Design Goal C++ was designed for Java was designed and
systems and applications created as an interpreter for
programming. printing systems.
Go to C++ supports Java doesn't support the goto
the goto statement. statement.
Multiple C++ supports multiple Java doesn't support multiple
inheritance inheritance. inheritance through class. It
supports interfaces.
Operator C++ supports operator Java doesn't support operator
Overloading overloading. overloading.
Pointers C++ supports pointers. Java supports pointer
internally.
You can't write the pointer
program in java.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 16
PATEL MANESH

Compiler and C++ uses compiler only. Java uses both compiler and
Interpreter C++ is compiled and run interpreter.
using the compiler which Java source code is
converts source code into converted into bytecode at
machine code. compilation time. The
interpreter executes this
bytecode at runtime and
produces output.
Call by Value C++ supports both call by Java supports call by value
and Call by value and call by only. There is no call by
reference reference. reference in java.
Structure and C++ supports structures Java doesn't support
Union and unions. structures and unions.
Thread Support C++ doesn't have built-in Java has built-
support for threads. in thread support.

Documentation C++ doesn't support Java supports documentation


comment documentation comment (/** ... */) to create
comments. documentation for java
source code.
Virtual Keyword C++ supports virtual Java has no virtual keyword.
keyword.

Inheritance Tree C++ always creates a Java always uses a single


new inheritance tree. inheritance tree because all
classes are the child of the
Object class in Java. The
Object class is the root of
the inheritance tree in java.
Object-oriented C++ is an object-oriented Java is also an object-
language. oriented language.
o Java doesn't support default arguments like C++.
o Java does not support header files like C++. Java uses the import keyword
to include different classes and methods.
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 17
PATEL MANESH

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 18
PATEL MANESH

import java.io.*;
import java.lang.*;

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 19
PATEL MANESH

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 20
PATEL MANESH

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 21
PATEL MANESH

Command Line Argument in Java


 The java command-line argument is an argument
 i.e. passed at the time of running the java program.
 The arguments passed from the console can be received in the java program
and it can be used as an input.
 So, it provides a convenient way to check the behavior of the program for
the different values.
 You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.

Simple example of command-line argument in java

 In this example, we are receiving only one argument and printing it.
 To run this java program, you must pass at least one argument from the
command prompt.

class CmdExa
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}

compile by > javac CmdExa.java

run by > java CmdExa BCA

Output:

Your first argument is: BCA

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 22
PATEL MANESH

Example of command-line argument that prints all the values


 In this example, we are printing all the arguments passed from the command-
line.
 For this purpose, we have traversed the array using for loop.

import java.io.*;

class CmdExa
{
public static void main(String args[])
{

for(int i=0; i<args.length; i++)


1.
2. System.out.println(args[i]);

}
}

compile by > javac CmdExa.java


run by > java CmdExa Manesh 25 5000

Output:

Manesh
25
5000

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 23
PATEL MANESH

Java Comments
 The Java comments are the statements in a program that are not executed
by the compiler and interpreter.

Why do we use comments in a code?


o Comments are used to make the program more readable by adding the
details of the code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about
the variable, method, class, or any statement.

Types of Java Comments


There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

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.

Syntax: //This is single line comment

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.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 24
PATEL MANESH

Syntax:

/*
This
is
multi line
comment
*/

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

Syntax:

/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 25
PATEL MANESH

Java Improvements

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 26
PATEL MANESH

IDE: Integrated Development Environment


 IDE stands for Integrated Development Environment.
 It is a programming environment that contains a lot of things in a single
package i.e. code editor, compiler, debugger and what you see is what you
get (WYSIWYG).
 It is actually a software application that provides comprehensive facilities
to computer programmers for software development.
 It combines all the basic tools that developers need to write or test software.
 This type of environment allows an application developer to write code
while compiling, debugging and executing it at the same place.
 It can be a standalone application or a part of one or more compatible
applications.
 For example: The IDE for developing .NET applications is Microsoft
Visual Studio and IDE for developing Java Application is Eclipse,
NetBeans, JDeveloper, MyEclipse, BlueJ, RSA etc.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 27
PATEL MANESH

JVM (Java Virtual Machine)


 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.
 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
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 28
PATEL MANESH

Constants
 Constant means fix value that cannot be changed once assigned.
 In Java, the constant values are defined by using the final keyword and
static keyword.
 The final keyword represents that the value of the variable cannot be
changed.
 Note that the identifier name must be in capital letters.
 We can also define constants as static because without object we can
access easily.

Syntax: static final datatype identifier_name=value;

For example: static final double PI = 3.14;

Literals
 In Java, literals are the constant values that appear directly in the program.
 It can be assigned directly to a variable.
 Java has various types of literals.
 The following figure represents a literal.

Types of Literals in Java


There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 29
PATEL MANESH

1. Integer Literals
 Integer literals are sequences of digits.
 There are three types of integer literals:

o Decimal Integer: These are the set of numbers that consist of digits from 0
to 9. It may have a positive (+) or negative (-) Note that between numbers
commas and non-digit characters are not permitted.
o For example, 5678, +657, -89, etc.

int decVal = 26;

o Octal Integer: It is a combination of number have digits from 0 to 7 with a


leading 0.
o For example, 045, 026,

int octVal = 067;

o Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered


as hexadecimal integers. It may also include a character
from a to f or A to F that represents numbers from 10 to 15, respectively.
o For example, 0xd, 0xf,

int hexVal = 0x1a;

o Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you
can create binary literals in Java SE 7 and later).
o Prefix 0b represents the Binary system.
o For example, 0b11010.

int binVal = 0b11010;

Backslash Literals
 Java supports some special backslash character literals known as backslash
literals.
 They are used in formatted output.
 For example:

\n: It is used for a new line


s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 30
PATEL MANESH

\t: It is used for horizontal tab


\b: It is used for blank space
\v: It is used for vertical tab
\a: It is used for a small beep
\r: It is used for carriage return
\': It is used for a single quote
\": It is used for double quotes

Character Literals
 A character literal is expressed as a character or an escape sequence,
enclosed in a single quote ('') mark.
 It is always a type of char.
 For example, 'a', '%', '\u000d', etc.

String Literals
 String literal is a sequence of characters that is enclosed
between double quotes ("") marks.
 It may be alphabet, numbers, special characters, blank space, etc.
 For example, "Jack", "12345", "\n", etc.

Floating Point Literals


 The vales that contain decimal are floating literals.
 In Java, float and double primitive types fall into floating-point literals.
 Keep in mind while dealing with floating-point literals.

o Floating-point literals for float type end with F or f. For example, 6f,
8.354F, etc. It is a 32-bit float literal.
o Floating-point literals for double type end with D or d. It is optional to
write D or d. For example, 6d, 8.354D, etc. It is a 64-bit double literal.
o It can also be represented in the form of the exponent.

Floating: float length = 155.4f; //add f behind float variable.

Decimal: double interest = 99658.445;

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 31
PATEL MANESH

Boolean Literals
 Boolean literals are the value that is either true or false.
 It may also have values 0 and 1.
 For example, true, 0, etc.

boolean ans = true;

How to use literals?


 A literal in Java can be identified with the prefix =, followed by a specific
value.

public class Demo


{
public static void main(String manish[])
{
int no = 100;
float per = 75.45f;
double cost = 34755.123;
int binary = 0b11010;
char c = 'M';
String str = "Java"

System.out.println(no);
System.out.println(per);
System.out.println(cost);
System.out.println(binary);
System.out.println(c);
System.out.println(str);

}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 32
PATEL MANESH

Data Types
 Variables are nothing but reserved memory locations to store values.
 This means that when you create a variable you reserve some space in the
memory.
 Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory.
 By assigning different data types to variables, you can store integers,
decimals, or characters in these variables.

There are two data types available in Java −

1. Primitive Data Types


2. Reference/Object Data Types

Primitive Data Types


 There are eight primitive data types supported by Java.
 Primitive data types are predefined by the language and named by a
keyword.
 Let us now look into the eight primitive data types in detail.

1. byte

 Byte data type is an 8-bit signed two's complement integer


 Minimum value is -128
 Maximum value is 127
 Default value is 0
 Example: byte a = 100, byte b = -50

2. short

 Short data type is a 16-bit signed two's complement integer


 Minimum value is -32,768
 Maximum value is 32,767
 A short is 2 times smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 33
PATEL MANESH

3. int

 int data type is a 32-bit signed


 Minimum value is - 2,147,483,648
 Maximum value is 2,147,483,647
 The default value is 0
 Example: int a = 100000, int b = -200000

4. long

 Long data type is a 64-bit signed


 Minimum value is -9,223,372,036,854,775,808
 Maximum value is 9,223,372,036,854,775,807
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L

5. float

 Float data type is a single-precision 32-bit


 Float is mainly used to save memory in large arrays of floating point
numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f

6. double

 double data type is a double-precision 64-bit


 Default value is 0.0d
 Example: double d1 = 123.4

7. boolean

 boolean data type represents 1 bit of information


 There are only two possible values: true and false
 Default value is false
 Example: boolean one = true

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 34
PATEL MANESH

8. char

 char data type is a single 16-bit Unicode character


 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 )
 Char data type is used to store any character
 Example: char C = 'A'

Reference Data types


 Reference variables are created using defined constructors of the classes.
 They are used to access objects.
 These variables are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under reference
datatype.
 Default value of any reference variable is null.
 Example: Demo D = new Demo();

Java Variables
 A variable is a container which holds the value.
 Def. Variable is a data name that is used to store data value.
 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.
 There are two types of data types in Java: primitive and non-primitive.

Syntax Data_type Varable_name = Data_value;


Example int no=10;

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 35
PATEL MANESH

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

1. local variable
2. instance variable
3. 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.

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.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 36
PATEL MANESH

Example of the types of variables in java

import java.io.*;

public class Demo


{
static int no=10; //static variable

void show()
1. {
2. int n=90; //local variable
3. }

public static void main (String manish[])


4. {
5. int data=50; //instance variable
6. }
7.
8.
}

Final Variables
 If you don't want to overwrite existing values, you have to use
the final keyword.

 This will declare the variable as "final" or "constant", which means


unchangeable and read-only)

Example:

final int no = 9;
no = 10; // will generate an error: cannot assign a value to a final
variable

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 37
PATEL MANESH

What are Java Global Variables?


 Global variables are those variables that are accessed by the entire program
and it is declared at the beginning of the program.
 Just to protect data and members (variables) of the Class, Java does not
support Global variables.

 So, we have Static variables that are globally declared and are accessible by
all method, subclass of a program.

Java Keywords
 Java keywords are also known as reserved words.
 Keywords are particular words that act as a key to a code.
 These are predefined words by Java so they cannot be used as a variable or
object name or class name.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 38
PATEL MANESH

Type Casting or Conversion in Java


 The process of converting a value from one data type to another is known
as type conversion in Java.
 Type casting is a method or process that converts a data type into another
data type in both ways manually and automatically.
 The automatic conversion is done by the compiler and manual conversion
performed by the programmer.
 Type conversion is also known as type casting in java or simply „casting’.

Types of Casting in Java

Two types of casting are possible in Java are as follows:

1. Implicit type casting or Widening Type Casting or casting down


2. Explicit type casting or Narrowing Type Casting or casting up

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 39
PATEL MANESH

1. Implicit type casting

 Converting a lower data type into a higher one is called widening type
casting.
 It is also known as implicit conversion or casting down.
 It is done automatically.
 It is safe because there is no chance to lose data.

int x = 10;
long y = x; // Automatic Conversion
Note:
 The conversion between numeric data type to char or Boolean is not done
automatically.
 Also, the char and Boolean data types are not compatible with each other.
class Demo
{
public static void main(String M[])
{
int x = 10;

//automatically converts the integer type into long type


long y = x;

//automatically converts the long type into float type


float z = y;

System.out.println("Before conversion, int value "+x);


System.out.println ("After conversion, long value "+y);
System.out.println ("After conversion, float value "+z);

} Output:
}
Before conversion, the value is: 10
After conversion, the long value is: 10
After conversion, the float value is: 10.0
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 40
PATEL MANESH

2. Explicit type casting

 Converting a higher data type into a lower one is called narrowing type
casting.
 It is also known as explicit conversion or casting up.
 It is done manually by the programmer.
 If we do not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

import java.io.*;

public class Demo


{
public static void main(String M[])
{
double d = 50.75;

//converting double data type into long data type


long l = (long)d;

//converting long data type into int data type


int i = (int)l;

System.out.println("Before conversion: "+d);

//fractional part lost


System.out.println("After conversion into long type: "+l);

//fractional part lost


System.out.println("After conversion into int type: "+i);

}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 41
PATEL MANESH

Output:
Before conversion: 50.75
After conversion into long type: 50
After conversion into int type: 50

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:

 Unary Operator or increment/Decrement Operator,


 Arithmetic Operator,
 shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator or Conditional Operator and
 Assignment Operator.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 42
PATEL MANESH

Java Operator Precedence

Java Unary Operator Example: ++ and --


class OpExa
{
public static void main(String args[]) Output:
{ 10
int x=10; 12
System.out.println(x++);//10 (11) 12
10
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
} }
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 43
PATEL MANESH

Java Unary Operator Example 2: ++ and --

class incre
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a);
//10+12=22
System.out.println(b++ + b++);
//10+11=21
}
}
Output:
22
21

Java Arithmetic Operator Example

class Arith
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
Output:
System.out.println(a*b); //50 15
System.out.println(a/b); //2 5
System.out.println(a%b); //0 50
} 2
0
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 44
PATEL MANESH

Java Arithmetic Operator Example: Expression

class OpExa
{
public static void main(String args[])
{

System.out.println(10*10/5+3-1*4/2);

}
}

Output: 21

Java Shift Operator Example: Left Shift


class ShiftExa
{
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
Output:
40
80
80
240

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 45
PATEL MANESH

Java Shift Operator Example: Right Shift


class ShiftExa
{
public static void main(String args[])
{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}}

Output:
2
5
2

Java AND Operator Example: Logical && and Bitwise &


 The logical && operator doesn't check second condition if first condition is
false. It checks second condition only if first one is true.
 The bitwise & operator always checks both conditions whether first
condition is true or false.

class LogicalExa
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b && a<c); //false && true = false
System.out.println(a<b & a<c); //false & true = false
}
}

Output:
false
false
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 46
PATEL MANESH

Java OR Operator Example: Logical || and Bitwise |


 The logical || operator doesn't check second condition if first condition is
true. It checks second condition only if first one is false.
 The bitwise | operator always checks both conditions whether first
condition is true or false.
Output:
class LogExa
true
{
true
public static void main(String args[])
true
{
int a=10; 10
int b=5; true
int c=20; 11
System.out.println(a>b | a<c); //true | true = true
//|| vs |
System.out.println(a>b || a++<c); //true || true = true
System.out.println(a); //10 because second condition is not checked
System.out.println(a>b | a++<c); //true | true = true
System.out.println(a); //11 because second condition is checked
}}

Java Ternary Operator Example


class TerExa
{
public static void main(String M[])
{
int a=2; Output:
int b=5;
2
int min = (a<b) ? a : b;
System.out.println(min);
}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 47
PATEL MANESH

Java Assignment Operator Example


class AssiExa
{
public static void main(String args[])
{
int a=10;
int b=20;

a += 2; //a=a+4 (a=10+4)
b -= 2; //b=b-4 (b=20-4)
System.out.println(a);
Output:
System.out.println(b); 12
} 18
}

Java Operators Precedence and Associativity


 Precedence and associativity are two features of Java operators.
 When there are two or more operators in an expression, the operator with
the highest priority will be executed first.

Category Operators Associativity

Postfix ++ - - Left to right

Unary + - ! ~ ++ - - Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 48
PATEL MANESH

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Java Control Statements | 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.
 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

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 49
PATEL MANESH

Decision-Making statements:

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

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.

1. class Student
{
2. public static void main(String[] args)
3. {
4. int x = 10;
5. int y = 12;
6. if(x+y > 20)
7. {
8. System.out.println("x + y is greater than 20");
}
}

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.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 50
PATEL MANESH

class Student
{
public static void main(String[] ashvin)
{
int x = 10;
int y = 12;

if(x+y < 10)


{
System.out.println("x + y is less than 10");
}

else
{
System.out.println("x + y is greater than 20");
}
}
}

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.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 51
PATEL MANESH

class Grade
{
public static void main(String Manish[])
{
int score; // To hold a test score
char grade; // To hold a letter grade

Scanner S = new Scanner(System.in);

System.out.print("Enter your numeric test score : ");


score = S.nextInt();

if (score >= 90)


{
grade = 'A';
}
else if (score >= 80)
{
grade = 'B';
}
else if (score >= 70)
{
grade = 'C';
}
else if (score >= 50)
{
grade = 'D';
}
else
{
grade = 'F';
}

System.out.println("Your grade is " + grade);


}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 52
PATEL MANESH

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.
Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.

switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 53
PATEL MANESH

import java.util.*;

class Week
{
public static void main(String[] ashvin)
{
int no;

Scanner S=new Scanner (System.in);


System.out.println ("Enter a number of WEEK day");
no=S.nextInt();

switch(no)
{
case 1:
System.out.println (“sunday”);
break;
case 2:
System.out.println ("Monday");
break;
case 3:
System.out.println ("Tuesday");
break;
case 4:
System.out.println ("Wednesday");
break;
default:
System.out.println (“Sorry!!!...Plz…enter number between
1 and 7”);
break;
}

}
}

 You can use Numaric, Character and String using switch case.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 54
PATEL MANESH

Loop Statements
 In programming, sometimes we need to execute the block of code
repeatedly while some condition evaluates to true.
 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

Let's understand the loop statements one by one.

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

for(initialization, condition, increment/decrement)


{
//block of statements
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 55
PATEL MANESH

Import java.io.*;

class Sum
{
public static void main(String[] manu)
{

int sum = 0;

for(int i = 1; i<=10; j++)


{
sum = sum + i;
}

System.out.println("The sum of first 10 natural numbers is " + sum);

}
}

Java 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.
 It is also known as the entry-controlled loop since the condition is checked
at the start of the loop.
 If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.

The syntax of the while loop is given below.

while (condition)
{
//looping statements
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 56
PATEL MANESH

import java.io.*;

class Even
{
public static void main(String[] args)
{
int i = 0;

System.out.println ("Printing the list of first 10 even numbers \n");

while (i<=10)
{
System.out.println (i);
i = i + 2;
}
}
}

Java 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.
 It is also known as the exit-controlled loop since the condition is not
checked in advance.

The syntax of the do-while loop is given below.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 57
PATEL MANESH

do
{
//statements
} while (condition);

public class Even


{
public static void main(String M[])
{
int i = 0;

System.out.println("Printing the list of first 10 even numbers \n");

do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Java 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.
class Cnt
{
public static void main (String manish[])
{
for (int i = 0; i<= 5; i++)
{
if (i == 4)
{
continue;
}
System.out.println (i);
}
}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 58
PATEL MANESH

Nested Loop
 Nested for loop in Java means a for loop inside another for loop is called
nested for loops.
 A nested for loops consists of an outer for loop and one or more inner for
loops.
 Each time the outer for loop repeats, the inner for loop re-enters and starts a
new execution.

public class Nested


{
public static void main(String args[])
{
int row=6;

for(int i=0; i<row; i++) //outer loop for rows


{
for(j=0; j<=i; j++) //inner loop for columns
{
System.out.print ("* ");
}
System.out.println ();
}
}
Output:
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 59
PATEL MANESH

Java Method
 A method is a way to perform some task.
 The method in Java is a collection of instructions that performs a specific task.
 It provides the reusability of code.
 We can also easily modify code using methods.
 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 most important method in Java is the main() method.

Method Declaration

 The method declaration provides information about method attributes, such


as visibility, return-type, name, and arguments.
 It has six components that are known as method header, as we have shown in
the following figure.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 60
PATEL MANESH

Naming a Method
 Single-word method name: sum(), area()
 Multi-word method name: areaOfCircle(), stringComparision()

 It is also possible that a method has the same name as another method name
in the same class, it is known as method overloading.

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

1. Predefined Method
2. User-defined Method

1. 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(), print(), println(), Max(), Min() etc.

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.

How to Create a User-defined Method


import java.lang.*;
import java.io.*;
class Box
{
int length, breadth, height;

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 61
PATEL MANESH

Box (int l, int b, int h)


{
length=l;
breadth=b;
height=h;
}
public void display()
{
int volume=length*breadth*height;
System.out.println ("Volume of Box is= "+volume);
}
}
class Demo1
{
public static void main(String M[])
{
Box b1=new Box(10,20,30);
Box b2=new Box(100,200,300);
b1.display();
b2.display(); Output:
}
} Volume of Box is=6000

Volume of Box is=60,00,000


Static Method
 A method that has static keyword is known as static method.
 The main advantage of a static method is that we can call it without
creating an object.
 It can access static data members and also change the value of it.
 It is used to create an instance method.
 It is invoked by using the class name.
 The best example of a static method is the main() method.

class Display
{
public static void main(String[] args)
{
show();
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 62
PATEL MANESH

static void show()


{
System.out.println("It is an example of static method.");
}
}

Abstract Method
 The method that does not has method body is known as abstract method.
 In other words, without an implementation is known as abstract method.
 It always declares in the abstract class.
 It means the class itself must be abstract if it has abstract method.
 To create an abstract method, we use the keyword abstract.

Syntax

abstract void method_name();

Example of abstract Method

abstract class Demo //abstract class


{
abstract void display(); //abstract method declaration

class MyClass extends Demo


{

void display() //method impelmentation


{
System.out.println("Abstract method?");
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 63
PATEL MANESH

public static void main(String args[])


{
//creating reference object of abstract class
Demo obj = new MyClass();

//invoking abstract method


obj.display();
}
}

Creating methods with zero, one and multiple arguments


import java.lang.*;
import java.io.*;

class Demo
{
int a,b; //class or instance variable

void display(int x) //Instance Method


{
System.out.println ("Single Argument= "+x);
}

void display(int x, int y) //Instance Method


{
a=x+y;
System.out.println ("Two Arguments= "+a);
}

void display(int x, int y, int z) //Instance Method


{
b=x+y+z;
System.out.println ("Three Arguments= "+b);
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 64
PATEL MANESH

class Demo1
{
public static void main(String M[])
{
Demo D1=new Demo(); Output:

D1.display(10); // method calling Single Argument=10


D1.display(10,20); Two Arguments=30
D1.display(10,20,30); Three Arguments=60
}
}

Instance Methods in Java

 Instance Methods are the group of codes that performs a particular task.
 Sometimes the program grows in size, and we want to separate the logic of
the main method from other methods.
 A method is a function written inside the class.
 Java is an object-oriented programming language, we need to write a
method inside some classes.

Instance Method without parameter


Syntax:

modifier return_type method_name( )


{
method body ;
}
Example:

public void display() //Instance Method


{
System.out.println ("Hello Good Morning”);
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 65
PATEL MANESH

Method with parameter


void display(int x) //Instance Method
{
System.out.println ("Single Argument= "+X);
}

Example of instance method:


import java.lang.*;
import java.io.*;

class Demo
{
int a,b; //class or instance variable

void display(int x) //Instance Method


{
System.out.println ("Single Argument= "+X);
}

void display(int x, int y) //Instance Method


{
a=x+y;
System.out.println ("Two Arguments= "+a);
}

void display(int x, int y, int z) //Instance Method


{
b=x+y+z;
System.out.println ("Three Arguments= "+b);
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 66
PATEL MANESH

class Demo1
{
public static void main(String M[])
{
Demo D1=new Demo(); //Object Output:

D1.display(10); // method calling Single Argument=10


D2.display(10,20); Two Arguments=30
D2.display(10,20,30); Three Arguments=60
}
}

How to Create Object in Java


 The object is a basic building block of an OOPs language.
 In Java, we cannot execute any program without creating an object.
 There is various way to create an object in Java.

Java provides five ways to create an object.

1. Using new Keyword


2. Using clone() method
3. Using newInstance() method of the Class class
4. Using newInstance() method of the Constructor class
5. Using Deserialization

Using new Keyword


 Using the new keyword is the most popular way to create an object or
instance of the class.
 When we create an instance of the class by using the new keyword, it
allocates memory (heap) for the newly created object and also returns
the reference of that object to that memory.
 The new keyword is also used to create an array.
 The syntax for creating an object is:

Syntax: ClassName object = new ClassName();

Example: Demo D=new Demo();

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 67
PATEL MANESH

Static method
 static keyword in java is used a lot in java programming.
 Java static keyword is used to create a Class level variable in java.
 static variables and methods are part of the class, not the instances of the
class.
 The static keyword in java is used for memory management mainly.
 We can apply java static keyword with variables, methods, blocks and
nested class.

The static can be:

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 68
PATEL MANESH

1) Java static variable

If you declare any variable as static, it is known static variable.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Student
{
int rollno;
String name;
String college="BCA";
}

 Suppose there are 500 students in my college, now all instance data
members will get memory each time when object is created.
 All students have its unique rollno and name so instance data member is
good.
 Here, college refers to the common property of all objects.If we make it
static,this field will get memory only once.
Java static property is shared to all objects.
Example
class Student
{
int rollno;
String name;
static String college ="BCA";

Student8(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 69
PATEL MANESH

public static void main(String args[])


{
Student s1 = new Student(111,"MANESH");
Student s2 = new Student(222,"BINA");

s1.display();
s2.display();
}

Output:
111 MANESH BCA
222 BINA BCA

2) Java static method

If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class.

 A static method can be invoked without an object.

 static method can access static data member and can change the value

of it.

class Student
{
int rollno;
String name;
static String college = "B.com";

static void change() // Static Method


{
college = " BCA ";
}

Student (int r, String n) //Constructor


{
rollno = r;
name = n;
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 70
PATEL MANESH

void display ()
{
System.out.println (rollno+" "+name+" "+college);
}

public static void main(String M[])


{
Student.change ();

Student s1 = new Student (111,"Ashvin");


Student s2 = new Student (222,"Nivanshi");

s1.display ();
111 Ashvin BCA
s2.display ();
}} 222 Nivanshi BCA

Why java main method is static?

Because object is not required to call static method if it were non-static


method, jvm create object first then call main() method that will lead the problem
of extra memory allocation.

3) Java static block

 Is used to initialize the static data member.


 It is executed before main method at the time of class loading.

class Demo
{
static
{
System.out.println ("static block is invoked"); Output:
}
static block is invoked
public static void main(String M[])
{ Hello main
System.out.println ("Hello main");
}
}
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 71
PATEL MANESH

Can we execute a program without main () method?

Yes, one of the way is static block but in previous version of JDK not in JDK
1.7 and later.
class XYZ{
static
{
System.out.println ("static block is invoked");
System.exit (0);
} }

Method overloading
 If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
 If we have to perform only one operation, having same name of the
methods increases the readability of the program.
 Suppose you have to perform addition of the given numbers but there can
be any number of arguments,
 if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method because its
name differs.

class Demo
{
int a=10,b=20;

void add()
{
System.out.println (a+b);
}

int add (int no1)


{
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 72
PATEL MANESH

a = no1;
int r = a + b;
return (r); class Manish
} {
public static void main (String M[])
void add (int no1, int no2) {
{ Demo d=new Demo ();
a=no1;
b=no2; d.add ();
System.out.println (a + b);
int z = d.add (100);
}
System.out.println (z);
}
d.add (500,600);
}
}

Public

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 73
PATEL MANESH

Constructors in Java
 In Java, a constructor is a block of codes similar to the method.
 It is called when an object 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.

There are two types of constructors in Java:

1. Default constructor
2. Parameterized constructor.

Rules for creating Java 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

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:

<class_name> () {}
Example Demo() {}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 74
PATEL MANESH

import java.io.*;

class Demo
{

Demo () //creating a default constructor


{
System.out.println ("I am Default….");
}

public static void main (String M[] )


{
Demo d = new Demo (); //calling a default constructor

}
}

Q) What is the purpose of a default constructor?

 The default constructor is used to provide the default values to the object like
0, null, etc., depending on the type.

Java Parameterized Constructor


 A constructor which has a specific number of parameters is called a
parameterized constructor.
Why use the parameterized constructor?

 The parameterized constructor is used to provide different values to distinct


objects.
 However, you can provide the same values also.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 75
PATEL MANESH

class Student
{
int id;
String name;

Student (int i, String n) //parameterized constructor


{
id = i;
name = n;
}
void display ()
{
System.out.println (id+" "+name);
}
public static void main (String M[])
{
Student s1 = new Student (101,"Manesh");
Student s2 = new Student (202,"Ashvin");
101 Manesh
s1.display ();
202 Ashvin
s2.display ();
}
}

Constructor Overloading in Java


 Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists.
 They are arranged in a way that each constructor performs a different task.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 76
PATEL MANESH

class Student
{
int id, age;
String name;

Student (int i, String n)


{
id = i;
name = n;
}

Student (int x,String y, int z)


{
id = x;
name = y;
age = z;
}

void display()
{
System.out.println (id+" "+name+" "+age);
}

public static void main (String M[])


{
Student s1 = new Student (101, "Manesh");
Student s2 = new Student (202, "Ashvin", 25);

s1.display ();
s2.display ();
}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 77
PATEL MANESH

Difference between constructor and method in Java

Java Constructor Java Method

A constructor is used to initialize the A method is used to expose


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

What is this Keyword


 This is a keyword in Java.
 It can be used inside the Method or constructor of Class.
 It(this) works as a reference to the current Object whose Method or
constructor is being invoked.
 The this keyword can be used to refer to any member of the current object
from within an instance Method or a constructor.

Usage of java this keyword

1. this can be used to refer current class variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 78
PATEL MANESH

Suggestion: If you are beginner to java, lookup only three usage of this keyword.

1) this: to refer current class variable

 This keyword can be used to refer current class variable.


 If there is complexity between the class variables and parameters, this
keyword resolves the problem of complexity.

Understanding the problem without this keyword


class Student
{
int rollno;
String name;
float fee;

Student (int rollno, String name, float fee)


{
rollno = rollno;
name = name;
fee = fee;
}

void display ()
{
System.out.println (rollno+" "+name+" "+fee);
}
}
class Demo
{
public static void main (String M[])
{
Student s1=new Student (111, "Bina", 5000f);
Student s2=new Student (112, "Nivanshi", 6000f);
s1.display ();
s2.display (); OUTPUT
}
0 null 0.0
}
0 null 0.0

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 79
PATEL MANESH

In the above example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.

Solution of the above problem by this keyword


class Student
{
int rollno;
String name;
float fee;

Student (int rollno, String name, float fee)


{
this.rollno = rollno;
this.name = name;
this.fee = fee;
}

void display ()
{
System.out.println (rollno+" "+name+" "+fee);
}
}

class Demo
{
public static void main (String M[])
{
Student s1=new Student (111, "Bina", 5000f);
Student s2=new Student (112, "Nivanshi", 6000f);
s1.display ();
s2.display ();
} OUTPUT
} 111 Bina 5000
112 Nivanshi 6000

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 80
PATEL MANESH

2) this: to invoke current class method

 You may invoke the method of the current class by using this keyword.
 If you don't use this keyword, compiler automatically adds this keyword
while invoking the method.
 Let's see the example

class A
{
void m()
{
System.out.println ("hello m");
}

void show()
{
System.out.println ("hello n");
//m(); //same as this.m()
this.m ();
}
}

class Demo
{
public static void main (String M[])
{
A obj=new A();
obj.show();
}
}

Output:
hello n
hello m

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 81
PATEL MANESH

3) this() : to invoke current class constructor

class A
{
A()
{
this(5); // Parameterized Constructor calling
System.out.println ("Hello");
}

A (int x) // Parameterized Constructor


{
System.out.println(x);
}
}

class Test
{
public static void main (String args[])
{
A a=new A(); // Default Constructor calling
}
}

Output:
5
Hello
4) this: to pass as an argument in the method

 this keyword can also be passed as an argument in the method.


 It is mainly used in the event handling.

class S2
{
void m (S2 obj)
{
System.out.println ("method is invoked");
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 82
PATEL MANESH

void p()
{
m(this);
}

public static void main(String args[])


{
S2 s1 = new S2();
s1.p();
}
}
Output:
method is invoked

Java Array
 Normally, array is a collection of similar type of elements that have
contiguous memory location.
 Java array is an object contains elements of similar data type.
 It is a data structure where we store similar elements.
 We can store only fixed set of elements in a java array.
 Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array

 Code Optimization: It makes the code optimized; we can retrieve or sort


the data easily.
 Random access: We can get any data located at any index position.

Disadvantage of Java Array

 Size Limit: We can store only fixed size of elements in the array.
 It doesn't grow its size at runtime.
 To solve this problem, collection framework is used in java.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 83
PATEL MANESH

Types of Array in java

There are three types of array.

1. Single Dimensional Array


2. Two Dimensional Array
3. Multidimensional Array

1. Single Dimensional Array in java

Syntax to Declare an Array in java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in java

datatype RefVar = new datatype[size];

class arr
{
public static void main(String manish[]){

int a[]=new int[5]; //declaration and instantiation


a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
Output:
a[4]=50;
10
20
//printing array 70
for (int i=0; i<a.length; i++) 40
System.out.println (a[i]); 50
}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 84
PATEL MANESH

Let's see the simple example to print this array.

class arr
{
public static void main(String args[])
{
int a[]={33,3,4,5}; //declaration, instantiation and initialization

//printing array

for (int i=0; i<a.length; i++)


System.out.println (a[i]);

}}

Two dimensional array in java


 In such case, data is stored in row and column based index (also known as
matrix form).

Syntax to Declare Two dimensional Array in java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Two dimensional Array in java

1. int[][] arr=new int[3][4]; //3 row and 4 column


2. Here, arr is a two-dimensional (2d) array.

The array can hold maximum of 12 elements of type int.

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 85
PATEL MANESH

Similarly, you can declare a three-dimensional (3d) array.

For example,

String[][][] manesh = new String[3][4][2];

Example to initialize Two Dimensional Array in java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 86
PATEL MANESH

Example of Multidimensional java array

class Demo
{
public static void main(String args[])
{
//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

for (int i=0;i<3;i++)


{
for (int j=0;j<3;j++)
{
System.out.print (arr[i][j]+" ");
}
System.out.println (); 123
} 245
}
} 445

Example of arraycopy method


class Demo
{
public static void main (String M[])
{
char[] CP = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] XYZ = new char[7];

System.arraycopy (CP, 2, XYZ, 0, 7);


System.out.println (new String(XYZ));
}
}
Output: caffeine
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 87
PATEL MANESH

Java For-each Loop


For-each is another array technique like for loop, while loop, do-while loop
introduced in Java5.

 It starts with the keyword for like a normal for-loop.


 Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a
colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than
using an indexed array element.
 It‟s commonly used to iterate over an array or a Collections class (eg,
ArrayList)

Syntax:

for (type var : array)


{
Statements using var;
}
Example:

import java.io.*;

class Demo
{
public static void main(String M[])
{
int arr[] = { 10, 50, 60, 80, 90 }; // array declaration

for (int i : arr)


{
System.out.print(i + " ");
}
}
} Output

10 50 60 80 90
s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 88
PATEL MANESH

Another Example

class Demo1
{
public static void main(String M[])
{
int arr[]={10,20,30,40};
int total=0;

for (int i : arr)


{
total = total + i; Output

} Total: 100
System.out.println ("Total: "+total);
}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 89
PATEL MANESH

How to return an array in Java


 A method can return a reference to an array.
 The return type of a method must be declared as an array of the correct data
type

import java.util.*;

public class arr


{
public static void main(String args[])
{
int[] a = numbers(); //obtain the array

for (int i = 0; i < a.length; i++) //for loop to print the array
{
System.out.print (a[i] + " ");
}
}

public static int[] numbers()


{
int[] arr={5,6,7,8,9}; //initializing array
return arr;
}
}

s
PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 90

You might also like