0% found this document useful (0 votes)
29 views27 pages

OOPS Class Notes-V1

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

OOPS Class Notes-V1

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

UNIT- I: Introduction to Object Oriented Concepts and Java:Java's Magic:

the Byte code; Java Development Kit (JDK); The Java Buzz words, Object Oriented Programming -
Two Paradigms, Abstraction, The Three OOP Principles and its advantages, Simple Java programs.
Data types, variables and arrays, Operators, Control Statements.

Programming Paradigm:
A programming paradigm is the classification, style or way of programming. It is an
approach to solve problems by using programming languages. Each paradigm consists of
certain structures, features, and opinions about how common programming problems
should be tackled.

Modern programming paradigm can be classified into 2 main types. Imperative


programming Paradigm and declarative programming paradigm.

Imperative programming paradigms:


The imperative paradigm is said to be command driven. The program code is
imperative paradigm directs the program execution as sequence of statements executed
one by one. The imperative style program consists of set of program statements. Each
statement directs the computer to perform specific task. Each statement directs what is to
be done and how it is to be done. Imperative programming is divided into three broad
categories: Procedural, OOP and parallel processing.

Declarative Programming paradigms:


The declarative paradigm is focused on the logic of the program and the end result.
In this paradigm that control flow is not the important element of the program. The main
focus of the declarative style of programming is achieving the end result.

Procedural Programming
Procedural programming can also be referred to as imperative programming. It is a
programming paradigm based upon the concept of procedure calls, in which statements are
structured into procedures (also known as subroutines or functions). They are a list of
instructions to tell the computer what to do step by step, Procedural programming
languages are known as top-down languages. Most of the early programming languages are
all procedural.
Examples: Fortran C and Cobol.
Features of Procedural Code
 Procedural Programming is excellent for general-purpose programming
 The coded simplicity along with ease of implementation of compilers and
interpreters
 A large variety of books and online course material available on tested algorithms,
making it easier to learn.
 The source code is portable
 The code can be reused in different parts of the program, without the need to copy it
 The program flow can be tracked easily as it has a top-down approach.

Object-Oriented Programming(OO):
In this framework, all real-world entities are represented by Classes. Objects are instances of
classes so each object encapsulates a state and behavior. State implies the fields, attributes
of the object and behavior is what you do with the state of the object and they are the
methods. Objects interact with each other by passing messages.

Features of OO:
 Encapsulation – This is a fundamental feature of Object-Oriented Programming. Here
you hide unnecessary details in classes and deliver a simple and clear interface for
working. It describes the idea of bundling data and methods that work on that data
within one unit. This concept is also often used to hide the internal representation,
or state, of an object from the outside
 Inheritance - Inheritance is one of the core concepts of object-oriented programming
(OOP) languages. It is a mechanism where you can derive a class from another class
for a hierarchy of classes that share a set of attributes and methods. It explains how
the class hierarchies develop code readability and support to the reuse of
functionality.
 Data Abstraction - to Data abstraction is the reduction of a particular body of data to
a simplified representation of the whole. Data abstraction is usually the first step in
database design.
 Polymorphism - Polymorphism is an object-oriented programming concept that
refers to the ability of a variable, function or object to take on multiple forms.
Programming languages that have implemented the OO paradigm are: Ruby, Java, C++,
Python, Simula (the first OOP language)

Difference of POP & OOP

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is In object-oriented programming, the program is


divided into small parts called functions. divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows a bottom-up


approach. approach.
Procedural Oriented Programming Object-Oriented Programming

There is no access specifier in procedural Object-oriented programming has access specifiers


programming. like private, public, protected.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any Object-oriented programming provides data hiding
proper way of hiding data so it is less secure. so it is more secure.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.

In procedural programming, there is no concept In object-oriented programming, the concept of


of data hiding and inheritance. data hiding and inheritance is used.

In procedural programming, the function is In object-oriented programming, data is more


more important than the data. important than function.

Procedural programming is based on the unreal Object-oriented programming is based on the real
world. world.

