0% found this document useful (0 votes)
11 views101 pages

Fundamentals of Object-Oriented Programming

The document provides an overview of Java programming, focusing on the fundamentals of Object-Oriented Programming (OOP) and its key concepts such as classes, objects, inheritance, and polymorphism. It outlines the features of Java, including its simplicity, portability, and security, as well as the history of Java's development and its evolution through various versions. Additionally, it describes the Java Development Kit (JDK), Java Runtime Environment (JRE), and the structure of a Java program.

Uploaded by

Amruta Sawakar
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)
11 views101 pages

Fundamentals of Object-Oriented Programming

The document provides an overview of Java programming, focusing on the fundamentals of Object-Oriented Programming (OOP) and its key concepts such as classes, objects, inheritance, and polymorphism. It outlines the features of Java, including its simplicity, portability, and security, as well as the history of Java's development and its evolution through various versions. Additionally, it describes the Java Development Kit (JDK), Java Runtime Environment (JRE), and the structure of a Java program.

Uploaded by

Amruta Sawakar
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

JAVA Programming

UNIT I
Fundamentals of Object
Oriented Programming(OOP)
Prof: Santosh.S.B
ARJ BCA College Ilkal.
 Object oriented programming(oop) is a
approach to program organization and
development, which attempt to eliminate the
some of the pitfalls of conventional
programming methods by incorporating the
best of structural programming features with
several new concepts.
 It is the new way of organizing and
developing programs and has nothing to do
with any particular language.
 Java is pure object oriented language.
Object oriented paradigm
• The major objective of object-oriented approach is to
eliminate some of the laws encountered in the
procedural approach.
• OOP treats data as a critical clement in the program
development and does not allow it to flow freely
around the system.
• OOP allows us to decompose a problem into a number
of entities called Objects and then build data and
functions (known as methods in Java) around these
entities.
• The combination of data and methods make up an
object The data of an object can be accessed only by
the methods associated with that object .
Features of Object oriented paradigm
• Emphasis is on data rather than procedure.
• Programs are divided into what are known as Objects.
• Data structures are designed such that they
characterize the objects.
• Methods that operate on the data of an object are tied
together in the data structure
• Data is hidden and cannot be accessed by external
functions.
• Objects may communicate with each other through
methods.
• New data and methods can be easily added
whenever necessary.
• Follows bottom-up approach in program
design.
Definition of OOP
“Object-oriented program that provides a way of
modularizing programs by creating partitioned
memory area for both data and functions that
can be used as templates for creating copies
of such modules on demand.”
This means that an object is considered to be a
partitioned area of computer memory that
stores data and set of operations that can
access the data
Basic OOP concept

• Object
• Classes
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Message Passing
Objects
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 without knowing the
details of each other's data or code.
objects
Classes
• Collection of objects is called class. It is a
logical entity.
• A class can also be defined as a blueprint from
which you can create an individual object.
Class doesn't consume any space.
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
Abstraction
• Hiding internal details and showing
functionality is known as abstraction.
For example phone call, we don't know the internal
processing.
• In Java, we use abstract class and interface to
achieve abstraction.
• Data Abstraction is the property by virtue of
which only the essential details are displayed to
the user.
• The trivial or the non-essentials units are not
displayed to the user.
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.
• A java class is the example of encapsulation. Java bean is the
fully encapsulated class because all the data members are
private here.
Inheritance

When one object acquires all the properties and


behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is
used to achieve runtime polymorphism.
• inheritance is an important pillar of
OOP(Object Oriented Programming).
• It is the mechanism in java by which one class
is allow to inherit the features(fields and
methods) of another class.
inheritance
polymorphism
• If one task is performed in different ways, it is
known as polymorphism. For example: to
convince the customer differently, to draw
something, for example, shape, triangle,
rectangle, etc.
• In Java, we use method overloading and method
overriding to achieve polymorphism.
• Another example can be to speak something; for
example, a cat speaks meow, dog barks woof, etc.
polymorpism
Message Passing
Message Passing: Objects communicate with one
another by sending and receiving information to
each other.
• A message for an object is a request for execution
of a procedure and therefore will invoke a
function in the receiving object that generates
the desired results.
• Message passing involves specifying the name of
the object, the name of the function and the
information to be sent.
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.
However, it was 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.
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) Initially designed for small, embedded systems in electronic
appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the
file extension was .gt.
4) After that, it was called Oak and was developed as a part of
the Green project.
Why Java named "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)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.
8) Java is an island of Indonesia where the first coffee was
produced (called java coffee). It is a kind of espresso bean.
Java name was chosen by James Gosling while having
coffee near 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 released in(January 23, 1996). After the first release of Java, there have
been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds the new features in Java.

Java Version History


• Many java versions have been released till now. The current stable release of Java
is Java SE 10.
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan 1996)
• JDK 1.1 (19th Feb 1997)
• J2SE 1.2 (8th Dec 1998)
• J2SE 1.3 (8th May 2000)
• J2SE 1.4 (6th Feb 2002)
• J2SE 5.0 (30th Sep 2004)
• Java SE 6 (11th Dec 2006)
• Java SE 7 (28th July 2011)
• Java SE 8 (18th Mar 2014)
• Java SE 9 (21st Sep 2017)
• Java SE 10 (20th Mar 2018)
Features of Java
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
1. Simple
Java is very easy to learn, and its syntax is
simple, clean and easy to understand.
According to Sun, Java language is a simple
programming language because:
• Java syntax is based on C++ (so easier for
programmers to learn it after C++).
• Java has removed many complicated and
rarely-used features, for example, explicit
pointers, operator overloading, etc.
[Link]-Oriented
Java is an object-oriented programming language.
Everything in Java is an object. Object-oriented
means we organize our software as a
combination of different types of objects that
incorporates both data and behavior.
• Basic concepts of OOPs are: Object, Class,
Inheritance ,Polymorphism ,Abstraction
,Encapsulation .
3. Portable
Java is portable because it facilitates you to carry
the Java bytecode to any platform. It doesn't
require any implementation.
4. Platform independent
• Java is platform independent because it is
different from other languages like C, C++, etc.
which are compiled into platform specific
machines while Java is a write once, run
anywhere language. A platform is the hardware
or software environment in which a program runs
• Java code can be run on multiple platforms, for
example, 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).
5. Secured
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS,
Cryptography etc
6. Robust
Robust simply means strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security
problems.
• There is automatic garbage collection in java
which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java
application anymore.
• There are exception handling and the type
checking mechanism in Java. All these points
make Java robust.
[Link] neutral
• Java is architecture neutral because there are no
implementation dependent features, for
example, the size of primitive types is fixed.
• Java compiler generates an architecture-neutral
object file format, which makes the compiled
code executable on many processors, with the
presence of Java runtime system
8. Interpreted
Java byte code is translated on the fly to native
machine instructions and is not stored anywhere.
The development process is more rapid and
analytical since the linking is an incremental and
light-weight process.
9. High Performance
With the use of Just-In-Time compilers, Java enables high
performance. Java is faster than other traditional
interpreted programming languages because Java bytecode
is "close" to native code.
10. Multithreaded
With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This
design feature allows the developers to construct
interactive applications that can run smoothly.
11. Distributed
Java is distributed because it facilitates users to create
distributed applications in Java. RMI and EJB are used for
creating distributed applications. This feature of Java makes
us able to access files by calling the methods from any
machine on the internet.
12. Dynamic
• Java is a dynamic language. It supports
dynamic loading of classes. It means classes
are loaded on demand. It also supports
functions from its native languages, i.e., C and
C++.
• Java supports dynamic compilation and
automatic memory management (garbage
collection).
JDK Environment
JDK is an acronym for Java Development Kit. The Java Development Kit
(JDK) is a software development environment which is used to
develop Java applications and applets. It physically exists. It contains
JRE + development tools.
A Primer The Java Development Kit comes with a collection of tools
that are used for developing and running java programs.
They include:
• appletviewer (for viewing Java applets)
• javac (Java compiler)
• java (Java interpreter)
• javap (Java disassembler)
• javah (for C header files)
• javadoc (for creating HTML documents)
• jdb (Java debugger)
appletviewer :Enables us to run Java applets (without
actually using a Java-compatible browser) Java
interpreter, which runs applets and applications by
reading and interpreting bytecode files.
Javac: The Java compiler, which translates Java source
code to bytecode files that the interpreter can
understand.
javadoc: Creates HTML-format documentation from Java
source code files.
Javah: Produces header files for use with native methods.
Javap: Java disassembler, which enables us to convert
bytecode files into a program description.
Jdb: java debugger, wich helps us to find errors in our
programs.
Java Virtual Machine
• All language compilers translate source code into
machine code for a specific computer compiler also
does the same thing.
• Then, how does Java achieve architecture neutrality?
• The answer that the Java compiler produces an
intermediat code known as bytecode for a machine
that does not exist.
• This machine is called the Java Virtual Machine and it
exists only inside the computer memory.
• It is simulated computer within the computer and does
all major functions of a real computer.
Process of compilation

