Sunteți pe pagina 1din 66

KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Programming Languages

Programming languages allow programmers to code software.

The three major families of languages are:

 Machine languages
 Assembly languages
 High-Level languages

1. Machine languages
Machine language is the lowest-level programming language. Machine languages are
the only languages understood by computers. machine languages are almost impossible for
humans to use because they consist entirely of numbers.

2. Assembly languages
An assembly language implements a symbolic representation of the machine code
needed to program a given CPU architecture. An assembly language is the most basic
programming language available for any processor.
Assembly languages generally lack high-level conveniences such as variables and functions,
and they are not portable between various families of processors.

3. High-Level languages
A high-level language (HLL) is a programming language that enables a programmer to
write programs that are more or less independent of a particular type of computer.
Such languages are considered high-level because they are closer to human languages and
further from machine languages.

There are two types of High-Level languages


1. Procedural oriented programming
2. Object Oriented programming

Prof. Raju Vathari 1


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

1. Procedure oriented programming (POP)

POP is a conventional way of programming. Procedural programming is where the


primary focus is on getting the task done in a sequential order. Flowchart organizes the flow
of control of the program. If the program is large, it is structured in some small units called
functions, which shares global data. Here the concern of data security arises, as there is an
unintentional change in the program by functions.

2. Object-oriented programming (OOP)

OOP’s main concern is to hide the data from non-member functions of a class, which it
treats like “critical information”. Data is closely tied to the member functions of a class,
which operates on it. It doesn’t allow any non-member function to modify the data inside it.
Objects communicate with each other through member functions to access their data.

OOP is developed on the basic concept of “object”, “classes”, “data encapsulation or


abstraction”, “inheritance”, and “Polymorphism/overloading”. In OOP, programs can be
divided into modules by partitioning data and functions, which further can be used as
templates for creating new copies of modules, if required.

Prof. Raju Vathari 2


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Difference between OOP and POP

Procedure-oriented Programming (POP) and Object-oriented programming (OOP) both are


the programming approaches, which uses high-level language for programming.

A Program can be written in both the languages, but if the task is highly complex, OOP
operates well as compared to POP.

In POP, the ‘data security’ is at risk as data freely moves in the program, as well as, ‘code
reusability’ is not achieved which makes the programming lengthy, and hard to understand.

Large programs lead to more bugs, and it increases the time of debugging. All these flaws
(faults) lead to a new approach namely “object-oriented programming”.

In object-oriented programming’s main concern is given on ‘data security’; it binds the data
closely to the functions which operate on it. It also resolves the problem of ‘code
reusability’, as if a class is created, its multiple instances (objects) can be created which
reuses the members and member functions defined by a class.

Prof. Raju Vathari 3


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Comparison Chart

BASIS FOR
POP OOP
COMPARISON

Basic Procedure/Structure oriented. Object oriented.

Approach Top-down. Bottom-up.

Basis Main focus is on "how to get the Main focus is on 'data


task done" i.e. on the procedure or security'. Hence, only objects
structure of a program. are permitted to access the
entities of a class.

Division Large program is divided into units Entire program is divided into
called functions. objects.

Entity accessing mode No access specifier observed. Access specifier are "public",
"private", "protected".

Overloading/Polymorphism Neither has it overloaded functions It overloads functions,


nor operators. constructors, and operators.

Inheritance There is no provision of Inheritance achieved in three


inheritance. modes public private and
protected.

Data hiding & security There is no proper way of hiding Data is hidden in three modes
the data, so data is insecure public, private, and protected.
hence data security increases.

Data sharing Global data is shared among the Data is shared among the
functions in the program. objects through the member
functions.

Friend functions/classes No concept of friend function. Classes or function can


become a friend of another
class with the keyword
"friend".
Note: "friend" keyword is used
only in c++

Virtual classes/ function No concept of virtual classes . Concept of virtual function


appear during inheritance.

Example C, VB, FORTRAN, Pascal C++, JAVA, VB.NET,


C#.NET.

Prof. Raju Vathari 4


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Conclusion
The flaws (fault) of POP arises the need of OOP. OOP corrects the flaws (fault) of POP by
introducing the concept of “object” and “classes”. It enhances the data security, and
automatic initialization & clear-up of objects. OOP makes it possible to create multiple
instances of the object without any interference.

Prof. Raju Vathari 5


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Structure of Java Program


Java is Developed by James Gosling in
Structure of a java program is the standard format released by Language developer to the
Industry programmer.
Sun Micro System has prescribed the following structure for the java programmers for
developing java application.

 A package is a collection of classes, interfaces and sub-packages. A sub package contains


collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported
by default and this package is known as default package.
 Class is keyword used for developing user defined data type and every java program must
start with a concept of class.
 "ClassName" represent a java valid variable name treated as a name of the class each and
every class name in java is treated as user-defined data type.
 Data member represents either instance or static they will be selected based on the name
of the class.
 User-defined methods represents either instance or static they are meant for performing
