You are on page 1of 35

IISem BCA OOPS USING JAVA

Unit – 1 Introduction to Java

Introduction to Java: Basics of Java programming, Data types, Variables,


Operators, Control structures including selection, Looping, Java methods,
Overloading, Math class, Arrays in java.

What is java?

java is a high-level, general-purpose, object-oriented, and secure programming


language developed by James Gosling at Sun Microsystems, Inc. in 1991. It is
formally known as OAK. In 1995, Sun Microsystem changed the name to Java.

Java runs on 3 billion devices worldwide, which makes Java one of the most popular
programming languages

The programming environment of Java consists of three components mainly

• JDK
• JRE
• JVM

What is JDK?

JDK (Java Development Kit) is a software development kit required to develop


applications in Java. When you download JDK, JRE is also downloaded with it.

In addition to JRE, JDK also contains a number of development tools (compilers,


JavaDoc, Java Debugger, etc).

What is JRE?

JRE (Java Runtime Environment) is a software package that provides Java class
libraries, Java Virtual Machine (JVM), and other components that are required to run
Java applications.

Page 1
IISem BCA OOPS USING JAVA

What is JVM?

JVM (Java Virtual Machine) is an abstract machine that enables your computer to run
a Java program.

When you run the Java program, Java compiler first compiles your Java code to
bytecode. Then, the JVM translates bytecode into native machine code

Features of Java

o Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or
re-implemented in Java. For example, pointer and operator overloading are not
used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It means it has
some data and behavior. A program must have at least one class and object.
o Robust: Java makes an effort to check error at run time and compile time. It uses
a strong memory management system called garbage collector. Exception
handling and garbage collection features make it strong.
o Secure: Java is a secure programming language because it has no explicit pointer
and programs runs in the virtual machine. Java contains a security manager that
defines the access of Java classes.
o Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any
machine.

Page 2
IISem BCA OOPS USING JAVA

o Portable: Java Byte code can be carried to any platform. No implementation-


dependent features. Everything related to storage is predefined, for example, the
size of primitive data types.
o High Performance: Java is an interpreted language. Java enables high
performance with the use of the Just-In-Time compiler.
o Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over
the internet. EJB and RMI are used to create a distributed system.
o Multi-threaded: Java also supports multi-threading. It means to handle more
than one job a time.

Java Hello World Program

class HelloWorld

// Your program begins with a call to main().

// Prints "Hello, World" to the terminal window.

public static void main(String args[])

System.out.println("Hello, World");

1. Class definition

This line uses the keyword class to declare that a new class is being defined.

class HelloWorld {

//

//Statements

Page 3
IISem BCA OOPS USING JAVA

2. HelloWorld

It is an identifier that is the name of the class. The entire class definition, including all
of its members, will be between the opening curly brace “{” and the closing curly
brace “}“.

3. main method:

In the Java programming language, every application must contain a main method.
The main function(method) is the entry point of your Java application, and it’s
mandatory in a Java program. whose signature in Java is:

public static void main(String[] args)

public: So that JVM can execute the method from anywhere.

static: The main method is to be called without an object. The modifiers public and
static can be written in either order.

void: The main method doesn’t return anything.

main(): Name configured in the JVM. The main method must be inside the class
definition. The compiler executes the codes starting always from the main function.

String[]: The main method accepts a single argument, i.e., an array of elements of
type String.

Compiling the program → Javac HelloWorld.java


Running the program → java HelloWorld

Page 4
IISem BCA OOPS USING JAVA

COMMENTS IN JAVA
In Java there are three types of comments:
Single-line comments.
//Comments here( Text in this line only is considered as comment )
Multi-line comments.
/*Comment starts
continues
continues
.
.
.
Comment ends*/

DATA TYPES

Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Page 5
IISem BCA OOPS USING JAVA

Primitive data types:

In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.There are eight primitive
data types in Java

Page 6
IISem BCA OOPS USING JAVA

Non-primitive data types :

The term non-primitive data type means that these types contain “a memory address of
the variable”.

In contrast to primitive data types, which are defined by Java, non-primitive data types
are not defined or created by Java but they are created by the programmers.

They are also called Reference data types because they cannot store the value of a
variable directly in memory.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

VARIABLES

A variable in Java is a container that holds the value during the execution of Java
program. In other words, 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.

Variable Declaration in Java

Page 7
IISem BCA OOPS USING JAVA

Naming Convention for the declaring variables in Java

1. As per Java coding standard, the variable name should start with a lower case
letter.
If you have lengthy variables such as more than one words then you can declare
the first word small and second word with the capital letter

2 The variable name should not contain a blank space.


3 The variable name can begin with a special character such as $ and _. .
4 We should not use java keywords as a variable name.
5 The variable names are case sensitive in Java.

• int age;//valid
• int smallNumber; // valid.
• String collegeName; // valid.
• int num ber = 100; is invalid because there is a blank space between num and
ber.
• String $name; // valid.
• String _nSchool; // valid.
• int @num; // invalid.

Page 8
IISem BCA OOPS USING JAVA

Types of Variables in Java

1) Local Variable

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”.

