Class – XII
Subject: Information Technology(802)
Teacher’s name: Satinder Kaur
Vocational Skills
Unit – 3
Fundamentals of JAVA Programming
ARRAYS
• An array is a collection of similar types of data. It is a
container that holds data (values) of one single type. Arrays
are used to store multiple values in a single variable, instead
of declaring separate variables for each value. For example,
you can create an array that can hold 100 values of int type.
• To declare an array, define the variable type with square
brackets [ ].
How to declare an array?
dataType[] arrayName;
• dataType - it can be primitive data type like int, char, double, byte, etc. or java objects
• arrayName - it is an identifier.
Let's take an example,
int[] age;
Here, age is an array that can hold values of type int. Now we have to allocate memory
for the array. The memory will define the number of elements that the array can hold.
age = new int[9];
Here, the size of the array is 9. This means it can hold 9 elements ( 9 double types
values). The size of an array is also known as the length of an array.
• Note: Once the length of the array is defined, it cannot be changed in the program.
Java Array Index
• In Java, each element in an array are associated with a number. The number
is known as an array index. We can access elements of an array by using
those indices. For example,
int[] age = new int[5];
Here, we have an array of length 5. In the image, we can see that each element consists
of a number (array index). The array indices always start from 0.
Now, we can use the index number to access elements of the array. For example, to
access the first element of the array is we can use age[0], and the second element is
accessed using age[1] and so on.
• Note: If the length of an array is n, the first element of the array will be
arrayName[0] and the last element will be arrayName[n-1].
• If we did not store any value to an array, the array will store some
default value (0 for int type and false for boolean type) by itself. For
example,
In this example, we have created an array named age.
However, we did not assign any values to the array. Hence
when we access the individual elements of the array, the
default values are printed to the screen.
How to initialize arrays in
Java?
In Java, we can initialize arrays during declaration or you can initialize
later in the program as per your requirement.
• Initialize an Array During Declaration
Here's how you can initialize an array during declaration.
int[] age = {12, 4, 5, 2, 5};
This statement creates an array named age and initializes it with the
value provided in the curly brackets.
The length of the array is determined by the number of values
provided inside the curly braces separated by commas. In our example,
the length of age is 5.
Loop Through an Array with
For-Each
There is also a "for-each" loop, which is used exclusively to loop through
elements in arrays:
• Syntax---- for (datatype variable name : arrayname)
{ ........... }
The following example outputs all elements in the cars array, using a "for-each"
loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)
{ System.out.println(i); }
The example above can be read like this: for each String element (called i - as in
index) in cars, print out the value of i.
If you compare the for loop and for-each loop, you will see that the for-each
method is easier to write, it does not require a counter (using the length
property), and it is more readable.
The program below computes sum and
average of values stored in an array of
type int.
• In the previous example, we have created an array of named numbers. We
have used the for...each loop to access each element of the array. To learn
more about for...each loop, visit Java for…. Each loop.
• Inside the loop, we are calculating the sum of each element. Notice the
line,
int arrayLength = number.length;
• Here, we are using the length attribute of the array to calculate the size of
the array. We then calculate the average using:
average = ((double)sum / (double)arrayLength);
• As you can see, we are converting the int value into double. This is called
type casting in Java.
Advantages of an Array
• Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
• Random access: We can get any data located at an index position.
Disadvantages of an Array
• Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Features of an Array
1. Dynamic allocation: In arrays, the memory is created dynamically,
which reduces the amount of storage required for the code.
2. Elements stored under a single name: All the elements are stored
under one name. This name is used any time we use an array.
3. Occupies contiguous location: The elements in the arrays are stored at
adjacent positions. This makes it easy for the user to find the locations of
its elements.
Java Program to sort the elements
of an array in ascending order
• In this program, we need to sort the given array in ascending order
such that elements will be arranged from smallest to largest. This can
be achieved through two loops. The outer loop will select an
element, and inner loop allows us to compare selected element with
rest of the elements.
//Initialize array
int [] arr = {5, 2, 8, 7, 1};
int temp = 0; Elements will be sorted in such a
//Displaying elements of original array
System.out.println("Elements of original array: "); way that the smallest element will
for (int i = 0; i < arr.length; i++)
{
appear on extreme left which in
System.out.print(arr[i] + " "); this case is 1. The largest element
}
//Sort the array in ascending order will appear on extreme right which
for (int i = 0; i < arr.length; i++)
{ in this case is 8.
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
OUTPUT:-
Elements of original array:
52871
Elements of array sorted in ascending
order:
12578
Java User Input
The Scanner class is used to get user input, and it is found in the java.util
package.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our
Methodwhich is used to read
example, we will use the nextInt() method, Description
Number:
nextBoolean() Reads a booleanvalue from the
user
nextByte() Reads a bytevalue from the
user
• Input Types nextDouble() Reads a doublevalue from the
user
To read other types, nextFloat() Reads a floatvalue from the
look at the table user
nextInt() Reads a intvalue from the user
nextLine() Reads a Stringvalue from the
user
nextLong() Reads a longvalue from the
user
nextShort() Reads a shortvalue from the
user
package myproject;
import java.util.Scanner;
public class Myproject
{
public static void main(String[] args)
{
Scanner abc = new Scanner(System.in);
System.out.println("Enter the number");
int num = abc.nextInt();
if(num <100 && num>=1)
{
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100)
{ System.out.println("Its a three digit number"); }
else if(num <10000 && num>=1000)
{ System.out.println("Its a four digit number"); }
else if(num <100000 && num>=10000)
{ System.out.println("Its a five digit number");
}
else
{ System.out.println("number is not between 1 & 99999");
}
}
}
Array Manipulation
• Sort Method
The sort method provided by ‘java.util.Arrays’ class is a very simple and
faster way to sort an array. This method can sort elements of primitive
types as well as objects that implement the comparable interface.
When primitive type elements are being sorted, the sort method uses
quick sort. When objects are being sorted, iterative merge sort is used.
Binary Search
• The binarySearch() method of the Arrays class helps us search for a
specific element in the array. The parameters it needs are the array
to be searched and the key element to be searched. The method
returns the index of the array where the key is present. If the key is
not found in the array, the binarySearch method returns -1.
double[] marks = {103, 144, 256.5, 346, 387.5}; int key = 346;
int index = Arrays.binarySearch(marks,key);
• Note that the array must be sorted before invoking binarySearch(). If
it is not sorted, the results are undefined
String Manipulation
• A string in literal terms is a series of characters. Strings, which are
widely used in Java programming, are a sequence of characters. In
Java programming language, strings are treated as objects.
• The Java platform provides the String class to create and manipulate
strings.
• Methods used to obtain information about an object are known as
accessor methods. One accessor method that you can use with
strings is the length() method, which returns the number of
characters contained in the string object. We can understand the
concept with the help of following program.
.toUpperCase
Exception Handling
• What is an Exception?
• An exception is an unwanted or unexpected event, which occurs during
the execution of a program i.e at run time, that disrupts the normal
flow of the program’s instructions.
• Error vs Exception
• Error: An Error indicates serious problem that a reasonable application
should not try to catch.
• Exception: Exception indicates conditions that a reasonable application
might try to catch.
Exception Handling
• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
Java Exception Keywords
• Java provides few keywords that are used to handle the exception.
• TRY
• CATCH
• FINALLY
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the necessary code of the program. It
is executed whether an exception is handled or not.
User Defined Methods
• What is a method?
• In mathematics, we might have studied about functions. For
example, f(x) = x2 is a function that returns a squared value of x.
If x = 2, then f(2) = 4
If x = 3, f(3) = 9
and so on.
Similarly, in computer programming, a function is a block of code that
performs a specific task.
A method is a block of code which only runs when it is called. You can
pass data, known as parameters, into a method. Methods are used to
perform certain actions, and they are also known as functions. The
most important method in Java is the main() method
Types of Java methods
• There are two types of methods in Java:
Standard Library Methods
User-defined Methods
• Standard Library Methods
The standard library methods are built-in methods in Java that are
readily available for use. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc. When we call any of the predefined
methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in
the library.
User-defined Methods
• We can also create methods of our own choice to perform some task.
Such methods are called user-defined methods.
• Method Declaration/Method Creation
• The method declaration provides information about method
attributes, such as visibility, return type, name, and arguments. The
method components are known as Method header, as we have shown
in the following figure.
• Method Signature: Every method has a method signature. It is a part of the
method declaration. It includes the method name and parameter list.
• Access Specifier/Modifiers: Access specifier or modifier is the access type of
the method. It specifies the visibility of the method.
• Return Type: Return type is a data type that the method returns. It may have
a primitive data type, object, collection, void, etc. If the method does not
return anything, we use void keyword.
• Method Name: It is a unique name that is used to define the name of a
method. It must be corresponding to the functionality of the method.
Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
• Parameter List: It is the list of parameters separated by a comma and
enclosed in the pair of parentheses. It contains the data type and variable
name. If the method has no parameter, left the parentheses blank.
• Method Body: It is a part of the method declaration. It contains all the
actions to be performed. It is enclosed within the pair of curly braces.
• Parameter A parameter is a value that is passed to a method. The values
passed to the method during its call from the caller are called arguments....
There are two types of parameters- actual parameters and formal parameters.
The parameters that appear in function call statement are called actual
parameters. The parameters that appear in method definition are called formal
parameters.
• We can also declare method as per following: Naming a Method
While defining a method, remember that the
method name must be a verb and start with a
lowercase letter. If the method name has
more than two words, the first name must be
a verb followed by adjective or noun. In the
multi-word method name, the first letter of
each word must be in uppercase except the
first word.
For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(),
stringComparision()
How to Create a User-defined Method
• Let's create a user defined method that checks the number is even or odd.
First, we will define the method.
//user defined method
public static void findEvenOdd(int num)
{
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
• We have defined the above method named findEvenOdd(). It has a
parameter num of type int. The method does not return any value that's
why we have used void. The method body contains the steps to check the
number is even or odd. If the number is even, it prints the number is even,
else prints the number is odd.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
In the above code snippet, as soon as the compiler reaches at line
findEvenOdd(num), the control transfer to the method and gives the output
accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else Output :
System.out.println(num+" is odd");
} Enter the number: 12
}
12 is even
How to Call or Invoke a
User-defined Method
• Once we have defined a method, it should be called. The calling of a
method in a program is simple. When we call or invoke a user-
defined method, the program control transfer to the called method.
There are two ways for passing argument to the method-
• Call by value: - In call by value, in place of passing a reference, a copy
of the actual argument is passed to the method.
• Call by reference: - In call by reference, in place of passing a value, a
reference to the original variable is passed to the method.
Call By Value
• package myproject;
• public class areaofc
• {
• public static void main(String[] args)
• {
• int num=2;
• circle(num);
• }
• public static void circle(double r)
• {
• double area=3.14*r*r;
• System.out.println("The Area of circle is = "+area);
• }
• }
Call by Reference
• //call by reference
• package myproject;
• public class evenodd
• {
• public static void swap(int[] a)
• {
• int t=a[0];
• a[0]=a[1];
• a[1]=t;
• }
•
• public static void main(String[] args)
• {
• int[] a={12,55};
• swap(a);
• for(int i:a)
• System.out.print(i+" ");
• }
• }
Object Oriented Programming (OOP) language
• Java is an Object Oriented Programming (OOP) language. In an OOP language, a program is collection of objects
that interact with other objects to solve a problem. Each object is an instance of a class.
• Imagine you are creating a database application for a bookstore. You will need to store data about all the books
in the store. So, each book will become an object in your program. Further, each book will have certain
characteristics or attributes such as its Title, Author, Publisher, and Price. You may also want to perform certain
actions on a book such as display its details on the computer screen or find its price. In an OOP language, such
as Java, an entity such as a book in the example is referred to as a class.
• A class is a physical or logical entity that has certain attributes. The title, author, publisher, genre and price are
the data members of the class Book. Displaying book details and getting its price are method members of the
class Book. Method members can get, set or update the class data members.
• Class Book
Data Members:
Title
Author
Publisher
Genre
Price
Method Members:
display()
getPrice()
To describe one particular book in the library, you would create an object of the class book and fill in all its data members.
For example one book in the library would be an object populated with the following data members:
Book: book1
Title: Game of Thrones
Author: George R Martin
Publisher: Harper Collins
Genre: Fiction
Price: 450
Another book would be another object populated with the following data members:
Book: book2
Title: Fundamentals of Database Systems
Author: Shamkant Navathe
Publisher: Pearson
Genre: Educational
Price: 400
You can think of a class as a template from which objects are created. All objects of the same class have the same type of data members.
Method members of a class are invoked on an object to perform the action associated with that method. For example, to display the
details of book1 you would call the method member display() of the class with book1 as the invoking object. To display the details of
book2 you would call the same method member display() but with the invoking object as book2.
Class Design
Java is an object-oriented programming language. Everything in Java is
associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and
color, and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.
A class is a user defined blueprint or prototype from which objects are created.
It represents the set of properties or methods that are common to all objects of
one type. In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access.
2. Class name: The name should begin with a initial letter.
3. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
5. Body: The class body surrounded by braces, { }.
• Freely speaking, a Java program is a set of packages, where each
package is a set of classes. A class can contain any number of fields and
methods - they are called members of a class. The implementation
design might suggest using private and public members.
Constructors
Constructors are used to initialize the object’s state. Like methods, a constructor also contains
collection of statements (i.e. instructions) that are executed at time of Object creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length,
breadth, and height). But when it comes to creating its object(i.e Box will now exist in computer’s
memory), then can a box be there with no value defined for its dimensions. The answer is no. So
constructors are used to assign values to the class variables at the time of object creation, either
explicitly done by the programmer or by Java itself (default constructor).
Rules for creating Java constructor
1) Constructor is a block of codes similar to the method having same name as that of class Name.
2) Constructor does not have any return type.
3) Constructor may or may not have a parameter list.
4) The only modifiers applicable for constructor are public, protected, default and private.
5) Constructor executes automatically when we create an object.
6) Constructor is used to initialize an object.
Types of Java constructors
There are two types of constructors in Java:
1. No-argument constructor (Default constructor)
2. Parameterized constructor
1. No argument Constructors
A constructor that has no parameter is known as default constructor. As the
name specifies the no argument constructors of Java does not accept any
parameters instead, using these constructors the instance variables of a
method will be initialized with fixed values for all objects.
Public class MyClass
Example {
Int num;
MyClass()
{
num = 100;
}
}
You would call constructor to initialize objects as follows
public class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}
This would produce the following result
100 100
Parameterized Constructors
• Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to
a method, just declare them inside the parentheses after the constructor's
name.Example
class MyClass
{
int x;
// Following is the constructor
MyClass(int i )
{
x = i;
}
}
You would call constructor to initialize objects as follows −
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x); This would produce the following
} result −
}
10 20
The following Java program has a class named
student which initializes its instance variables
name and age using both default and
parameterized constructors.
import java.util.Scanner;
class Student {
private String name;
private int age;
Student(){
this.name = "Rama";
this.age = 29;
}
Student(String name, int age){
this.name = name;
this.age = age;
}
public void display() {
System.out.println("name: "+this.name);
System.out.println("age: "+this.age);
}
}
public class AccessData{
public static void main(String args[]) {
//Reading values from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
Student obj1 = new Student(name, age);
obj1.display();
Student obj2 = new Student();
obj2.display();
}}
Assertion:
• An assertion is a useful mechanism for effectively identifying/detecting and
correcting logical errors in a program. When developing your Java programs,
it is good programming practice to use assert statements to debug your code.
An assert statement states a condition that should be true at a particular
point during the execution of the program.
There are two ways to write an assertion
• assert expression;
• assert expression1 : expression2
The first statement evaluates expression and throws an AssertionError if expression
is false. The second statement evaluates expression1 and throws an AssertionError
with expression2 as the error message if expression1is false.
Note that, since assertions reduce runtime performance, they are
disabled by default.
To enable assertions at runtime, you can enable them from the
command line by using
the –ea option.
java –eaAssertionDemo
• Alternatively, to enable assertions in NetBeans, Right click on your
project>Properties>Run>VMOptions. Type–ea in the text box next
to VM Options and click OK.
The program fragment below
demonstrates usage of the
assert statement.
assert age >= 18:"Age not
Valid";
When this statement is
executed, we assert that the
value of the variable age
should be
>= 18. If it is not, an
AssertionError is thrown and
the error message “Age not
Valid” is returned.
Thread
A multithreaded program is one that can perform multiple tasks concurrently
so that there is optimal utilization of the computer's resources. A
multithreaded program consists of two or more parts called threads each of
which can execute a different task independently at the same time.
In Java, threads can be created in two ways
1. By extending the Thread class
2. By implementing the Runnable interface
Java Program to create a
thread by extending
thread class
Java Program to create a
thread by implementing the
Runnable Interface.
Wrapper Classes
• By default, the primitive datatypes (such as int, float, and so on) of Java are
passed by value and not by reference. Sometimes, you may need to pass the
primitive datatypes by reference. That is when you can use wrapper classes
provided by Java. These classes wrap the primitive datatype into an object of
that class. For example, the Integer wrapper class holds an int variable.
• 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 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.
Getter Setter Method
• Getter Setter Method is used to set and get the value of class variable.
• Private data members of a class cannot be accessed outside the class. However,
we can give controlled access to data members outside the class through getter
setter method.
• Getter method returns the value
double getprice()
{
return price;
}
• Setter method is used to set the value.
void setprice(double newprice){
if(newprice<100)
System.out.println(“Price cannot be set lower than 100”);
else
price=newprice;
}