the operations either once or each and every time.
 Each and every java program starts execution from the main() method. And hence main()
method is known as program driver.

Prof. Raju Vathari 6


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

 Since main() method of java is not returning any value and hence its return type must be
void.
 Since main() method of java executes only once throughout the java program execution
and hence its nature must be static.
 Since main() method must be accessed by every java programmer and hence whose access
specifier must be public.
 Each and every main() method of java must take array of objects of String.
 Block of statements represents set of executable statements which are in term calling user-
defined methods are containing business-logic.
 The file naming conversion in the java programming is that which-ever class is containing
main() method, that class name must be given as a file name with an extension .java.

Object Oriented Programming (OOPs) Concept in


Java (Pillars of OOPs)
Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs
refers to languages that uses objects in programming. Object-oriented programming aims to
implement real-world entities like inheritance, hiding, polymorphism etc in programming.

OOPs Concepts:

 Object

 Class

 Inheritance

 Polymorphism

 Abstraction

 Encapsulation

 Message Passing

Prof. Raju Vathari 7


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

1. Object :
It is a basic unit of Object Oriented Programming and represents the real life entities. 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 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.
Example of an object : dog

Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such
as “shopping cart”, “customer”, and “product”.

2. Class:
A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
 Class is user defined data type, on which objects are created.
 Class is “blueprint”––
 Class is a “prototype”

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


2. Class name: The name should begin with a initial letter.
3. Super class (if any): The name of the class’s parent (super class), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. 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.
5. Body: The class body surrounded by braces, { }.

Prof. Raju Vathari 8


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

3. Inheritance

1. Inheritance
2. Types of Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template


or blueprint from which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

o Reusability: As the name specifies, reusability is a mechanism which facilitates you


to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

Prof. Raju Vathari 9


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

Single Inheritance Example


File: TestInheritance.java

class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}

Prof. Raju Vathari 10


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}

4. Polymorphism (Many Forms)

Polymorphism in Java is a concept by which we can perform a single action in different


ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java:

 compile-time polymorphism and runtime polymorphism.

We can perform polymorphism in java by method overloading and method overriding.


If you overload a static method in Java, it is the example of compile time polymorphism..

 Real life example of polymorphism

Suppose if you are in class room that time

you behave like a student, when you are

in market at that time you behave like a

customer, when you at your home at that

time you behave like a son or daughter,

Here one person present in different-

different behaviors.

Prof. Raju Vathari 11


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

5. Abstraction

Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.

Ex: A car is viewed as a car rather than its individual components.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does
not know about how on pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of accelerator, brakes etc
in the car. This is what abstraction is.

6. Encapsulations
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates.

Other way to think about encapsulation is, it is a protective shield that prevents the
data from being accessed by the code outside this shield.

 Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which
they are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class as private
and writing public methods in the class to set and get the values of variables.

Advantage of Encapsulation

The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not accessible
outside the class.

Real life example of Encapsulation in Java

The common example of encapsulation is capsule. In capsule all medicine are encapsulated in
side capsule.

Prof. Raju Vathari 12


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Benefits of encapsulation

 Provides abstraction between an object and its clients.

 Protects an object from unwanted access by clients.

 Example: A bank application forbids (restrict) a client to change an Account's balance.

7. Message Passing
An object oriented program consists of a set of objects that communicates with each other.
The process of programming in an object oriented language, therefore, involves the
following basic steps.
1. Creating classes that define objects and their behavior.
2. Creating objects from class definitions.
3. Establishing communication among objects.

Prof. Raju Vathari 13


KLE’s BK BCA College Chikodi Introduction to OOPS in 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 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 suited for
internet programming. Later, Java technology was
incorporated by Netscape.
Born May 19-1955

The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted and Dynamic".

Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. There are given the 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.

2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.

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

4) After that, it was called Oak and was developed as a part of the Green project.

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

Prof. Raju Vathari 14


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Why Java named "Oak"?

Why Oak? Oak is a symbol of strength and chosen as


a national tree of many countries like U.S.A., France,
Germany, Romania, etc.

Java Version History

Many java versions have been released till now. The current stable release of Java is Java SE 10.

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 March 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th March 2018)

James Gosling currently working in Amazon company.

Prof. Raju Vathari 15


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Features of Java

Features of a language are nothing but the set of services or facilities provided by the
language vendors to the industry programmers. Some important features of java are;

Important Features of Java


1. Simple
2. Platform Independent
3. Portable
4. Secured
5. Robust
6. Dynamic
7. High Performance
8. Interpreted
9. Object Oriented

Prof. Raju Vathari 16


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

1. Simple

It is simple because of the following factors:


 It is free from pointer due to this execution time of application is improved. [Whenever
we write a Java program without pointers then internally it is converted into the equivalent
pointer program].
 It has Rich set of API (application protocol interface).
 It hs Garbage Collector which is always used to collect un-Referenced (unused) Memory
location for improving performance of a Java program.

 It contains user friendly syntax for developing any applications.

