Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JAVA NOTES

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Fundamentals of Java

Repetition Structures
In real life you often do something repeatedly, for example, consider a task such as reading a book,
first you open the book, and then repeatedly – read a page; flip the page – until you get to the end of
the book, then close the book.

Similarly, when writing programs, you might need to perform the same sequence of statements
repeatedly until some condition is met.
The ability of a computer to perform the same set of actions again and again is called looping.
The sequence of statements that is repeated again and again is called the body of the loop.
The test conditions that determine whether a loop is entered or exited is constructed using relational
and logical operators.
A single pass through the loop is called an iteration.
For example, a loop that repeats the execution of the body three times goes through three iterations.

Types of loops : while, do-while and for


The while statement :
while (expression)
{
Statements
}
In while statement first the condition or expression is tested. If it is true then statements written
inside the brackets gets executed repeatedly until the condition becomes false.
While loop is entry controlled loop.
Let us write a program to print the squares of numbers from 1 to 5. The following steps need to be
performed.
1. Initialize number = 1
2. Test if the number <= 5
3. If yes, print the square of the number;
Increment number (number = number + 1)
Go back to step 2
4. If no, exit the loop.
Example program :
int number = 1;
while (number <= 5)
{
System.out.println ("Square of a number = " + number*number);
++number; }
The do – while statement : The do while statement evaluates the test after executing the body of a
loop. Do – while is exit controlled loop. The structure of the Java do while statement is as shown:
do
{
statements
} while (expression);

Example program :
int number = 1;
do
{
System.out.println ("Square of a number = " + number*number);
++number;
} while (number <= 5);

Difference between Entry control loop and Exit control loop


Entry Control Loop Exit Control Loop

In entry control loop condition is checked In exit control loop condition is checked
first last

If the condition is false, loop body will not If the condition is false, loop body will
execute execute at least once

Example of entry control loop – For &


Example of exit control loop – Do-while
While

Difference between while and do-while loop :


1. A while loop is an entry controlled loop – it tests for a condition prior to running a block of code
whereas A do-while loop is an exit control loop - it tests for a condition after running a block of
code
2. A while loop runs zero or more times Body of loop may never be executed whereas A do-while
loop runs once or more times but at least once.

System.out.print is used to display the output in output window.


System.out.println is used to display each output in new line in output window.

For Statement : The for loop is the most widely used Java loop construct. The structure of the
Java for statement is as below:
for (counter=initial_value; test_condition;change counter)
{
statements
}
Semicolons separate the three parts of a for loop:
The initial_value initializes the value of the loop counter.
The test_condition tests whether the loop should be executed again. The loop is
exited when the test condition fails.
The step updates the counter in each loop iteration.
e.g. Program to print the square of numbers from 1 to 5 using For loop.
int number;
for (number = 1; number<= 5; ++number)
{
System.out.print("Square of "+ number);
System.out.println(" = "+ number*number);
}

Arrays in Java :
Arrays are variables that can hold more than one value, they can hold a list of values of the same
type.
e.g.
double [ ] marks = new double[5];
marks is a variable of type array that can store marks of five students of decimal type. Each element
of the array is indexed by its position starting from 0. So the five elements of the array can be
accessed as marks[0], marks[1], marks[2], marks[3], marks[4]

To store the specific marks we can write


double [ ] marks = { 78.5, 98.0, 86,5, 67.0, 89.5} ;

To print all the marks, we can use a for loop, varying the loop index from 0 to 4.
int i;
for (i = 0; i< 5; i++)
System.out.println(marks[i]);

This loop will display all the marks line by line.

The following code shows the use of an array to print the class report card for the five students.

double percentage = 0;
double tmarks = 100;
String result = “ “;
for (int i = 0 ; i <marks.length ; i++)
{
percentage = (marks[i]/tmarks)*100;
if (percentage >= 40)
result = "Passed";
else
result = "Failed";
}
In this program length function is used to find out the total numbers of elements in an array.
Array Variable Declaration

User Defined Methods


A method in Java is a block of statements grouped together to perform a specific task. A method has
a name, a return type, an optional list of parameters, and a body.

e.g. double rectangle_area (double length, double breadth)


{
return (length * breadth);
}
The name of the method is rectangle_area. The method has two parameters – both of type double.
The body of the method has only a single statement, one that calculates the area based on the
parameters and returns it. The return type from the method is of type double.

A method is called/invoked from another method. When a method is called, control is transferred
from the calling method to the called method. The statements inside the called method's body are
executed. Control is then returned back to the calling method.