Java Java Virtual


Program Compiler machine

Source code Byte code


The virtual machine code is not machine specific. The machine
specific code (known as machine code) is generated by the
Java interpreter by acting as an intermediary between the
virtual machine and the real machine .
Process of converting bytecode into machine code
Java Machine
Bytecode
Interpreter Code
virtual machine real machine
How java works?
Java Runtime environment
Java Runtime Environment (JRE) facilitates the execution of
programs developed in Java. It primarily comprises of the
following.
Java Virtual Machine (JVM): It is a program that interprets the
intermediate Java byte code and generates the desired
output. It is because of byte code and JVM concepts that
programs written in Java are highly portable.
Runtime class libraries: These are a set of core class libraries
that are required for the execution of java programs.
User interface toolkits: AWT and Swing are examples of
toolkits that support varied input methods for the users to
interact with the application program.
deployment technologies: JRE comprises the
following key deployment technologies:
• Java plug-in: Enables the execution of a Java
applet on the browser.
• Java Web Start: Enables remote-deployment
of an application. With Web Start, users can
launch an application directly from the Web
browser without going through the
installation procedure.
Java Program Structure
• Documentation Section :-The documentation section
comprises a set of comment lines giving the name of
the program, the author and other details, which the
programmer would like to refer to at a later stage.
Comments must explain why and what of classes and
how of algorithms.
• Package Statement :-The first statement allowed in a
Java file is a package statement. This statement
declares a package name and informs the compiler that
the classes defined here belong to this package.
Example:
package student;
The package statement is optional. That is, our classes do
not have to be part of a package.
• Import Statement :-
The next thing after a package statement (but before any class
definition) may be a number of import statements. This is
similar to the #include statement in C. Example,

import [Link];

This statement instructs the interpreter to load the test class


contained in the package student. Using import statement,
we can have access to classes that are part of other named
packages.
• Interface Statement :- An interface is like a class but
includes a group of method declarations. This is also an
optional section and is used only when we wish to
implement the multiple inheritance feature in the program.
• Class Definitions :-A Java program may contain
multiple class definitions. Classes are the primary and
essential elements of a Java program. These classes are
used to map the objects of real-world problems. The
number of classes used depends on the complexity of
the problem.

• Main Method Class :-Since every Java stand-alone