public void mySchool()

// Declaration of local variables.

String schoolName; // Compilation error due to not initializing of value.

System.out.println("Name of School: " +schoolName);

}
3. We cannot 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.

2) Instance Variable
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.
Page 9
IISem BCA OOPS USING 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.

3) Static variable

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.
OPERATORS
Operators are used to perform operations on variables and values.
Java provides many types of operators which are classified based on the functionality
they provide.

Java divides the operators into the following groups:

1 Arithmetic Operators
2 Unary Operators
3 Assignment Operator
4 Relational Operators
5 Logical Operators
6 Ternary Operator
7 Bitwise Operators
8 Shift Operators
9 instance of operator
Arithmetic Operators

Page 10
IISem BCA OOPS USING JAVA

They are used to perform simple arithmetic operations on primitive data types.

2 Unary Operators
Unary operators need only one operand. They are used to increment, decrement or
negate a value.

Page 11
IISem BCA OOPS USING JAVA

3 Assignment Operator
Assignment operator is used to assign a value to any variable.

4 Relational Operators
These operators are used to check for relations like equality, greater than, less
than.

Page 12
IISem BCA OOPS USING JAVA

5 Logical Operators
Logical operators are used to determine the logic between variables or values

6 Ternary Operator
A ternary operator evaluates the test condition and executes a block of code
based on the result of the condition.
Syntax
condition ? expression1 : expression2;
Here, condition is evaluated and
• if condition is true, expression1 is executed.
• And, if condition is false, expression2 is executed.

Control structures in Java

Page 13
IISem BCA OOPS USING JAVA

Three kinds of control structures in Java

• Decision Making statements


o if statements
o switch statement
• Loop statements
o do while loop
o while loop
o for loop
o for-each loop
• Jump statements
o break statement
o continue statement

Decision Making statements

if statement: It is a simple decision-making statement. It is used to decide whether the


statement or block of statements should be executed or not. Block of statements will be
executed if the given condition is true otherwise the block of the statement will be
skipped.

public class IfStatementExample