2. Platform Independent (Java is a write once, run anywhere language)

A program or technology is said to be platform independent if and only if which can run on
all available operating systems with respect to its development and compilation. (Platform
represents O.S).

Prof. Raju Vathari 17


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

3. Portable
If any language supports platform independent and architectural neutral feature known as
portable. The languages like C, CPP, Pascal are treated as non-portable language. It is a
portable language.
According to SUN microsystem.

4. Robust

Simply means of Robust are strong. It is robust or strong Programming Language because of
its capability to handle Run-time Error, automatic garbage collection, the lack of pointer
concept, Exception Handling. All these points make It robust Language.

5. Secure

It is a more secure language compared to other language; In this language, all code is
covered in byte code after compilation which is not readable by human

6. High performance

It have high performance because of following reasons;

 This language uses Bytecode which is faster than ordinary pointer code so Performance
of this language is high.
 Garbage collector, collect the unused memory space and improve the performance of
the application.
 It has no pointers so that using this language we can develop an application very easily.
 It support multithreading, because of this time consuming process can be reduced to
executing the program.

Prof. Raju Vathari 18


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

7. Dynamic

It supports Dynamic memory allocation due to this memory wastage is reduce and improve
performance of the application. The process of allocating the memory space to the input of
the program at a run-time is known as dynamic memory allocation, To programming to
allocate memory space by dynamically we use an operator called 'new' 'new' operator is
known as dynamic memory allocation operator.

8. Interpreted

It is one of the highly interpreted programming languages.

9. Object Oriented

It supports OOP's concepts because of this it is most secure language,

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
incorporates both data and behavior.

JAVA DEVELOPMENT KIT

The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment (JRE), an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc) and other tools needed in Java development.
OR

The JDK is a software package that contains a variety of tools and utilities that make it
possible to develop, package, monitor and deploy applications that build for any standard Java
platform, including Java Platform, Standard Edition (Java SE); Java Platform, Micro Edition
(Java ME); and Java Platform, Enterprise Edition (Java EE)

JDK components, tools and utilities

The bin directory of the JDK provides a variety of features and tools that aid in the software
development process. Some of the more popular JDK utilities include:

Prof. Raju Vathari 19


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

 javac: This utility is used to compile Java source code into Java bytecode.

 jar: This compression utility aggregates a multitude of files into a single Java ARchive
(JAR) file. The jar utility uses a standard compression algorithm used by all of the most
common zip utilities.

 javadoc: This utility can examine the names of classes and the methods contained within a
class, as well as consume special annotations in order to create application programming
interface (API) documentation for Java code.

 javap: This utility disassembles class files, generating information about the methods,
properties and attributes of a given compiled component and etc.

JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

There are three notation in 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 Performs following tasks:

The JVM performs following operation:

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

Prof. Raju Vathari 20


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

Java Runtime Environment (JVM)

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

The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.

Java Environment:

It is contains JDK + Java standard libraries(JSL) + Application Programming Interface (API)


JSL: It is also known as API. Java standard libraries include number of classes grouped into
functional packages.
Most among used packages are;
1. Language support package
2. Utility packages
3. Input and output packages
4. Abstract Windows tool kit
5. Applet packages

Prof. Raju Vathari 21


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Java Identifiers and Keywords:

Java Identifiers

In programming languages, identifiers are used for identification purpose. In Java, an


identifier can be a class name, method name, variable name or a label.

For example :

public class Test


{
public static void main(String[] args)
{
int a = 20;
}
}

In the above java code, we have 5 identifiers namely :

 Test : class name.


 main : method name.
 String : predefined class name.
 args : variable name.
 a : variable name.

Rules for defining Java Identifiers


There are certain rules for defining a valid java identifier. These rules must be followed,
otherwise we get compile-time error. These rules are also valid for other languages like C,C++.

 The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-
9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “java@” is not a valid java identifier
as it contain ‘@’ special character.
 Identifiers should not start with digits([0-9]). For example “123java” is a not a valid java
identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to use an optimum length
of 4 – 15 letters only.

Prof. Raju Vathari 22


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

 Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid
statement as while is a reserved word. There are 53 reserved words in Java.

Examples of valid identifiers :

1. MyVariable 7. i1
2. MYVARIABLE 8. _myvariable
3. myvariable 9. $myvariable
4. x 10. sum_of_array
5. i 11. geeks123
6. x1

Examples of invalid identifiers :


1. My Variable // contains a space
2. 123java // Begins with a digit
3. a+c // plus sign is not an alphanumeric character
4. variable-2 // hyphen is not an alphanumeric character

Reserved Words
 Any programming language reserves some words to represent functionalities defined by
that language. These words are called reserved words.
 They can be briefly categorized into two parts : keywords(50) and literals(3).

Prof. Raju Vathari 23


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Java keywords

java keywords are also known as reserved words. Keywords are particular words which act as a
key to a code. These are predefined words by Java so it cannot be used as a variable or object
name.