program requires a main method as its starting point,
this class is the essential part of Java program. A simple
Java program may contain only this part. The main
method creates objects of various classes and
establishes communications between them. On
reaching the end of main, the program terminates and
the control passes back to the operating system.
Keywords
Java keywords are also known as reserved words. Keywords are particular words
which acts as a key to a code. These are predefined words by Java so it cannot be
used as a variable or object name.
• abstract: Java abstract keyword is used to declare abstract class.
Abstract class can provide the implementation of interface. It can have
abstract and non-abstract methods.
• boolean: Java boolean keyword is used to declare a variable as a
boolean type. It can hold True and False values only.
• break: Java break keyword is used to break loop or switch statement. It
breaks the current flow of the program at specified condition.
• byte: Java byte keyword is used to declare a variable that can hold an
8-bit data values.
• case: Java case keyword is used to with the switch statements to mark
blocks of text.
• catch: Java catch keyword is used to catch the
exceptions generated by try statements. It must
be used after the try block only.
• char: Java char keyword is used to declare a
variable that can hold unsigned 16-bit Unicode
characters
• class: Java class keyword is used to declare a
class.
• continue: Java continue keyword is used to
continue the loop. It continues the current flow
of the program and skips the remaining code at
the specified condition.
• default: Java default keyword is used to specify the default block of
code in a switch statement.
• do: Java do keyword is used in control statement to declare a loop.
It can iterate a part of the program several times.
• double: Java double keyword is used to declare a variable that can
hold a 64-bit floating-point numbers.
• else: Java else keyword is used to indicate the alternative branches
in an if statement.
• enum: Java enum keyword is used to define a fixed set of constants.
Enum constructors are always private or default.
• extends: Java extends keyword is used to indicate that a class is
derived from another class or interface.
• final: Java final keyword is used to indicate that a variable holds a
constant value. It is applied with a variable. It is used to restrict the
user.
• finally: Java finally keyword indicates a block of code in a try-catch
structure. This block is always executed whether exception is
handled or not.
• float: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
• for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some conditions become true. If the
number of iteration is fixed, it is recommended to use for loop.
• if: Java if keyword tests the condition. It executes the if block if condition is true.
• super: Java super keyword is a reference variable that is used to refer parent class
object. It can be used to invoke immediate parent class method.
• switch: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable against
multiple values.
• synchronized: Java synchronized keyword is used to specify the critical sections or
methods in multithreaded code.
• this: Java this keyword can be used to refer the current object in a method or
constructor.
• throw: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exception. It is followed by an instance.
• throws: The Java throws keyword is used to declare an exception. Checked
exception can be propagated with throws.
• int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
• interface: Java interface keyword is used to declare an interface. It can have only
abstract methods.
• long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
• native: Java native keyword is used to specify that a method is implemented in
native code using JNI (Java Native Interface).
• new: Java new keyword is used to create new objects.
• null: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.
• package: Java package keyword is used to declare a Java package that includes the
classes.
• private: Java private keyword is an access modifier. It is used to indicate that a
method or variable may be accessed only in the class in which it is declared.
• protected: Java protected keyword is an access modifier. It can be accessible
within package and outside the package but through inheritance only. It can't be
applied on the class.
• public: Java public keyword is an access modifier. It is used to indicate that an item
is accessible anywhere. It has the widest scope among all other modifiers.
• return: Java return keyword is used to return from a method when its execution is
complete.
identifiers
Identifiers are the name given to variables, classes, methods.
Rules for Naming an Identifier
• Identifiers cannot be a keyword.
• Identifiers are case-sensitive.
• It can have a sequence of letters and digits. However, it
must begin with a letter, $ or _. The first letter of an
identifier cannot be a digit.
• It's a convention to start an identifier with a letter rather
and $ or _.
• Whitespaces are not allowed.
• Similarly, you cannot use symbols such as @, #, and so on.
Example: int score;
• Here, score is a variable (an identifier). You cannot use
keywords as variable names. It's because keywords
have predefined meanings. For example,
int float;
The above code is wrong. It's because float is a keyword
and cannot be used as a variable name.
int marks;
float avg;
• For class names we use identifiers like
Student, HelloJava
Data Types
Java Primitive Data Types
• In Java language, primitive data types are the building
blocks of data manipulation. These are the most basic
data types available in Java language.
There are 8 types of primitive data types:
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
Integer Data Type
• The int data type is generally used as a default data
type for integral values unless if there is no problem
about memory.
• The int data type is a 32-bit signed two's complement
integer. Its value-range lies between - 2,147,483,648 (-
2^31) to 2,147,483,647 (2^31 -1) (inclusive)
Example: int a = 100000, int b = -200000