Object Oriented Programming : Java is an Object Oriented Programming (OOP) language.


In an OOP language, a Class is collection of objects that interact with other objects to solve a
problem.
Each object is an instance of a class.

For e.g. Book can be a class and different types of books are the objects of class Book.

Class Design :
A class in Java begins with the keyword class followed by the name of the class. The body of the
class is enclosed within curly braces. The body contains the definitions of the data and method
members of the class.
The data members are defined by specifying their type. The method members have access to all the
data members of the class and can use them in their body. The data members of a class are like
global variables – they can be accessed by all the method members of the class.

e.g. public class Book {


String title;
String author;
double price;
void display( )
{
System.out.println(“Title “ + title);
System.out.println(“Author “ + author);
System.out.println(“Price “ + price);
}
}
Here class is a keyword used to create a class named as Book.
Then data members are declared.
Void display( ) is a member function in which we are displaying information.

What is Object?
An object is an entity with state and behaviour, such as a chair, bike, marker, pen, table, or car.
Object Definitions:
 An object is a real-world entity.
 An object is a runtime entity.
 The object is an entity which has state and behavior.
 The object is an instance of a class.
Constructors
A special method member called the constructor method is used to initialize the data members of
the class (or any other initialization is to be done at time of object creation).
The constructor has the same name as the class, has no return type, and may or may not have
a parameter list. Whenever a new object of a class is created, the constructor of the class is
invoked automatically. We do not call the constructor explicitly.
Access Modifiers : There are three access modifiers Public, Private and Protected.

Private : Members in a class declared as private cannot be accessed outside the class. i.e. they
cannot be accessed through the object of the class but can be accessed by member
methods of the class.
Public : Members declared as public can be accessed outside the class i.e. they can be accessed
through the object of the class using dot operator. By default all the members of the class
are public.
e.g. public class Book {
String title;
String author;
double price;
void display( )
{
System.out.println(“Title “ + title);
System.out.println(“Author “ + author);
System.out.println(“Price “ + price);
}
}
Now to create an object of class book we need to write :
Book book1 = new Book( );
Here Book is the name of the class and book1 is an object of the class Book.
new method is used to allocate memory to the object book1 and Book( ) is the constructor method
to initialize the data members for the object book1.
To access display( ) method of class Book, we need to write
book1.display( );

Getter and Setter Methods


A class’s private data members cannot be accessed from outside the class, but you can grant getter
and setter methods controlled access to data members outside the class. The value of a data member
is returned by a getter method.
For example we could define a getter method in the Book class for the price data member as given
below –
double getPrice ( ) {
return price;
}
Array Manipulation
The elements of an array can be any combination of integers, floating numbers, or complex
numbers, and they all share the same underlying data type. Array manipulation helps to manipulate
the data using predefine function, from example “binarySearch()”.
We can search for a specific element in an array using the binarySearch() function of the Arrays
class. The array to be searched and the key element to be searched are the parameters required. The
method returns the array’s index, which is the location of the key. The binarySearch method gives a
negative value if the key cannot be found in the array.
Example –
Double[ ] marks = {103, 144, 256.5, 346, 387.5};
int key = 346;
int index = Arrays.binarySearch(marks, key);
String Functions : String myString = “Hello World”;
Exception Handling

Sometimes the programs gets terminated unexpectedly with runtime errors at the time of execution.
The errors could have occurred because an array index reference was out of range, or an attempt
was made to divide an integer by zero, or there was insufficient computer memory and so on.
Such an error situation that is unexpected in the program execution and causes it to terminate
unexpectedly is called an exception.
Java provides the following keywords to handle an exception:

try – A try block surrounds the part of the code that can generate exception(s).

catch – The catch blocks follow a try block. A catch block contains the exception handler – specific
code that is executed when the exception occurs. Multiple catch blocks following a try block can
handle different types of exceptions.

Wrapper Classes
Java’s primitive datatypes, including int, float, and others, are typically supplied by value rather
than via reference. Primitive datatypes may occasionally need to be passed by reference. When that
happens, you can use the Java wrapper classes.
These classes encapsulate the primitive datatype in an object. For instance, an int variable is held by
the Integer wrapper class.

Consider the following two declarations:

int a = 50;

Integer b = new Integer(50);

In the first declaration, an int variable is declared and initialized with the value 50.

In the second declaration, an object of the class Integer is created and initialized with the

value 50.

The variable a is a memory location and the variable b is a reference to a memory location that
holds an object of the class Integer.

You might also like