All keywords are written in lower-case letter. And we cannot use them as names for variables,
classes, and methods and so on..

Examples for java keywords.

publicclassJavaKeyword

Prof. Raju Vathari 24


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

{
publicstaticvoidmain(String[] args)
{
double d1 = 23.56; // Here double is a keyword

double d2 = 56.23;

int a=10; // Here int is a keyword

for(i=0;i<n;i++) //Here for is a keyword


{
//Statements
}

System.out.println(d1);
}
}

Java Data Types


Data type specifies the size and type of values that can be stored in an identifier. The Java
language is rich in its data types. Different data types allow you to select the type appropriate to
the needs of the application.

Data types are divided into two groups:

1. Primitive data types


2. Non-primitive data types

 Primitive data types – these data types are the data types which is predefined by java is known as
primitive data types.
It includes 8 primitive data types are: byte, short, int, long, float, double, boolean and char
 Non-primitive data types are the data types which is defined by the programmers
- such as String, Arrays and Classes

Primitive Data Types


A primitive data type specifies the size and type of variable values, and it has no additional
methods.
There are eight primitive data types in Java:

Prof. Raju Vathari 25


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

List of all primitive data types and their sizes:

Data
Type Size Description

byte 1 byte Stores whole numbers from -128 to 127


short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values

Prof. Raju Vathari 26


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

char 2 bytes Stores a single character/letter or ASCII values

Numbers
Primitive number types are divided into two groups:

Integer types store whole numbers, positive or negative (such as 123 or -456), without decimals.
Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.

Even though there are many numeric types in Java, the most used for numbers are int (for whole
numbers) and double (for floating point numbers). However, we will describe them all as you
continue to read.

Integer Types

Byte :
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or
other integer types to save memory when you are certain that the value will be within -128 and 127:
Ex: byte a=100;

Short :
The short data type can store whole numbers from -32768 to 32767:
Ex: short myNum = 5000;

Int :
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.

Ex: int myNum = 100000;

Long :
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that you
should end the value with an "L":
Ex: long myNum = 15000000000L;

Prof. Raju Vathari 27


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Floating Point Types


You should use a floating point type whenever you need a number with a decimal, such as 9.99 or
3.14515.

Float :
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should
end the value with an "f":
Ex: float myNum = 5.75f;

Double :
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should
end the value with a "d":
Ex: ouble myNum = 19.99d;

Use float or double?


The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is only six or seven decimal digits, while double variables
have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
public class MyClass {
public static void main(String[] args) {
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
}
}
O/P:
35000.0
120000.0

Booleans :
A boolean data type is declared with the boolean keyword and can only take the values true or false:

public class MyClass {


public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}

Prof. Raju Vathari 28


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

O/P:
------------

True
false

Characters :
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
public class MyClass
{
public static void main(String[] args)
{
char myGrade = 'B';
System.out.println(myGrade);
}
}

Strings :
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
The String type is so much used and integrated in Java, that some call it "the special ninth type".
A String in Java is actually a non-primitive data type, because it refers to an object. The String
object has methods that are used to perform certain operations on strings.

//Write a java program to display the size of primitive data types that is in
bytes.
import java.io.*;
public class PrimitiveDatatypes
{
public static void main(String[] args)
{
System.out.println("Byte= "+(Byte.SIZE/8));
System.out.println("Short="+(Short.SIZE/8));
System.out.println("Integer="+(Integer.SIZE/8));
System.out.println("Long="+(Long.SIZE/8));
System.out.println("Float="+(Float.SIZE/8));
System.out.println("Character="+(Character.SIZE/8));
System.out.println("Double="+(Double.SIZE/8));
}
}

Prof. Raju Vathari 29


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

---------------------Output-------------------
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>javac PrimitiveDatatypes.java
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>java PrimitiveDatatypes
Byt e= 1
Short = 2
Integer = 4
Long = 8
Float = 4
Character = 2
Double = 8

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


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

 Narrowing Casting (manually) - converting a larger type to a smaller size type


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

Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:

Example
public class MyClass
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

OUTPUT
9
9.0

Prof. Raju Vathari 30


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:

Syntax:
dataType <variableName> = (dataType) <variableToConvert>;

Example
public class MyClass
{
public static void main(String[] args)
{
double myDouble = 9.78f;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}

OUTPUT

9.78
9

Java Variables
A variable is a container which holds the value while the java program is executed. A
variable is assigned with a data type.
A variable is a name given to a memory location. It is the basic unit of storage in a
program. The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
In Java, all the variables must be declared before use.

How to declare variables?


We can declare variables in java as follows:

datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Prof. Raju Vathari 31


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Examples:
float simpleInterest; //Declaring float variable
int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable

Variable is a name of memory location. There are three types of variables in java:
1) Local variable
2) Instance variable
3) Static variable

Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.

int data=50;//Here data is variable

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.

Prof. Raju Vathari 32


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

 The scope of these variables exists only within the block in which the variable is declared.