Float Data Type


The float data type is a single-precision 32-bit IEEE
754 floating point. Use a float (instead of double) if you
need to save memory in large arrays of floating point
numbers.
Example: float f1 = 234.5f
Boolean Data Type
• The Boolean data type is used to store only two
possible values: true and false. This data type is used
for simple flags that track true/false conditions.
• The Boolean data type specifies one bit of information,
but its "size" can't be defined precisely.
Example: Boolean one = false

Character Data Type


• The char data type is a single 16-bit Unicode character.
Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).The char data type is used to store
characters.
• Example: char letterA = 'A'
Double Data Type
• The double data type is a double-precision 64-bit IEEE 754 floating
point. Its value range is unlimited. The double data type is generally
used for decimal values just like float.
Example: double d1 = 12.3

Short Data Type


• The short data type is a 16-bit signed two's complement integer. Its
value-range lies between -32,768 to 32,767 (inclusive). Its minimum
value is -32,768 and maximum value is 32,767. Its default value is 0.
• The short data type can also be used to save memory just like byte
data type. A short data type is 2 times smaller than an integer.
Example: short s = 10000, short r = -5000
Long Data Type
• The long data type is a 64-bit two's complement integer. The long
data type is used when you need a range of values more than those
provided by int.
• Example: long a = 100000L, long b = -200000L
Simple Java Program
class Simple
{
public static void main(String args[]){
[Link]("Hello Java");
}
}

save this file as [Link]


