0% found this document useful (0 votes)
16 views

java notes1

Java notes

Uploaded by

rohithrajesh006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

java notes1

Java notes

Uploaded by

rohithrajesh006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Module-I

Object Oriented Programming


Introduction
It is an approach 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. Thus the object is considered to be a partitioned area of computer memory that stores data
and set of operations that can access that data.
 OOP treat data as a critical element in the program development and does not allow it to flow freely
around the system.
 It ties data more closely to the functions that operate on it, and protects it from accidental modification
from outside functions.
 OOP allows decomposition of a problem into a number of entities called objects and then build data
functions around these objects.
 The data of an object can be accessed only by the functions associated with that object.
 Functions of one object can access the functions of another objects
Characteristics of Procedure-Oriented Programming
 Emphasis is on doing things.
 Large programs are divided into smaller programs known as functions.
 Most of the functions share global data.
 Data move openly around the system from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.
Characteristics of Object-Oriented Programming
 Emphasis is on data rather than procedure.
 Programs are divided into objects.
 Data structures are designed such that they characterize the objects.
 Functions 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 functions.
 New data and functions can be added easily whenever necessary.
 Follows bottom-up approach in program design
Basic Concepts of Object-Oriented Programming
 Objects
 Classes
 Data Abstraction and Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing
Objects
Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a
bank account, etc. Objects take up space in the memory and have an associated address like a structure in C.
When a program is executed, the objects interact by sending messages to one another.
Classes
Classes are user-defined data types.
The entire set of data and code of an object can be made a user-defined data type with the help of a class.
Objects are variables of the type class. Once a class has been defined, we can create any number of objects
belonging to that class. Each object is associated with the data of type class with which they are created.
A class is a collection of objects of similar type.
Data Abstraction and Encapsulation
o The wrapping up of data and functions into a single unit is known as encapsulation.
o The data is not accessible to the outside world, and only those functions which are wrapped in
the class can access it.
o These functions provide the interface between the object’s data and the program. This
insulation of the data from direct access by the program is called data hiding or information
hiding.
o The attributes wrapped in the classes are called data members and the functions that operate on
these data are called methods or member functions.
o Since the classes use the concept of data abstraction, they are known as Abstracted Data Types
(ADT).
Inheritance
o Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
o It supports the concept of hierarchical classification.
o Each derived class shares common characteristics with the class from which it is derived.
o Inheritance provides the idea of reusability.
o We can add additional features to an existing class without modifying it.
(By deriving new class from existing one.
The new class will have the combined features of both the classes.)
Polymorphism - ability to take more than one form
o An operation may exhibit different behaviors in different instances.
o The behavior depends upon the types of data used in the operation.
o add( 3, 5) gives 8
o Add(“hello”, “-world”) gives “hello-world”
o The process of making an operator to exhibit different behaviors in different instances is known
as operator overloading.
o << Insertion Operator
o << Left-shift bit-wise operator
o Using a single function name to perform different types of tasks is known as function
overloading.
o add( 3, 5) gives 8
o Add(“hello”, “-world”) gives “hello-world”
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
Dynamic binding (late binding) means that the code associated with a given procedure call is
not known until the time of the call at run-time.
It is associated with polymorphism and inheritance.
Message Passing
o An oop consists of a set of objects that communicate with each other.
o Oop involves the following steps:
o Creating classes that define objects and their behavior.
o Creating objects from class definitions.
o Establishing communication among objects.
o Objects communicate with one another by sending and receiving information.
o A message for an object is a request for execution of a procedure.
o The receiving object will invoke a function and generates results.
o Message passing involves specifying:
o The name of the Object.
o The name of the Function.
o The information to be send.
Benefits of OOP
 Inheritance – eliminate redundant code and extend the use of existing classes.
 We can build programs from the standard working module, no need of starting from the scratch.
 Data hiding helps the programmer to build secure programs that cannot be invaded by code in other