Procedural programming is used for designing Object-oriented programming is used for designing
medium-sized programs. large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the concept of
procedure abstraction. data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Introduction of JAVA
Java is an object-oriented, cross-platform programming language introduced in 1995 by
Sun Microsystems. Today, Java helps run many applications, including Sports, Social
Media, Audio, Video, etc.

History of Java
James Gosling, often called as the father of Java pioneered Java in June 1991 as a
project called ‘Oak.’ Gosling aimed to develop a virtual machine and language with a
well-known notation like C but with more precision and simplicity than C/C++. In 1995,
Java 1.0 was the first public execution. It pledged ‘Write Once, Run Anywhere’ on
popular platforms with free runtimes. It was very safe and configurable, with security
restricting network and file access.
Between the initial implementation of Oak, and the public announcement of Java in the
spring of 1995, many more people contributed to the design and evolution of the
language. The other key contributories to the maturing of the original prototype of the
Java programming language were:
• Bill Joy
• Arthur van Hoff
• Jonathan Payne
• Frank Yellin
• Tim Lindholm
Features of Java
A list of the most important features of the Java language is given below.
 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Dynamic
Simple:
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun Microsystem, Java language is a simple programming language 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.
There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behaviour.

Platform Independent
Java code can be executed 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).

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
 Classloader: Classloader in Java is a part of the Java Runtime Environment
(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
 Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.

Dynamic
Java is a dynamic language. It supports the 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 Platform (Ecosystem)


Java platform is only a software-based platform that runs on top of other hardware-
based platforms such as Microsoft Windows, Linux, and Mac.
Java Development Kit (JDK) is a software development environment that is developed and
distributed by Oracle. It is used for building (developing) java software applications and
applets. In simple words, it is used to write java programs by programmers.
Architecture of JAVA:

Java Development Kit has the following components. They are as follows:

a) Java Development Tools: It consists of Java compiler, JAR tool, class file disassembler,
debugger, JRE builder, etc. Java Development Tools provides everything for compiling,
running, monitoring, debugging, and documenting applications.
The most important tools are javac compiler, java launcher, and javadoc documentation
tool.

b) Java Runtime Environment (JRE): It is an environment that is required for running


(executing) a java application. It cannot be used for the development of Java applications. It
is used only for executing the application program.
Java Runtime Environment is a collection of programs that contain JVM (Java Virtual
Machine), Java APIs (Application Programming Interface), and Java Class Libraries that help
in the development of Java application programs.

c) Java Language Specification: The Java language specification is a technical definition of


syntax and semantics of the Java programming language.

d) Bytecode in Java is a highly optimized set of instructions for the Java Virtual
Machine (JVM) that reads and interprets to run the java program. A bytecode is a binary
program code that can only run on JVM. In other words, it is a machine language (code) for
JVM in the form of .class file, but it is not machine specific because it is not a native code.
Byte code acts as an intermediate language that is platform (machine) independent. It is
generated by Java interpreter that can be directly run by a real machine.

Java bytecode has two most important characteristics that are as follows:
 Byte code is independent of processor, i.e., Java program can be executed on any
processor architecture.
 It does not depend on operating systems such as Windows, Linux, and Mac OS.
Java source code file (with a .java extension) are compiled into bytecode (with a .class
extension), which is then interpreted and executed by a Java processor called JVM.
Flow of the process :

Step1: Create a java source code with .java extension

Step2: Compile the source code using java compiler, which will create bytecode file
with .class extension

Step3: Class loader reads both the user defined and library classes into the memory for
execution

Step4: Bytecode verifier validates all the bytecodes are valid and do not violate Java’s
security restrictions

Step5: JVM reads bytecodes and translates into machine code for execution. While
execution of the program the code will interact to the operating system and hardware

1. A bytecode in Java is a set of byte-long instructions that Java compiler produces and Java
interpreter (JVM) executes.
2. When Java compiler compiles .java file, it generates a series of bytecode (machine
independent code) and stores them in a .class file.
3. JVM then interprets and executes the byte code stored in the .class file and converts
them into machine code.
4. The byte code remains the same on different platforms such as Windows, Linux and Mac
OS.