• To compile: javac [Link]
• To execute: java Simple
• Output: Hello Java
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[],
[Link]().
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility. It
means it is visible to all.
• static is a keyword. If we declare any method as static, it is known as
the static method. The core advantage of the static method is that
there is no need to create an object to invoke the static method. The
main method is executed by the JVM, so it doesn't require to create an
object to invoke the main method. So it saves memory.
• void is the return type of the method. It means it doesn't return any
value.
• main represents the starting point of the program.
• String[] args is used for command line argument. We will learn it later.
• [Link]() is used to print statement. Here, System is a class,
out is the object of PrintStream class, println() is the method of
PrintStream class. We will learn about the internal working of
[Link] statement later.
Type casting in java
Type casting means conversion of a variable from
one data type to another. The value may be lost
when large type is converted to a smaller type.
or
• When you assign value of one data type to
another, the two types might not be compatible
with each other. If the data types are compatible,
then Java will perform the conversion
automatically known as Automatic Type
Conversion and if not then they need to be casted
or converted explicitly.
1. Widening or Automatic type conversion
Widening casting is done automatically when passing a
smaller size type to a larger size type.
converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
public class MyClass
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
}
}
[Link] or Explicit Conversion
• If we want to assign a value of larger data type to a smaller
data type we perform explicit type casting or narrowing.
• Narrowing casting must be done manually by placing the type
in parentheses in front of the value.
Example:
public class MyClass
{
public static void main(String[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to
int [Link](myDouble); // Outputs 9.78
[Link](myInt); // Outputs 9
}
}
Variables
• A variable is a container which holds the value
while the Java program is executed. A variable
is assigned with a data type.
• Variable is a name of memory location. There
are three types of variables in java:
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 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.
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.
Example to understand the types of variables in java

class Rcb{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
} //end of class
Declaring (Creating) Variables
• To create a variable, you must specify the type
and assign it a value:
Syntax: type variable = value;
Example:
• Create a variable called myNum of type int and assign it the
value 15:
int myNum = 15;
[Link](myNum);
Other Types
• A demonstration of how to declare variables
of other types:

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Adding two numbers using variables
class Simple
{
public static void main(String[] args)
{
int a=10; // variable a
int b=10; // variable b
int c=a+b;
[Link](c);
}}
Expressions
A Java expression consists
of variables, operators, literals, and method calls.
For example
int score;
score = 90;
Here, score = 90 is an expression that returns an int.
Consider another example,
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4;
Here, a + b - 3.4 is an expression.
if (number1 == number2)
{
[Link]("Number 1 is larger than number 2");
}
Here, number1 == number2 is an expression
that returns a boolean value.
Similarly, "Number 1 is larger than number
2" is a string expression.
Java Coding conventions
(Java Naming conventions)
• Java naming convention is a rule to follow as you
decide what to name your identifiers such as
class, package, variable, constant, method, etc.
• But, it is not forced to follow. So, it is known as
convention not rule. These conventions are
suggested by several Java communities such as
Sun Microsystems and Netscape.
• All the classes, interfaces, packages, methods and
fields of Java programming language are given
according to the Java naming convention. If you
fail to follow these conventions, it may generate
confusion or erroneous code.
Advantage of naming conventions in java
• By using standard Java naming conventions, you
make your code easier to read for yourself and
other programmers.
• Readability of Java program is very important. It
indicates that less time is spent to figure out what
the code does.
The following are the key rules that must be
followed by every identifier:
• The name must not contain any white spaces.
• The name should not start with special characters
like & (ampersand), $ (dollar), _ (underscore).
Let's see some other rules that should be followed
by identifiers.
1. Class
• It should start with the uppercase letter.
• It should be a noun such as Color, Button, System, Thread, etc.
• Use appropriate words, instead of acronyms.
Example: -
public class Employee
{
//code snippet
}
[Link]
• It should start with the uppercase letter.
• It should be an adjective such as Runnable, Remote, ActionListener.
• Use appropriate words, instead of acronyms.
Example: -
interface Printable
{
//code snippet
}
[Link]
• It should start with lowercase letter.
• It should be a verb such as main(), print(), println().
• If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such
as actionPerformed().
Example:-
class Employee
{
void draw() //method
{
//code snippet
} }

[Link]
• It should be a lowercase letter such as java, lang.
• If the name contains multiple words, it should be separated by dots (.)
such as [Link], [Link].
Example :-
package [Link]; //package
class Employee
{
//code snippet
}
[Link]
• It should start with a lowercase letter such as id, name.
• It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
• If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such
as firstName, lastName.
Example :-
class Employee
{
int id; //variable
//code snippet
}
[Link]
• It should be in uppercase letters such as RED, YELLOW.
• If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY.
• It may contain digits but not as the first letter.
Example :-
class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}
Control structures
There may be a situation when you need to execute
a block of code several number of times. In
general, statements are executed sequentially:
• Programming languages provide various control
structures that allow for more complicated
execution paths.
• A loop statement allows us to execute a
statement or group of statements multiple times
Java control structures are two types namely
• Entry control
• Exit Control
1. While loop
A while loop statement in Java programming language repeatedly
executes a target statement as long as a given condition is true.
Syntax
while(test condition)
{
// Statements
}

• Here, statement(s) may be a single statement or a block of


statements. The condition may be any expression, and true is any
non zero value.
• When executing, if the boolean_expression(test condition) result is
true, then the actions inside the loop will be executed. This will
continue as long as the expression result is true.
2. do while loop
A do...while loop is similar to a while loop, except that a
do...while loop is guaranteed to execute at l
Syntax
Following is the syntax of a do...while loop −
do {
// Statements
}
while(test condition);

• Notice that the test condition appears at the end of the


loop, so the statements in the loop execute once before the
Boolean is tested.
• If the condition is true, the control jumps back up to do
statement, and the statements in the loop execute again.
This process repeats until the Boolean expression is false.
3. For loop
• A for loop is a repetition control structure that allows
you to efficiently write a loop that needs to be
executed a specific number of times.
• A for loop is useful when you know how many times a
task is to be repeated.
Syntax
The syntax of a for loop is −