i.e. we can access these variable only within that block.
 Initilisation of Local Variable is Mandatory.

Example:
public class StudentDetails
{
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}
public static void main(String args[])
{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}
Output:
Student age is : 5
In the above program, the variable age is a local variable to the function StudentAge(). If we
use the variable age outside StudentAge() function, the compiler will produce an error as
shown in below program.
public class StudentDetails {
public void StudentAge()
{ // local variable age
int age = 0;
age = age + 5;
}

public static void main(String args[])


{
// using local variable age outside it's scope
System.out.println("Student age is : " + age);
}
}

Output:
Compilation Error in java code:-
prog.java:12: error: cannot find symbol
System.out.println("Student age is : " + age);

Prof. Raju Vathari 33


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

^
symbol: variable age
location: class StudentDetails
1 error

2) Instance Variable
A variable declared inside the class but outside the body of the method, constructors or
any blocks is called instance variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
 As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
 Initialization of Instance Variable is not Mandatory. Its default value is 0
 Instance Variable can be accessed only by creating objects.

import java.io.*;
class InstanceVariable
{
int c; //instance variable
public void add()
{
int a=10;
int b=10;
c=a+b; // using instance variable here that is c
System.out.println(c);
}
}

class variables
{
public static void main(String args[])
{
InstanceVariable instance=new InstanceVariable();
instance.add();
}
}

Output:
20

Here in above program int c; is a instance variable and it is declared within a class of
InstanceVariable. And this variable again we are used in add() method that is c=a+b; but only

Prof. Raju Vathari 34


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

we can access this instance variable by creating object for this add() method ie
instance.add();

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

 Static variables are created at the start of program execution and destroyed automatically
when execution ends.
 Initilisation of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like Instance variable (through an object), the compiler will
show the warning message and it won’t halt the program. The compiler will replace the
object name to class name automatically.
 If we access the static variable without the class name, Compiler will automatically append
the class name.
To access static variables, we need not create an object of that class, we can simply access the
variable as

class_name.variable_name;

Sample Program:
import java.io.*;
class Emp
{
// static variable salary
public static double salary;
public static String name = "Harsh";
}

public class EmpDemo


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

// accessing static variable without object


Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:"
+ Emp.salary);
}
}
Output:
Harsh's average salary:1000.0

Prof. Raju Vathari 35


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Example to understand the types of variables in java

class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class

In above program consist three types of variable , here int data=50; is a instance variable
because it is declared in class and static int m=100; is a static variable because it is declared as
a static by using static keyword and also outside the method and inside the class and int n=90;
Is a local variable it is declared in within method().

Prof. Raju Vathari 36


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Control Statements in java or (Decision Making Statements):


Java if, if...else Statement

In programming, it's often desirable to execute a certain section of code based upon whether the
specified condition is true or false (which is known only during the run time). For such cases,
control flow statements are used.
The Java if statement is used to test the condition. It checks boolean
condition: true or false. There are various types of if statement in java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement

Java if (if-then) Statement

The Java if statement tests the condition. It executes the if block if condition is true.
The syntax of if-then statement in Java is:

if (expression)
{
// statements
}

Here expression is a boolean expression (returns either true or false).


If the expression is evaluated to true, statement(s) inside the body of if (statements inside
parenthesis) are executed.
If the expression is evaluated to false, statement(s) inside the body of if are skipped from execution.

Prof. Raju Vathari 37


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

How if statement works?

Example 1: Java if Statement


1. class IfStatement
2. {
3. Public static void main(String[] args)
4. {
5. int number = 10;
6. if (number >0)
7. {
8. System.out.println("Number is positive.");
9. }
10. System.out.println("This statement is always executed.");
11. }
12. }// End of class

When you run the program, the output will be:

Number is positive.
This statement is always executed.

When number is 10, the test expression number > 0 is evaluated to true. Hence, codes inside the
body of if statements are executed.
Now, change the value of number to a negative integer. Let's say -5. The output in this case will
be:

This statement is always executed.

When number is -5, the test expression number > 0 is evaluated to false. Hence, Java compiler skips
the execution of body of if statement.

Prof. Raju Vathari 38


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Java if...else (if-then-else) Statement

The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.

The syntax of if-then-else statement is:

if (expression)
{
// codes
}
Else
{
// some other code
// Else code will executes.
}

How if...else statement works?

Prof. Raju Vathari 39


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Example 2: Java if else Statement


1. class IfElse
2. {
3. Public static void main(String[] args)
4. {
5. int number = 10;
6. if (number >0)
7. {
8. System.out.println("Number is positive.");
9. }
10. else
11. {
12. System.out.println("Number is not positive.");
13. }
14. System.out.println("This statement is always executed.");
15. }
16. }

When you run the program, the output will be:

Number is positive.
This statement is always executed.

When number is 10, the test expression number > 0 is evaluated to true. In this case, codes inside

the body of if are executed, and codes inside the body of else statements are skipped from
execution.
Now, change the value of number to a negative number. Let's say -5. The output in this case will
be:

Number is not positive.


This statement is always executed.

When number is -5, the test expression number > 0 is evaluated to false. In this case, codes inside
the body of else are executed, and codes inside the body of if statements are skipped from
execution.

Prof. Raju Vathari 40


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Java if..else..if Statement (if ..else.. ladder)


In Java, it's possible to execute one block of code among many. For that, you can use if..else...if
ladder.
Syntax of if..else..if

if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
// codes
}
.
.
else
{
// codes
}

Prof. Raju Vathari 41


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

The if statements are executed from the top towards the bottom. As soon as the test expression
is true, codes inside the body of that if statement is executed. Then, the control of program jumps
outside if-else-if ladder.
If all test expressions are false, codes inside the body of else is executed.

Example 3: Java if..else..if Statement


1. class Ladder
2. {
3. Public static void main(String[] args)
4. {
5. int number = 0;
6. if (number >0)
7. {
8. System.out.println("Number is positive.");
9. }
10. elseif (number <0)
11. {
12. System.out.println("Number is negative.");
13. }
14. else
15. {
16. System.out.println("Number is 0.");
17. }
18. }
19. }

When you run the program, the output will be:

Number is 0.

When number is 0, both test expression number > 0 and number < 0 is evaluated to false. Hence, the
statement inside the body of else is executed.
The above program checks whether number is positive, negative or 0.

Prof. Raju Vathari 42


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Java Nested if..else Statement

The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
It's possible to have if..else statements inside a if..else statement in Java. It's called
nested if...else statement.
Here's a program to find largest of 3 numbers:
Sysntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Prof. Raju Vathari 43


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Example 4: Nested if...else Statement


1. Class Number
2. {
3. publicstaticvoid main(String[] args)
4. {
5. Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;
6. if (n1 >= n2)
7. {
8. if (n1 >= n3)
9. {
10. largestNumber = n1;
11. }
12. else
13. {
14. largestNumber = n3;
15. }
16. }
17. Else
18. {
19. if (n2 >= n3)
20. {
21. largestNumber = n2;
22. }
23. else
24. {
25. largestNumber = n3;
26. }
27. }
28. System.out.println("Largest number is " + largestNumber);
29. }
30. }

When you run the program, the output will be:


Largest number is 4.5

Note: In above programs, we have assigned value of variables ourselves to make this easier.
However, in real world applications, these values may come from user input data, log files, form
submission etc.
You should also check ternary operator in Java, which is kind of shorthand notation
of if...else statement.

Prof. Raju Vathari 44


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Java Switch Statements


Use the switch statement to select one oPf many code blocks to be executed.

Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional,

Prof. Raju Vathari 45


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

The example below uses the weekday number to calculate the weekday name:
Example:
public class MyClass
{
public static void main(String[] args)
{
int day = 4;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}

Outputs: "Thursday" (day 4)

The break Keyword


 When Java reaches a break keyword, it breaks out of the switch block.
 This will stop the execution of more code and case testing inside the block.
 When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.

Prof. Raju Vathari 46


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

The default Keyword


The default keyword specifies some code to run if there is no case match:
Example

int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}

Outputs :
"Looking forward to the Weekend"

Note that if the default statement is used as the last statement in a switch block, it does not need a
break.

Prof. Raju Vathari 47


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Looping Statement in Java


Looping statement are the statements execute one or more statement repeatedly several number of
times. In java programming language there are three types of loops; while, for and do-while.

Why use loop ?


When you need to execute a block of code several number of times then you need to use looping
concept in Java language.

Advantage with looping statement


 Reduce length of Code
 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.

Difference between conditional and looping statement


Conditional statement executes only once in the program where as looping statements executes
repeatedly several number of time.

While Loop in Java


In while loop in Java first check the condition if condition is true then control goes inside the loop
body otherwise goes outside of the body. while loop will be repeats in clock wise direction.

Syntax
while(condition)

Prof. Raju Vathari 48


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

{
Statement(s)
Increment / decrements (++ or --);
}

Example while loop

class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(+i);
i++;
}

Output

0
2
3
4

For Loop in Java


For Loop in Java is a statement which allows code to be repeatedly executed. For loop contains 3
parts Initialization, Condition and Increment or Decrements

Syntax

for ( initialization; condition; increment )


{
statement(s);
}

Prof. Raju Vathari 49


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

 Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any loop
control variables.
 Condition: This is next step after initialization step, if it is true, the body of the loop is
executed, if it is false then the body of the loop does not execute and flow of control goes
outside of the for loop.
 Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is execute. This statement
allows to update any loop control variables.

Flow Diagram

Control flow of for loop

Prof. Raju Vathari 50


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

 First initialize the variable


 In second step check condition
 In third step control goes inside loop body and execute.
 At last increase the value of variable
 Same process is repeat until condition not false.
Improve your looping conceptFor Loop

Display any message exactly 5 times.


Example of for loop