Components of Java Runtime Environment (JRE)

JRE consists of the following main components that are as follows:


 Java API (Application Programming Interface)
 Class Loader
 Bytecode verifier
 Java Virtual Machine (Interpreter)
JAVA API :
Java Application Programming Interface (API) is a very large collection of
prepackaged, ready-made software components that provides the core functionality of the
Java programming language.

In simple words, Java API is a large collection of already defined classes, interfaces,
and methods in the form of Java packages.
Java API is grouped into libraries of related classes and interfaces along with their fields,
constructors, and methods. These libraries are provided in the form of packages.

Class Loader :
Java Class loader takes .class file containing bytecode and transfers it to the memory.
It loads the .class file from a disk on your system or over a network. After loading of class, it
is passed to the bytecode verifier.

Bytecode Verifier:
The bytecode verifier verifies that byte codes are valid or not without breaching any
of Java’s security rules. It gives special attention to checking the type of all the variables and
expressions in the code.
Bytecode verifier ensures that there is no unauthorized access to memory. Once the
code is successfully verified, it is transferred to Java Virtual Machine (JVM) for
interpretation.

Execution Engine
Execution engine consists of two parts: Interpreter and JIT (Just In Time) compiler.
They convert the byte code instructions into machine code so that the processor can
execute them.
In Java, JVM implementation uses both interpreter and JIT compiler simultaneously to
convert byte code into machine code. This technique is called adaptive optimizer.
Java Compiler
Java Compiler and Interpreter are the most fundamental tools in Java language that
programmers use during programming.
A compiler in Java is a computer program that is used for compiling Java programs. It
is platform-independent. It converts (translates) source code (.java file) into bytecode (.class
file).
In other words, the compiler (javac.exe) generates bytecode during the compilation
process.

Interpreter in Java :
Interpreter in Java is a computer program (software) that implements Java Virtual
Machine (JVM) and runs Java applications (programs).
It translates (converts) bytecode to machine code (native code) line by line during
runtime.

It is used for executing Java programs. Interpreter takes bytecode as an input and
executes that code by converting it to machine code. It is recognized by “Java.exe”
command.

JIT compiler in Java (JUST IN TIME compiler) :


JIT compiler in Java is the part of JVM that is used to increase the speed of execution
of a Java program.
In other words, it is used to improve the performance of the execution of the
program. It helps to reduce the amount of time needed for the execution of the program.
When .class file is loaded in the memory, JVM, first of all, tries to identify which code is to
be given to the interpreter and which one to JIT compiler so that the performance is better.
The blocks of repetitive code given to the JIT compiler are also called hotspots in Java. This
feature in Java language really improves the execution time of the program at runtime,
especially when it is to be executed multiple times.
Thus, both the Java interpreter and JIT compiler works simultaneously to translate
the byte code instruction into machine code instruction.

Object Oriented Programming Concepts:


Object-Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts are
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
o Data Binding
1. Object: A real-world entity that has state and behavior is called object in java. Here, state
represents properties and behavior represents actions and functionality. For example, a
person, chair, pen, table, keyboard, bike, etc.

Let’s take a realtime example to understand the characteristics of an object. A person has
three characteristics: Identity (name), State (properties), and behavior (actions or
functionality).
o The state/properties of a person are black hair, black eyes, white skin, 6 feet tall, etc.
The actions or behavior of the person may be “eat, sleep, walk, play, and study”.

2. Class: A class is basically user-defined data types that act as a template for creating
objects of the identical type. It represents the common properties and actions (functions) of
an object.
o For example, bus and car are objects of vehicle class. Sparrow and parrot are objects
of birds class. Similarly, MS Dhoni, Sachin Tendulkar, and Virat Kohali are objects of
cricketer class.
o Object takes space in the memory but class does not take any space in the memory.
Class does not exist physically but an object exists physically.

3. Encapsulation: The process of binding data (variables) and corresponding functions