parts of the program.
 Multiple instances of an objects can co-exists without any interference.
 It is easy to partition the work in a project based on objects.
 Object-oriented system can be easily upgraded from small to large systems.
 Message passing techniques for communication between objects makes the interface descriptions with
external systems much simpler.
 Software complexity can be easily managed.
Introduction to Java
 JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later acquired by
Oracle Corporation.
 It is a simple programming language. Java makes writing, compiling, and debugging programming
easy. It helps to create reusable code and modular programs.
 Java is a class-based, object-oriented programming language.
 A general-purpose programming language made for developers to write once run anywhere that is,
compiled Java code can run on all platforms that support Java.
 Java applications are compiled to byte code that can run on any Java Virtual Machine.
 The syntax of Java is similar to c/c++.
Important features of Java
The following are some important features of Java Programming Language:
Simple Distributed
Platform Independent Multi-Threading
Architectural Neutral Networked
Dynamic and Extensible Secured
Portable High Performance
Robust Object Oriented
Simple
 The Java language is easy to learn and its coding style is easy to read and write.
 It contains many features of other Languages like C and C++.
 Java removes complexity because it doesn't use pointers and doesn't support Multiple Inheritance.
Platform Independent
 This is where the "Write Once, run anywhere" motto for Java comes in.
 It means that you can develop on one environment (Operating System) and run on another
environment without doing any modification of the code.
Architectural Neutral
 Java application runs the same byte codes regardless of any environment (Operating System).
 To enable a Java application to execute anywhere on the network, the compiler generates an
architecture-neutral object file format.
Dynamic and Extensible
 Java has Dynamic and Extensible means with the help of OOPS you can add classes and plug in new
methods to classes, creating new classes through sub classes.
 This makes Java very easy to augment with your own classes or even to modify.
Portable
 Java programs can execute in any environment (Linux, Window, Mac etc.) for which there is a Java
run-time system (JVM).
 That really means there is no implementation dependent features.
Multi-Threading
 Java supports Multithreading. Multithreading means handling more than one job at a time, so get more
process get done in less time than it could with just one thread.
Distributed
 Java was designed with the distributed environment.
 It has networking facilities, so it can be transmit, run over internet.
Networked
 Java is mainly designed for web based applications.
 Java masks lot of complexity by providing classes that already implements the hard parts, such as
creating socket connections, reading the contents of the URL as a file etc.
 Moreover, J2EE is used for developing network based applications.
Robust
 Robust simply means strong. Its capability to handle Run-time Error, automatic garbage collection, the
lack of pointer concept, Exception Handling etc. makes java robust.
Secured
 The Java platform is designed with security features built into the language and runtime system such as
Byte code verification for distrusted code, support for authentication and privacy etc.
 Java program always runs in Java runtime environment with almost null interaction with OS, hence it
is more secure.
High Performance
 Although Java is an interpreted language, it was designed to support "just-in-time" compilers, which
dynamically compile byte codes to machine code.
 Byte codes are highly optimized, so Java Virtual Machine can executed them much faster.
Object Oriented
 Java supports Inheritance, encapsulation and polymorphism, the three major Object Oriented
constructs that distinguish a language as Object-Oriented.

Java Environment
 Java Environment includes large number of development tools.
 The development tools are part of the system known as Java Development Kit ( JDK ).

1. JavaDevelopment Kit ( JDK )


The Java Development Kit ( JDK ) comes with a collection of tools that are used for developing and running
Java programs.
They includes:
 appletviewer ( for viewing java applets) :
Applets are small programs that can only run within a web browser.
 java ( java interpreter ):
A program that can analyses and executes your program line by line.
 javac ( java compiler ):
A program that can analyse and executes your whole program.
 javap ( java disassembler):
A disassembler is used to translate machine code (0 and 1) into a human readable format.
 javah :
Used for importing other programming files.
 javadoc :
Used in web based applications .
 jdb ( java debugger ):