for(initialization; test condition; increment)


{
// Statements
}
• Initialization: It is the initial condition which is
executed once when the loop starts. Here, we can
initialize the variable, or we can use an already
initialized variable. It is an optional condition.
• Condition: It is the second condition which is executed
each time to test the condition of the loop. It continues
execution until the condition is false. It must return
boolean value either true or false. It is an optional
condition.
• Statement: The statement of the loop is executed each
time until the second condition is false.
• Increment/Decrement: It increments or decrements
the variable value. It is an optional condition.
Decision making statements
Decision Making in programming is similar to decision making in real
life. In programming also we face some situations where we want a
certain block of code to be executed when some condition is
fulfilled.
A programming language uses control statements to control the flow
of execution of program based on certain conditions
• if
• if-else
• nested-if
• if-else-if or else if ladder
• switch-case
• jump – break, continue, return
If: if statement is the most simple decision making statement. It is used to
decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a block of statement
is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Example:
public class Test
{
public static void main(String args[]) {
int age = 18;
if( age > 17 ) {
[Link](“right tovote");
}}
}
if-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.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
nested if 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.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
public class JavaNestedIfExample {
public static void main(String[] args) {
int age=20;
int weight=80;
if(age>=18){
if(weight>50){
[Link]("You are eligible to donat
e blood");
}
}
}}
if-else-if ladder
Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the
final else statement will be executed.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;

if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
}
Output:
i is 20
A switch statement allows a variable to be tested
for equality against a list of values. Each value is
called a case, and the variable being switched on
is checked for each case.
Syntax
The syntax of enhanced for loop is −
switch(expression)
{ case value : // Statements break;
// optional case value :
// Statements break;
// optional
// You can have any number of case statements.
default : // Optional // Statements }
Java Arrays
• Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for
each value.
• To declare an array, define the variable type
with square brackets:
Declaring Array Variables
• To use an array in a program, you must declare a
variable to reference the array, and you must specify
the type of array the variable can reference. Here is the
syntax for declaring an array variable −
Syntax
• dataType[] arrayRefVar; // preferred way. or
• dataType arrayRefVar[]; // works but not preferred way.
Example
• The following code snippets are examples of this
syntax −
• double[] myList; // preferred way. or
• double myList[]; // works but not preferred way.
We have now declared a variable that holds an array of
strings. To insert values to it, we can use an array literal
- place the values in a comma-separated list, inside
curly braces:
• To create array of strings
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

• To create an array of integers, you could write:


int[] myNum = {10, 20, 30, 40};
Java Command Line Arguments
• 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.
it provides a convenient way to check the
behavior of the program for the different
values.
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 CommandLineExample
{
public static void main(String args[])
{
[Link]("Your first argument is: "+args[0]);
}
}
• compile by > javac [Link]
• run by > java CommandLineExample mykk
• Output: Your first argument is: mykk
command-line argument that prints all the values
class San
{
public static void main(String args[]){

for(int i=0;i<[Link];i++)
{
[Link](args[i]);

}
}
compile by > javac [Link]
run by > java San arj bca 1 3 abc
Output: arj bca 1 3 abc
• Using command line arguments
After writing a Java program we will compile it using the
command javac and run it using the command javas.
Consider the following code −
Example
public class Sample
{
public static void main(String[] args){
int a = 20;
int b = 30;
int c = a+b;
[Link]("Sum of the two numbers is "+c);
}
}
Here, we are hard coding (fixing to a specific value) the values of a
and b which is not recommendable.

Example
In the following example we are rewriting the above program, by
accepting the (two integer) values from the command line. And, we are
extracting these two from the String array in the main method and
converting them to integer −
public class Sample {
public static void main(String[] args){
int a = [Link](args[0]);
int b = [Link](args[1]);
int c = a+b;
[Link]("Sum of the two numbers is "+c);
}
}
Output

You can compile and, run the program by passing the values at
execution line through command prompt as shown below

You might also like