(methods) together into a single unit (called class) is called encapsulation in Java. It is one of
the striking features to achieve data security in an object-oriented program.
o Through encapsulation, data is hidden and protected from access by outside non-
member methods of a class. Only member methods defined in a class will have
access to the data.
o A Java class is an example of encapsulation because class binds variables and
methods together.
o Generally, variables of a class are declared as “private” whereas, methods of class
are declared as “public”. This means that variables cannot be accessed from outside
the class but methods can be accessed from anywhere outside the class.
o To use variables from outside, we will have to take the help of methods. Thus,
encapsulation protects data of a class from members of another class.
o The reason is that when we create an object of class, each object shares different
memory and thus, overwriting of data is not possible.

4. Abstraction: Abstraction is a technique by which we can hide the unnecessary data that is
not needed from a user and expose only that data is of interest to the user. It hides all
unwanted data so that users can work only with the required data.
o Abstraction is one of the fundamental principles of object-oriented programming
that permits the user to use an object without knowing its internal details. It helps to
reduce complexity by not including background details.
o A realtime example of abstraction is “sending SMS”. When you need to send SMS
from your mobile, you only type the text and send the message. But you don’t know
the internal processing of the message delivery.

5. Inheritance: Inheritance is one of the main pillars of the OOP concept. It provides a
mechanism for the users to reuse the existing code within the new applications.
o It does this by allowing the programmer to build a relationship between a new class
and existing class and define a new code in terms of existing code.
o The technique of constructing a new class by using an existing class functionality is
called inheritance.
o In other words, Inheritance in Java is a process where a child class acquires all the
properties and behaviors of the parent class. The existing class is called parent class
and the new class is called child class.
o Let’s take a realtime example to understand inheritance process. In the below figure,
course is a parent class from which two child classes professional and non -
professional courses are derived.
o The courses B.Sc, B.Com, and BA are child classes that are derived from a non-
professional course class. Similarly, B.Tech, MBA, and MBBS are child classes derived
from professional course class as shown in the below figure.

6. Polymorphism: Polymorphism is another salient feature of OOP concepts in which


method can take more than one form based on the type of parameters, order of
parameters, and number of parameters.
o It is a concept by which we can perform a single task in different ways. That is, when
a single entity behaves differently in different cases, it is called polymorphism.
o Using polymorphism, we can achieve flexibility in our code because we can perform
various operations by using methods with the same names according to
requirements.
o The best real-life example of polymorphism is human behavior. One person can have
different behavior.
o For example, a person acts as an employee in the office, a customer in the shopping
mall, a passenger in bus/train, a student in school, and a son at home.

7. Dynamic Binding: Dynamic binding (also known as late binding) is a way of connecting
one program to another that is to be executed whenever it is called at runtime. It is
associated with inheritance and polymorphism.
A Simple Java Program – The Set Up
Before we learn about writing a simple java program, let us understand what
preparations are needed for running a java program from console. We have to define PATH
and CLASSPATH parameters and create necessary directories (folders) where we will be
storing all our program files.

PATH :
 PATH is an environmental variable in DOS(Disk Operating System), Windows and
other operating systems like Unix.
 PATH tells the operating system which directories(folders) to search for executable
files, in response to commands issued by a user .
 It is a convenient way of executing files without bothering about providing the
absolute path to the folder, where the file is located.

How to set PATH ?


1. Right Click My Computer
2. Select Properties
3. You will get to see the Properties Page of My Computer
4. Select Advanced Tab
5. Select Environment Variables
6. You will see Environment Variables Page as displayed here

CLASSPATH :
 CLASSPATH is a parameter which tells the JVM or the Compiler, where to locate classes that
are not part of Java Development ToolKit(JDK).
 CLASSPATH is set either on command-line or through environment variable.
 CLASSPATH set on command-line is temporary in nature, while the environment variable is
permanent.

How to set CLASSPATH ?


1. Right Click My Computer
2. Select Properties
3. You will get to see the Properties Page of My Computer
4. Select Advanced Tab
5. Select Environment Variables
6. You will see Environment Variables Page as displayed

Our first Java Program:


public class Welcome {
public static void main(String args[])
{
System.out.println(“Welcome..!”);
}
}

Create source file : Welcome.java