{
public static void main(String arg[])
{
int a = 5;
int b = 4;
// Evaluating the expression that will return true or false
if (a > b) {
System.out.println("a is greater than b");
}
}
Nested if statement: Nested if statements mean an if statement inside an if
statement. The inner block of if statement will be executed only if the outer block
condition is true.

public class NestedIfStatementExample

Page 14
IISem BCA OOPS USING JAVA

public static void main(String arg[])

int age = 20;

boolean hasVoterCard = true;

// Evaluating the expression that will return true or false

if (age > 18)

// If outer condition is true then this condition will be check

if (hasVoterCard)

System.out.println("You are Eligible");

if-else statement: An if-else statement, there are two blocks one is if block and
another is else block. If a certain condition is true, then if block executes otherwise else
block executes.

public class IfElseStatementExample

Page 15
IISem BCA OOPS USING JAVA

public static void main(String arg[]) {

int a = 10;

int b = 50;

// Evaluating the expression that will return true or false

if (a > b)

System.out.println("a is greater than b");

else

System.out.println("b is greater than a");

if-else if statement/ ladder if statements: If we want to execute the different codes


based on different conditions then we can use if-else-if. It is also known as if-else if
ladder. This statement is always be executed from the top down. During the execution
of conditions if any condition founds true, then the statement associated with that if it is
executed, and the rest of the code will be skipped. If none of the conditions is true, then
the final else statement will be executed.

Page 16
IISem BCA OOPS USING JAVA

public class IfElseIfStatementExample


{
public static void main(String arg[]) {
int a = 10;
// Evaluating the expression that will return true or false
if (a == 1)
{
System.out.println("Value of a: "+a);
}
// Evaluating the expression that will return true or false
else if(a == 5)
{
System.out.println("Value of a: "+a);
}
// Evaluating the expression that will return true or false
else if(a == 10)
{
System.out.println("Value of a: "+a);
}
else
{
System.out.println("else block");
}
}
}
Switch statement: The switch statement is like the if-else-if ladder statement. To reduce
the code complexity of the if-else-if ladder switch statement comes.
In a switch, the statement executes one statement from multiple statements based on
condition. In the switch statements, we have a number of choices and we can perform a
different task for each choice. public class SwitchStatementExample

public static void main(String arg[]) {

int a = 10;

// Evaluating the expression that will return true or false

Page 17
IISem BCA OOPS USING JAVA

switch(a)

case 1:

System.out.println("Value of a: 1");

break;

case 5:

System.out.println("Value of a: 5");

break;

case 10:

System.out.println("Value of a: 10");

break;

default:

System.out.println("else block");

break;

Loop statements

Statements that execute a block of code repeatedly until a specified condition is met are
known as looping statements. Java provides the user with three types of loops

Page 18
IISem BCA OOPS USING JAVA

While

Known as the most common loop, the while loop evaluates a certain condition. If the
condition is true, the code is executed. This process is continued until the specified
condition turns out to be false.
The condition to be specified in the while loop must be a Boolean expression.

Syntax:

while (condition)

statementOne;

public class whileTest

public static void main(String args[])

int i = 5;

while (i <= 15)

System.out.println(i);

i = i+2;

Page 19
IISem BCA OOPS USING JAVA

Do..while

The do-while loop is similar to the while loop, the only difference being that the
condition in the do-while loop is evaluated after the execution of the loop body. This
guarantees that the loop is executed at least once

Syntax

do{

//code to be executed

}while(condition);

Example

public class Main

public static void main(String args[])

int i = 20;

do

System.out.println(i);

i = i+1;

} while (i <= 20);

Page 20
IISem BCA OOPS USING JAVA

For

The for loop in java is used to iterate and evaluate a code multiple times. When the
number of iterations is known by the user, it is recommended to use the for loop.

Syntax

for (initialization; condition; increment/decrement)

statement;

Example

public class forLoop

public static void main(String args[])

for (int i = 1; i <= 10; i++)

System.out.println(i);

Method in Java

A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation. It is used to achieve the reusability of

Page 21
IISem BCA OOPS USING JAVA

code. We write a method once and use it many times. We do not require to write code
again and again. It also provides the easy modification and readability of code,

Method Declaration

The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method
header,

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: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in
our application.
o Private: When we use a private access specifier, the method is accessible only in
the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.

Page 22
IISem BCA OOPS USING JAVA

o Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.

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.

Naming a Method

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method

Page 23
IISem BCA OOPS USING JAVA

Predefined Method

In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in
the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc.

User-defined Method

The method written by the user or programmer is known as a user-defined method.


These methods are modified according to the requirement.

public static void findEvenOdd(int num)


{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}

Method Overloading in Java

Method Overloading is a feature that allows two or more methods may have the same
name but different in parameters, These methods are called overloaded methods and
this feature is called method overloading.
void func() { ... }

void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ... }

Here, the func() method is overloaded. These methods have the same name but accept
different arguments.

Example2:

Page 24
IISem BCA OOPS USING JAVA

Java array

Java array is an object which contains elements of a similar data type The elements of
an array are stored in a contiguous memory location. It is a data structure where we
store similar elements.

Page 25
IISem BCA OOPS USING JAVA

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

The general form of a one-dimensional array declaration is


type var-name[];
OR
type[] var-name;

Instantiating an Array in Java

When an array is declared, only a reference of an array is created.


To create or give memory to the array
var-name = new type [size];

Example:

int intArray[]; //declaring array


intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one

Instantiation of an Array in Java

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

int[] myNum = {10, 20, 30, 40};

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

Page 26
IISem BCA OOPS USING JAVA

Loop Through an Array

You can loop through the array elements with the for loop, and use the length property
to specify how many times the loop should run.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++) {

System.out.println(cars[i]);

Loop Through an Array with For-Each

Syntax

for (type variable : arrayname) {

...

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {

System.out.println(i);

Page 27
IISem BCA OOPS USING JAVA

Java program to illustrate creating an array of integers

class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}

Multidimensional arrays are arrays of arrays

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

public class multiDimensional


{
public static void main(String args[])
{

Page 28
IISem BCA OOPS USING JAVA

// declaring and initializing 2D array


int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}
Output
279
361
742

Passing Arrays to Methods

Like variables, we can also pass arrays to methods.

public class Test


{
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};

// passing array to method sum


sum(arr);

public static void sum(int[] arr)


{

Page 29
IISem BCA OOPS USING JAVA

// getting sum of array values


int sum = 0;

for (int i = 0; i < arr.length; i++)


sum+=arr[i];

System.out.println("sum of array values : " + sum);


}
}

Output
sum of array values : 15

JAGGED ARRAY IN JAVA

Jagged arrays are a special type of arrays that can be used to store rows of data of
varying lengths

In jagged array we can create a 2-D array but with a variable number of columns in
each row.

// Program to demonstrate 2-D jagged array in Java

class Main {
public static void main(String[] args)

Page 30
IISem BCA OOPS USING JAVA

{
// Declaring 2-D array with 2 rows
int arr[][] = new int[2][];

// Making the above array Jagged

// First row has 3 columns


arr[0] = new int[3];

// Second row has 2 columns


arr[1] = new int[2];

// Initializing array
int count = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++;

// Displaying the values of 2D Jagged array


System.out.println("Contents of 2D Jagged Array");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}

Output
Contents of 2D Jagged Array
012
34

Page 31
IISem BCA OOPS USING JAVA

Array of objects

Java programming language is all about classes and objects as it is an object-oriented


programming .The array of objects, as defined by its name, stores an array of objects

// Java program to demonstrate initializing


// an array of objects using a method

class GFG {

public static void main(String args[])


{

// Declaring an array of student


Student[] arr;

// Allocating memory for 2 objects


// of type student
arr = new Student[2];

// Creating actual student objects


arr[0] = new Student();
arr[1] = new Student();

// Assigning data to student objects


arr[0].setData(1701289270, "Satyabrata");
arr[1].setData(1701289219, "Omm Prasad");

// Displaying the student data

Page 32
IISem BCA OOPS USING JAVA

System.out.println(
"Student data in student arr 0: ");
arr[0].display();

System.out.println(
"Student data in student arr 1: ");
arr[1].display();
}
}

// Creating a Student clas with


// id and name as a attributes
class Student {

public int id;


public String name;

// Method to set the data to


// student objects
public void setData(int id, String name)
{
this.id = id;
this.name = name;
}

// display() method to display


// the student data
public void display()
{
System.out.println("Student id is: " + id + " "+ "and Student name is: + name);
System.out.println();
}
}

Page 33
IISem BCA OOPS USING JAVA

JAVA MATH
The java.lang.Math class contains many methods that allows you to perform
mathematical tasks on numbers.

The various java math methods are as follows:

Page 34
IISem BCA OOPS USING JAVA

public class JavaMathExample1


{
public static void main(String[] args)
{
double x = 28;
double y = 4;

// return the maximum of two numbers


System.out.println("Maximum number of x and y is: " +Math.max(x, y));

// return the square root of y


System.out.println("Square root of y is: " + Math.sqrt(y));

//returns 28 power of 4 i.e. 28*28*28*28


System.out.println("Power of x and y is: " + Math.pow(x, y));

// return the logarithm of given value


System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));

// return the logarithm of given value when base is 10


System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));

} }

Output:

Maximum number of x and y is: 28.0

Square root of y is: 2.0

Power of x and y is: 614656.0

Logarithm of x is: 3.332204510175204

Logarithm of y is: 1.3862943611198906

log10 of x is: 1.4471580313422192

Page 35

You might also like