Debugging is the process of detecting and removing of existing errors .
2. Java Runtime Environment ( JRE )
The Java Runtime Environment ( JRE ) facilitates the execution of programs developed in java. It comprises
the following:
Java Virtual Machine ( JVM ) :
Java Virtual Machine (JVM) is an engine that provides a runtime environment to drive the Java Code or
applications. It converts Java bytecode into machine language. This machine is called Java Virtual
Machine and it exists only inside the computer memory.
 Compiling source code into bytecode ( machine readable code ) using javac compiler.
 Executing the bytecode ( machine-readable code ) to human-understandable code using
a Java inter
preter


Java Data Types
Data types are the kind of data that variables hold in a programming language. A data type is an attribute of
data that tells the compiler or interpreter how the programmer plan to use the data. There are two types of data
types in Java:

 Primitive data types ( intrinsic or built-in types )


 Non-primitive data types (derived types )

‍Primitive data types ( intrinsic or built-in types )

Primitive types are predefined (already defined) in Java. A primitive type starts with a lowercase letter.
The primitive data types include char, byte, short, int, long, boolean, float, and double.

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

Stores whole numbers from -2,147,483,648 to


int 4 bytes
2,147,483,647

Stores whole numbers from -


long 8 bytes 9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

Stores fractional numbers. Sufficient for


float 4 bytes
storing 6 to 7 decimal digits

Stores fractional numbers. Sufficient for


double 8 bytes
storing 15 decimal digits

boolean 1 bit Stores true or false values


Data Type Size Description

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

‍Non-Primitive Data Types

Non-primitive types are created by the programmer. non-primitive types start with an uppercase letter. The
non-primitive data types include Classes, Interface, Strings, and Arrays.
Classes:
A class is a group of objects which have common properties. It is a user-defined data type with a template that
serves to define its properties. To create a class, use the keyword class. Let's learn the class in detail in
upcoming chapters.
public class Main { // Main is the class name int num = 20; void getdata(){ } void putdata(){ } }

Interfaces:
The interface keyword to create an interface. An interface is slightly different from the class. It contains only
constants and method declarations.
interface car // car is the interface name{ void start(); void stop(); }

Strings:
The String data type is used to store a sequence of characters (text). String values must be surrounded by
double quotes.
String greeting = "Hello World"; System.out.println(greeting);

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.
String[] cars = {"Audi", "BMW", "Ford"}; int[] num = {10, 20, 30, 40};

Java Variables

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. In Java, all the variables must be declared before use.

1. Declaring variables
 datatype: Type of data that can be stored in this variable.
 variable_name: Name given to the variable.

Syntax:

data_type variable_name;

Example:

char alphabet ; int number;

‍Where alphabet and number are then variables of type character and integer.

2. Assigning values to variables

Values can be assigned to a variable directly using assignment operator(=).


Syntax:

data_type variable_name = value;

Example:‍

char alphabet = 'A'; int number = 100;

‍Where A and 100 are the values assigned to the variable alphabet and number.

3. Rules for Naming Variables

 Variable names may consists of alphabets , digits , underscore ( _ ) and dollar sign ( $ ).
 They must not be begin with digits.
 It should not be a keyword.
 White space is not allowed.
 Variable names can't be in length.
 Uppercase and Lowercase are distinct.

Java Constants
Constants in Java refer to fixed values that do not change during the execution of the program. A
constant is a variable whose value cannot change once it has been assigned.
To define a variable as a constant, we just need to add the keyword “final” in front of the variable
declaration.
Syntax:
inal data_type = value;
Example:‍
final float pi = 3.14f;
The above statement declares the float variable “pi” as a constant with a value of 3.14f. We cannot
change the value of "pi" at any point in time in the program.
Types of Constants
1. Integer Constants :
It refers to sequence of digits . There are three types of integers namely decimal integer , octal
integer and hexadecimal integer.
final int num1 = 225; // decimal integer begins with non zero digitfinal int num2 = 035; // octal
integer begins with 0final int num3 = 0x2; // hexadecimal integer begins with "0x" or "0X"
2. Real Constants:

Integer numbers are inadequate to represent quantities that are very continuously, such as
temperatures, prices, heights ,etc. These numbers are represented by fractional parts. Such
numbers are called real constants.
Example:
final int num1 = 435.36;
real constants are represented by fractional parts.
3. Single Character Constants :
It contains a single character enclosed within a pair of single quote marks.‍
Example:
final char alphabet1 = 'A';
'A' is a single character constant enclosed with single quote.
final char num1 = '5';
'5' is single character constant enclosed with single quote.
iv) String Constants: It contains a single character enclosed within a pair of double quote marks.
Example: “hello", “2000”, “7+5”.
final String greeting = "Hello"; // "Hello" is a string constant enclosed with double quotes final String
num = "20"; // "20" is a string constant enclosed with double quotes
Java Typecasting