Compile : javac Welcome.java
Execute : java Welcome

Accessing command line arguments :

When you execute a java program, you can pass command line arguments in the following
way :
java Simple <argument1> <argument2>….<argument-n>
You can access these arguments in your program, using the String array that you have
passed as an argument to the main method – String[] args

args[0] args[1] args[n-1]


class Simple {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
When we compile the above code successfully and execute it as Java Simple IRISE, the
output will be IRISE

Accessing numeric values from command line arguments :

class Simple {
public static void main(String[] args) {
int i1 = Integer.parseInt(args[0]);
int i2 = Integer.parseInt(args[1]);
System.out.println(i1+i2);
}
}
When we compile the above code successfully and execute it as Java Simple 10 20,
the output will be 30

Finding length of an Array :

• How to find the number of command line arguments that a user may pass while
executing a java program?
• The answer to the above question lies in args.length, where args is the String array
that we pass to the main method and length is the property of the Array Object.

class FindNumberOfArguments {
public static void main(String[ ] args) {
int len = args.length;
System.out.println(“No of input passed :“ + len);
}
}
• If you compile the above code successfully and execute it as java FindLength A B C D
E F, the result will be 6
• And if you execute it as java FindLength Tom John Lee, the result will be 3

Scanner in Java
Scanner in Java is a predefined class that reads or scans the data dynamically from
the keyboard or a text file.
In other words, Scanner class allows the user to read all types of numeric values,
strings, and other types of data in java, whether it comes from a disk file, keyboard, or
another source.
We must import Scanner class into the java program before using Scanner class. The
statement to import scanner class is as follows:

import java.util.Scanner;
Or,
import java.util.*;

Example:
Let’s create a simple program where we will accept input data through the
keyboard and display them on the console.

package javaPackage;
import java.util.Scanner;

public class ScanData {


public static void main(String[] args)
{
// Create an object of Scanner class using read input.
Scanner sc = new Scanner(System.in);

// Reading values.
System.out.println("Enter an integer number: ");
int integer = sc.nextInt();
System.out.println("Enter a long integer number: ");
long longInteger = sc.nextLong();

System.out.println("Enter a floating point number: ");


float floatNumber = sc.nextFloat();
System.out.println("Enter a double data type number: ");
double doubleNumber = sc.nextDouble();

System.out.println("Enter a string: ");


String str = sc.nextLine();

System.out.println("Entered data: ");


System.out.println("Integer number: " +integer);
System.out.println("Long integer number: " +longInteger);

System.out.println("Floating point number: " +floatNumber);


System.out.println("Double data type number: " +doubleNumber);
System.out.println("String: " +str);
sc.close();
}
}
Output:
Enter an integer number: 100
Enter a long integer number: 253646747
Enter a floating point number: 200.50
Enter a double data type number: 244444444444.55555
Enter a string:

Entered data:
Integer number: 100
Long integer number: 253646747
Floating point number: 200.5
Double data type number: 2.4444444444455554E11
String:

Language Basics
• Keywords
• Data Types
• Variables
• Operators
• Conditional Statements
• Loops

Java Character sets:


Java language uses the character sets as the building block to form the basic elements such
as identifiers, variables, array, etc in the program. These are as follows:
 Letters: Both lowercase (a, b, c, d, e, etc.) and uppercase (A, B, C, D, E, etc.) letters.
 Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
 Special symbols: _, (, ), {, }, [, ], +, -, *, /, %, !, &, |, ~, ^, <, =, >, $, #, ?, Comma (,), Dot
(.), Colon (:), Semi-colon (;), Single quote (‘), Double quote (“), Back slash (\).
 White space: Space, Tab, New line.

Unicode defines a standardized 16-bit character coding system. It currently supports more
than 34,000 defined characters derived from 24 languages from America, Europe, Middle
East, Africa, and Asia (including India).

In Java, we can define Unicode characters as escape sequences by using the notation \
uXXXX, where XXXX specifies the character’s 16-bit representation in hexadecimal.

Types of Tokens :
Tokens are the various elements in the java program that are identified by Java compiler.
A token is the smallest individual element (unit) in a program that is meaningful to the
compiler.
Java language contains five types of tokens that are as follows:
 Reserved Keywords
 Identifiers
 Literals,
 Operators
 Separators

Java Keywords
Keywords in Java are predefined words that have specific meanings to the compiler and that
meanings cannot be changed. Java language has currently reserved 50 words as keywords
and these keywords are called reserved keywords.

The list of the reserved keyword is as follows:


a) Data Type: Java language has reserved eight words as keywords for data types that are as
follows:
 byte
 short
 int
 long
 float
 double
 char
 boolean