class Hello
{
public static void main(String args[])
{
int i;
for (i=0: i<5; i++)
{
System.out.println("Hello Friends !");
}
}
}

Output

Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !

Prof. Raju Vathari 51


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

do-while Loop in Java


A do-while loop in Java is similar to a while loop, except that a do-while loop is execute at least one
time.

A do while loop is a control flow statement that executes a block of code at least once, and then
repeatedly executes the block, or not, depending on a given condition at the end of the block (in
while).

When use do..while loop


when we need to repeat the statement block at least one time then use do-while loop. In do-while
loop post-checking process will be occur, that is after execution of the statement block condition part
will be executed.
Syntax

do
{
Statement(s)

increment/decrement (++ or --)


}while();

In below example you can see in this program i=20 and we check condition i is less than 10, that
means condition is false but do..while loop execute onec and print Hello world ! at one time.

Prof. Raju Vathari 52


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Example do..while loop

class dowhileDemo
{
public static void main(String args[])
{
int i=20;
do
{
System.out.println("Hello world !");
i++;
}
while(i<10);
}
}

Output

Hello world !

Example do..while loop

class dowhileDemo
{
public static void main(String args[])
{
int i=0;
do
{
System.out.println(+i);
i++;
}
while(i<5);
}
}

Output

1
2
3
4
5

Prof. Raju Vathari 53


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Enhanced For Loop(For –each loop)

 It is mainly used to traverse the array or collection elements. The advantage of the for-each
loop is that it eliminates the possibility of bugs and makes the code more readable. It is
known as the for-each loop because it traverses each element one by one.
 The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order.
Here, you do not have the option to skip any element because it does not work on an index
basis. Moreover, you cannot traverse the odd or even elements only.
 But, it is recommended to use the Java for-each loop for traversing the elements of array and
collection because it makes the code readable.

Advantages
o It makes the code more readable.
o It eliminates the possibility of programming errors.

Syntax

The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:),
then array or collection.

for(data_type variable : array)


{
//body of for-each loop
}

How it works?

The Java for-each loop traverses the array or collection until the last element. For each element, it
stores the element in the variable and executes the body of the for-each loop.

For-each loop Example: Traversing the array elements


//An example of Java for-each loop

class ForEachExample1
{
public static void main(String args[])
{
//declaring an array
int arr[]= {12,13,14,44};

Prof. Raju Vathari 54


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

//traversing the array with for-each loop


for(int i:arr)
{
System.out.println(i);
}
1. }
2. }

Output:

12
12
14
44

Let us see another of Java for-each loop where we are going to total the elements.

class ForEachExample1
{
public static void main(String args[])
{
int arr[]= {12,13,14,44};
int total=0;
for(int i:arr)
{
total=total+i;
}
System.out.println("Total: "+total);
}
}

Output:
Total: 83

Prof. Raju Vathari 55


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Array in java
Array is a collection of similar type of data. It is fixed in size means that you can't
increase the size of array at run time. It is a collection of homogeneous data elements. It
stores the value on the basis of the index value.

Advantage of Array
1) One variable can store multiple value: The main advantage of the array is we can
represent multiple value under the same name.
2) Code Optimization: No, need to declare a lot of variable of same type data, We can
retrieve and sort data easily.
3) Random access: We can retrieve any data from array with the help of the index
value.

Disadvantage of Array
The main limitation of the array is Size Limit when once we declare array there is
no chance to increase and decrease the size of an array according to our requirement,
Hence memory point of view array concept is not recommended to use. To overcome
this limitation in Java introduces the collection concept.

Types of Array
There are two types of array in Java.
 Single Dimensional Array
 Multidimensional Array

Array Declaration
Single dimension arrays declarations.
Syntax

1. int[] a;
2. int a[];
3. int []a;

Note: At the time of array declaration we cannot specify the size of the array. For
Example int[5] a; this is wrong.

Prof. Raju Vathari 56


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

2D Array declaration.
Def: Multidimensional Arrays can be defined in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order).

Syntax

1. int[][] a;
2. int a[][];
3. int [][]a;
4. int[] a[];
5. int[] []a;
6. int []a[];

2D Array creation
Every array in a Java is an object, Hence we can create array by using new keyword.

Syntax

int[] arr = new int[10]; // The size of array is 10.


or
int[] arr = {10,20,30,40,50};

Accessing array elements


Access the elements of array by using index value of elements.
Syntax

arrayname[n-1];

Access Array Elements

int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[2]);

Prof. Raju Vathari 57


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Example of Array

public class ArrayEx


{
public static void main(String []args)
{
int arr[] = {10,20,30};
for (int i=0; i < arr.length; i++)
{
System.out.println(arr[i]);
}
}
}

Output

10
20
39

Note:
1) At the time of array creation we must be specify the size of array otherwise get an
compile time error. For Example
int[] a=new int[]; Invalid.
int[] a=new int[5]; Valid

2) If we specify the array size as negative int value, then we will get run-time error,
NegativeArraySizeException.