Convert a value from one data type to another data type is known as type casting.

In Java, there are two types of casting:


 Widening Casting (automatically) - converting a smaller type to a larger type . It is also known
as implicit conversion or casting down.

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

Example:

int x = 7;
long y = x; //automatically converts the integer type into long type

float z = y; //automatically converts the long type into float type

 Narrowing Casting (manually) - converting a larger type to a smaller type. It is also known
as explicit conversion or casting up.

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

Syntax:
type variable1 = (type) variable2;

Java Decision Making And Looping


LOOPS:

A Loop executes the sequence of statements many times until the stated condition becomes false. A loop
consists of two parts, a body of a loop and a control statement. The purpose of the loop is to repeat the same
code several times.

1. while loop :

A while loop statement in Java programming language repeatedly executes a target statement as long as a
given condition is true. When executing, if the boolean_expression result is true, then the actions inside the
loop will be executed. When the condition becomes false, the loop will exit.
Syntax:
while(Boolean_expression)
{
// Statements
}
Example:
public class Looping
{
public static void main(String args[]) {
int x = 10;
while( x < 15 ) {
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}
}
}
EXPLANATION:
The loop executes until the value of x is less than 15, the value of x is incremented by 1. When the condition is
false the loop exit */

OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */

2. do while loop :

A do-while loop is similar to a while loop with one exception that it executes the statements inside the body of
the do-while before checking the condition. If the Boolean expression is true, the statements in the loop
execute again. This process repeats until the Boolean expression is false.
Syntax:
do
{
// Statements
}while(Boolean_expression);
Example:
public class Looping
{
public static void main(String args[])
{
int x = 10;
do
{
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}while( x < 15 );
}
}
EXPLANATION:
The control passes to the body of the loop and then checks the condition.
If the condition is less than 15 loop executes, and then the value of x is incremented
by 1.When the condition false the loop terminates. */
OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */

3. for loop

A for loop ( finite 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:
for(initialization; Boolean_expression; update)
{
// Statements
}
Example:
public class Looping
{
public static void main(String args[])
{
for(int x = 10; x < 15; x = x + 1)
{
System.out.print("value x : " + x );
System.out.print("\\n");
}
}
}
EXPLANATION:
The loop executes until the value of x is less than 15,
when the condition is false the loop exit*/
OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */
Jump Statements:

Jump statements are used to unconditionally transfer program control from one point to elsewhere in the
program. Jump statements are primarily used to interrupt loops or switch-case instantly. Java supports three
jump statements: break, continue, and return.

i) break statement:

The break construct is used to break out of the middle of loops: for, do, or while loop. When a break statement
is encountered, execution of the current loops immediately stops and resumes at the first statement following
the current loop.
Example:
public class BreakStatement
{
public static void main(String args[])
{
System.out.println("Welcome to ShapeAI");
for (int i = 1; i <= 10; i++)
{
System.out.println("i = "+i);
if (i == 5)
{
System.out.println("\\nBye");
break;//hence break statement is used to terminate the loop
}
}
}
}
OUTPUT:
Welcome to ShapeAI
i=1
i=2
i=3
i=4
i=5

Bye