b) Access Modifiers: There are three reserved words as keywords for access modifiers by
Java language. They are as follows:
 private
 protected
 public
c) Control Statement: There are ten reserved words as keywords for the control statement
by Java language. They are as:
 else
 switch
 case
 default
 for
 while
 do
 continue
 break
 goto [reserved but not in used]
 if
d) Object and Classes: There are seven reserved keywords for classes and objects by Java
language. They are as follows:
 class
 interface
 extends
 implements
 this
 super
 new
e) Modifiers: There are eight modifier keywords reserved in the Java language. These
keywords are also called non-access modifier keywords. They are as follows:
 static
 abstract
 synchronized
 volatile
 native
 transient
 strictfp
 final
f) Exceptions: There are five exception keywords that are reserved by Java language. They
are as:
 try
 catch
 finally
 throw
 throws
g) Package: Java language has included two reserved keywords for a package that is as
follows:
 package
 import
h) Miscellaneous keywords:
 return
 const (*)
 instanceof
 void
 assert
 default
 enum
The keywords const and goto are reserved but not used. In addition to these keywords, Java
reserves the following: null, true, and false.

Identifiers in Java:
Identifiers in Java are names that identify elements such as classes, variables, and methods
in a program.
Java identifiers obey the following rules that are as follows:
1. Java identifier is a sequence of characters that consists of letters, digits,
underscores (_), and dollar signs ($).
2. It must start with a letter, an underscore (_), or a dollar sign ($). It cannot begin
with a digit.
3. It cannot be a reserved word.
4. It cannot be true, false, or null.
5. It can be of any length.

Naming conventions that are followed by Java programmers are:


1. The names of all public instance variables and methods begin with a leading
lowercase (small) letter. For example, average, sum, etc.
2. If more than one word is used in a name, the second and subsequent words must
start with a leading uppercase letter. For example, dayTemperature, totalMarks,
schoolId, etc.
3. All private and local variables start with only lowercase letters combined with
underscores. For example, length, student_id, etc.
4. All classes and interfaces must begin with a leading uppercase letter and each
subsequent word with a leading uppercase letter. For example, Student, HelloJava,
Vehicle, etc.
5. Variables that are initialized with constant values, must start with a leading
uppercase letter and can place underscores between words. For example, TOTAL,
PRINCIPAL_AMOUNT, etc.
Note that all the above points are conventions, not rules.

Comments in Java:
Java comments are not executed by the compiler and interpreter. They can be used to
provide information about variables, methods, classes, or any statement.
There are three types of comments in Java that are as follows:
 Single line comment
 Multi line comment
 Java documentation comment

Single line comment:


It is used for making a single line as a comment. Single line comment is also called
inline comment that provides brief summary comments for a single line.
It begins with a double slash symbol / / and after this, whatever is written till the end of the
line is considered as a comment.
Example :
//Variable declaration for business logic
int s = a+ b + c; // Adding three numbers and store it into a variable s of type int.
Multi line comments:
These comments are used for commenting several lines as comments. Multi line comments
begins with / * and end with * /. In between / * and * /, whatever will be written, will be
treated as a comment by Java and everything will ignore by java compiler until it finds a */.
Example:
/*
This
is
multi line
comments
*/
Java documentation comments:
These comments begins with / * * and end with * /. Java documentation comments are
used to provide explanations for every feature in a Java program.
Example:
/**
This is
documentation
comment
*/

Java Data Types