3) To specify the array size the allowed data types are byte, short, int, char If we use
other data type then we will get an Compile time error.

4) The maximum allowed size of array in Java is 2147483647 (It is the maximum value
of int data type)

Prof. Raju Vathari 58


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Difference Between Length and Length() in Java

length: It is a final variable and only applicable for array. It represent size of array.
Example

int[] a=new int[10];


System.out.println(a.length); // 10
System.out.println(a.length()); // Compile time error

length(): It is the final method applicable only for String objects. It represents the
number of characters present in the String.

Example

String s="Java";
System.out.println(s.length()); // 4
System.out.println(s.length); // Compile time error

Example for the 2-D array is matrix addition:


refer: https://www.programmingsimplified.com/java/source-code/java-program-add-matrices

Prof. Raju Vathari 59


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Jagged Array:
 Jagged array is a multidimensional array where member arrays are of different size.
 We can create a 2-D arrays but with variable number of columns in each row. These
type of arrays are also known as Jagged arrays.

Example :
class JaggedArray
{
// Program to illustrate Jagged array in Java
public static void main(String[] args)
{
// Declare a jagged array containing three elements
int[][] arr = new int[3][];

// Initialize the elements


arr[0] = new int[] { 1, 2, 3 };
arr[1] = new int[] { 4, 5, 6, 7 };
arr[2] = new int[] { 8, 9 };

// print the array elements


for (int[] row : arr)
System.out.println(Arrays.toString(row));
}
}
OUTPUT:
[1, 2, 3]
[4, 5, 6, 7]
[8, 9]

Prof. Raju Vathari 60


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

int[][] arr = new int[3][];


// this will initialize the array elements by 0
arr[0] = new int[1];
arr[1] = new int[2];
arr[2] = new int[3];

Prof. Raju Vathari 61


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Command Line Arguments in Java


If any input value is passed through the command prompt at the time of running of the
program is known as command line argument by default every command line argument will
be treated as string value and those are stored in a string array of main() method.

Syntax for Compile and Run CMD programs

Compile By -> Javac Mainclass.java

Run By -> Java Mainclass value1 value2 value3 ....................

Program Command Line Argument in Java

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Argument is: "+args[0]);
}
}

Compile and Run above programs

Compile By > Javac CommandLineExample.java

Run By > Java CommandLineExample RAJUVATHARI

Output

Argument is: RAJUVATHARI

Prof. Raju Vathari 62


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

Example of command-line argument in java

class Demo1
{
public static void main(String args[])
{
System.out.println("First argument is: "+args[0]);
System.out.println("Second argument is: "+args[1]);
}
}

Compile and Run above programs

Compile By > Javac Demo1.java


Run By > Java SumDemo 10 20

Output

First argument is: 10


Second argument is: 20

When the above statement is executing the following sequence of steps will take place.

 Class loader sub-system loads Demo1 along with Command line argument(10, 20) and in
main memory.

 JVM takes the loaded class Demo1 along with Command line arguments (10, 20) and
place the number of values in the length variable that is 2.

 JVM looks for main() that is JVM will place the Command in the main() in the form of
string class that is.

10
main(String args[length])  args
20

Prof. Raju Vathari 63


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

 Hence all the CMD line arguments of Java are sending to main() method available in the
form of an array of object of String class (every CMD are available or stored in main
method in the form of an array of object of String class).

 JVM calls the main() method with respect to load class Demo1 that is Demo1.main().

Accept command line arguments and display their values

class CMD
{
public static void main(String args[])
{
System.out.println("no. of arguments ="+ args.length);
for(int i=0;i< args.length;i++)
{
System.out.println(args.[i]);
}
}
}

Note: Except + operator any numeric operation not allowed in command line arguments.

Prof. Raju Vathari 64


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

1. Write a Java program to find factorial of a number reading input as


command line argument.
Factorial.java

import java.io.*;
public class Factorial
{
public static void main(String args[])
{

int fact=1,n;
if(args.length==1)
{
n=Integer.parseInt(args[0]); //convert entered argument into integer
for(int i=1;i<n;i++)
{
fact=fact*i;
}
System.out.println("Factorial of a given number is: "+fact);
}
else if(args.length>1)
{
System.out.println("More than one argument entered");
}
else
{
System.out.println("No command line arguments are passed");
}
}
}
OUTPUT:
C:\Users\staff1>set path="C:\Program Files\Java\jdk1.7.0\bin"
C:\Users\staff1>cd C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>javac Factorial.java

RUN 1:
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>java Factorial

No command line arguments are passed

RUN 2:

Prof. Raju Vathari 65


KLE’s BK BCA College Chikodi Introduction to OOPS in JAVA

C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>java Factorial 8


Factorial of a given number is: 5040

RUN 3:
C:\Users\staff1\Desktop\JAVA PROGRAMS\Journal_Programs>java Factorial 8 9
More than one argument entered

Prof. Raju Vathari 66

S-ar putea să vă placă și