ii) continue Statement:

The continue statement also skips the remaining statements of the body of the loop where it is defined but
instead of terminating the loop, the control is transferred to the beginning of the loop for the next iteration.
The loop continues until the test condition of the loop becomes false.
Example:
public class ContinueStatement
{
public static void main(String args[])
{
int i;
for (i = 1; i <= 10; i++)
{
if (i == 5)
continue; // continue statement breaks the loop continues until the test condition of the loop becomes
false
System.out.print(i + " ");
}
}
}
OUTPUT:
1 2 3 4 6 7 8 9 10

iii) return Statement:


A return statement ends the execution of a function, and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return
statement can return a value to the calling function.

Example:
public class ReturnStatement
{
int display()
{
return 5;
}
public static void main(String[] args)
{
ReturnStatement e = new ReturnStatement();
System.out.println(e.display());
}
}

OUTPUT:
5
Java Decision Making And Branching
“Decision making and branching” is one of the most important concepts of computer programming. Programs
should be able to make logical (true/false) decisions based on the condition provided. So controlling the
execution of statements based on certain condition or decision is called decision making and branching.

1.If Statements

The if statement is used to test the condition. It checks boolean conditions true or false. There are various
types of if statements in Java.
 Simple if statement
 if-else statement
 if-else-if ladder
 nested if statement

i) Simple if Statement :

The Java if statement tests the condition. It executes the *if block* if the condition is true. Where
boolean_expression is a condition.
Syntax:
if(Boolean_expression)
{
// Statements will execute if the Boolean expression is true
}
Statement-X;
Example:
public class Branching
{
public static void main(String args[])
{
int num = 10;
if( num < 20 ) {
System.out.print("Welcome to ShapeAI");
}
}
}
EXPLANATION:
Hence num value 10 is less than 20, it executes the statement inside if block
OUTPUT:
Welcome to ShapeAI

ii) if-else Statement :

The Java if-else statement also tests the condition. It executes the if block, if the condition is true
otherwise else block, is executed.
Syntax:
if(Boolean_expression)
{
// Executes when the Boolean expression is true
}else
{
// Executes when the Boolean expression is false
}
Statement-X;
Example:
public class Branching
{

public static void main(String args[])


{
int num = 30;

if( num < 20 )


{
System.out.print("This is if statement");
}else
{
System.out.print("This is else statement");
}
}
}
EXPLANATION:
Executes the else statement hence the num value 30 is greater than 20
OUTPUT
This is else statement

iii) if-else-if ladder Statement :

The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
// Executes when the Boolean expression 3 is true
}
else
{
// Executes when the none of the above condition is true.
}
Statement-X;
Example:
public class Branching
{
public static void main(String args[])
{
int num = 30;
if (num == 10)
{
System.out.print("Value of num is 10");
}
else if (num == 20)
{
System.out.print("Value of num is 20");
}
else if (num == 30)
{
System.out.print("Value of num is 30");
}
else
{
System.out.print("This is else statement");
}
}
}

EXPLANATION:
executes the second else if block hence the num value 30 is equal to 30
OUTPUT
Value of X is 30
iv) nested if statement :

The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when the outer if block condition is

Syntax:

switch(expression)
{
case value :
// Statements
break;

case value :
// Statements
break;

// You can have any number of case statements.


default : // Optional
// Statements
}
Statement-X;
Example:
public class Switching
{

public static void main(String args[])


{
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Good");
break;
case 'C' :
System.out.println("Well done");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

EXPLANATION:
The given expression grade is assigned with 'C'. hence it matches with the case 'C'.
So case 'C' statement "Well done" is executed
OUTPUT:

Well done
Your grade is
Labeled Loop in Java

A label is a valid variable name that denotes the name of the loop to where the control of execution should
jump. To label a loop, place the label before the loop with a colon at the end. Therefore, a loop with the label
is called a labeled loop.
Syntax for labelled for-loop:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}
Example:
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}
Output:

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9

You might also like