Java language provides several data types, as shown in the below figure. It divided all data
types into two categorized that are as:
1. Primitive data types (also called intrinsic or built-in types)
2. Non-primitive data types (also called derived or reference data type)

Summary of Data types:

Non-primitive data types :


Non-primitive data types are created by programmers. They are not predefined in java like
primitive data types. These data types are used to store a group of values or several values.
A non-primitive data type variable is also called referenced data type in Java or simply
object reference variable.

There are five types of non-primitive data types in Java. They are as follows:
1. Array
2. String
3. Class
4. Object
5. Interface

Difference between Primitive and Non-primitive Data types in Java

1. Primitive data types are predefined in Java whereas non-primitive data types are created
by programmers. They are not predefined in Java.
2. In primitive data type, variables can store only one value at a time whereas, in non-
primitive data type, we can store multiple values either the same type or different type or
both.
3. All the data for primitive type variables are stored on the stack whereas, for reference
types, the stack holds a pointer to the object on the heap.

Variables in Java
A variable is the name of the memory location reserved for storing value.
Each variable in Java has a specific type that determines the size of the memory. The size of
the memory reserved depends on the data type.

Example :
int x, y, z; // Here, we declare three variables x, y, and z having data type int.
int x = 10, y = 20; // Example of Initialization.
byte a = 30; // Initializes a byte type variable a.
double pi = 3.14; // declares and assigns a value of pi.

There are three types of variables in java. They are as:


1. Local variables
2. Instance variables
3. Class/Static variables

Local Variables in Java

1. A variable that is declared and used inside the body of methods, constructors, or
blocks is called local variable in java. It is called so because local variables are not
available for use from outside.
2. We must assign a local variable with a value at the time of creating. If you use a
local variable without initializing a value, you will get a compile-time error like
“variable x not have been initialized”.
3. We can not use access modifiers with local variables.
4. The local variables are visible only within the declared constructors, methods, or
blocks.
5. A local variable is not equivalent to an instance variable.
6. A local variable cannot be static.

Example 1:
public void mySchool()
{
// Declaration of local variables.
String schoolName; // Compilation error due to not initializing of value.
System.out.println("Name of School: " +schoolName);
}

Example 2 :
package localVariables;
public class Student
{
// Declaration of constructor.
Student()
{
String nCollege = "MVJ"; // Declaration and initialization of local variable.
System.out.println("Name of college: " +nCollege); // We can access local variable inside
the constructor.
}
// Declaration of instance method.
void subMarks()
{
// Declaration and initialization of local variables.
int cMarks = 90;
int pMarks = 85;
int mMarks = 99;
int totalMarks = cMarks + pMarks + mMarks;
System.out.println("Total marks in PCM: " +totalMarks);
}
public static void main(String[] args)
{
// Create an object of class.
Student s = new Student();
// This statement will produce compile-time error because local variable cannot be accessed
from the outside.
// System.out.println("Name of college: " +nCollege);
s.subMarks(); // Calling instance method.
// System.out.println("Total marks in PCM: " + totalMarks); // Compile-time error.
}
}
Instance Variables in Java
1. A variable that is declared inside the class but outside the body of the methods,
constructors, or any blocks is called instance variable in java.
They are available for the entire class methods, constructors, and blocks. It is also
called non-static variable because it is not declared as static.
2. Instance variables are created when an object is created using the keyword ‘new’
and destroyed when the object is destroyed.
3. We can also use access modifiers with instance variables. If we do not specify any
modifiers, the default access modifiers will be used which can be accessed in the
same package only.
4. It is not necessary to initialize the instance variable.

Example :

package instanceVariables;
public class Marks
{
// Declare the instance variable inside the class.
int phyMarks = 80;
public static void main(String[] args)
{
// Create the two objects of the class 'Marks'.
Marks m1 = new Marks();
Marks m2 = new Marks();

// Call the variables using object m1 and m2.


int pMarks1 = m1.phyMarks;
int pMarks2 = m2.phyMarks;
System.out.println("Marks in Physics: " +pMarks1);
System.out.println("Marks in Physics: " +pMarks2);

/* If we change the value of instance variable using object reference m2,


the value of object m1 variable will not change.
Only the value of instance variable calling by using object m2 will change.
This shows that they have their own copy of instance variable.*/

m2.phyMarks=90;
System.out.println("After changing the value of instance variable using
object m2 ");
System.out.println("Marks in Physics: " +m1.phyMarks);
System.out.println("Marks in Physics: " +m2.phyMarks);
}
}

Static Variables in Java


1. A variable which is declared with a static keyword is called static variable in java. A static
variable is also called class variable because it is associated with the class.
2. Static variables are always declared inside the class but outside of any methods,
constructors, or blocks.

Example :
package staticVariables;
public class Test
{
// Declaration of static variables.
static int a = 400;
static int b = 500;
// Static method or main method.
public static void main(String[] args)
{
// Static area. So, we can call static variables or static methods by using the class name.
System.out.println(Test.a); // Test is the name of class.
System.out.println(Test.b);
Test t = new Test(); // Creating the object of class Test.
t.m1;
}
// Instance method.
void m1()
{
// Instance area.
System.out.println(Test.a);
System.out.println(Test.b);
}
}
Example 2:

package staticVariables;
class College
{
// Static variable.
static String collegeName = "MVJ";
// static method.
public static void main(String[] args)
{
System.out.println(College.collegeName);
// Suppose anyone changes the value of a static variable using the class
name.
// In this case it will display changed value.
College.collegeName = "IRISE";
System.out.println(College.collegeName);
}
}
Operators:
• Java provides a set of operators to manipulate operations.

• Types of operators in java are,

– Arithmetic Operators

– Unary Operator

– Relational Operators

– Logical Operators

– Simple Assignment Operator

– Bitwise Operators

See the PPT for more details

Control Statements

• Control statements are statements which alter the normal execution flow of a
program

• There are three types of Control Statements in java

Selection Iteration Jumping


statement Statement Statement
If while break
if – else for continue
switch do – while return
See the PPT for more details

Arrays in Java
The main features (or properties) of arrays in java are as follows:
1. An array in Java is a sequence of variables with a similar data type. The
variables are called elements or components of the array that contain values of
the same type.
2. The elements of an array can be either primitive data types or reference types
(including itself array type).
3. Elements in Java array are always numbered from 0 to (n – 1) where n is the
individual elements in the array.
4. The position of an element in an array is called index of element or subscript.
The main intention of starting at 0 position is to make Java arrays follow the same
convention as that of C and C++.
The index of the first element in every array is always zero and is sometimes
called zeroth element.
5. The elements in the array are ordered or arranged in contiguous memory
locations.
6. Arrays are objects in Java. Therefore, they can hold reference variables of other
objects.
7. Arrays are created dynamically during runtime in Java.
8. They are dynamic, created on the heap memory.
9. The length of an array is its number of elements. It is set when the array is
created and it cannot be changed. That is, the length of an array is fixed once the
size of an array is created. Therefore, an array is not resizable.
10. Arrays may be assigned to variables of the Object type.
11. Any method of Object class can be called on the array.
12. Array objects implement Cloneable and Serializable interfaces.
13. An exception named ArrayIndexOutOfBoundsException will be thrown when
property 3 is violated.
14. Arrays in Java can be duplicated with Object.clone() method.
15. They can be verified for equality with Arrays.equals() method.

The general syntax for the creation of array object is as follows:

arrayname = new datatype[arraySize];

datatype[ ] arrayname = new datatype[arraySize];

Or,
datatype arrayname[ ] = new datatype[arraySize];
Example :
num = new int[5]; // It can store five elements of integer type in an array.
double[ ] myList = new double[10]; // It can store 10 elements of double type.
int length = 10;
int[ ] arr1 = new int[length]; // arr1 has 10 elements.
int[ ] arr2 = new int[length * 2] // arr2 has 20 elements.
int sId[ ] = new int[5]; // Create an array object.
Object obj = sId[ ]; // valid assignment.
See the PPT for more details

-----------------------------------------------------END of Unit-I ---------------------------------------------------

You might also like