0% found this document useful (0 votes)
68 views134 pages

Unit-Ii Full

The document outlines the syllabus and key concepts of Java programming, including various programming paradigms such as structural, procedural, and object-oriented programming. It details Java applications, platforms, program structure, variables, constructors, data types, access modifiers, and operators. Additionally, it provides examples to illustrate the concepts discussed.

Uploaded by

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

Unit-Ii Full

The document outlines the syllabus and key concepts of Java programming, including various programming paradigms such as structural, procedural, and object-oriented programming. It details Java applications, platforms, program structure, variables, constructors, data types, access modifiers, and operators. Additionally, it provides examples to illustrate the concepts discussed.

Uploaded by

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

UNIT-2 - JAVA PROGRAMMING

PARADIGMS
Syllabus
Object and Classes; Constructor; Data types; Variables; Modifier and
Operators - Structural Programming Paradigm: Branching, Iteration,
Decision making, and Arrays - Procedural Programming
Paradigm:Characteristics; Function Definition; Function Declaration
and Calling; Function Arguments - Object-Oriented Programming
Paradigm: Abstraction; Encapsulation; Inheritance; Polymorphism;
Overriding -Interfaces: Declaring, Implementing; Extended and Tagging
- Package: Package Creation.
What is Java?
 Java is a high level, robust, object-oriented and secure programming language
 Application
 1.Desktop Applications such as acrobat reader, media player, antivirus, etc.
 2.Web Applications such as irctc.co.in, javatpoint.com, etc.
 3.Enterprise Applications such as banking applications.
 4.Mobile
 5.Embedded System
 6.Smart Card
 7.Robotics
 8.Games, etc.
Types of Java Applications
 1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
 2) Web Application

An application that runs on the server side and creates a dynamic page is called a web application. Currently,
Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java.
 3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an enterprise application.
It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for creating
enterprise applications.
 4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.
Java Platforms / Editions

1) Java SE (Java Standard Edition)


It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io,
java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex,
Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built
on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Structure of Java Program
Structure of Java Program
 Documentation Section
 The documentation section is optional for a Java program. It includes basic information about a Java
program, the author's name, date of creation, version, program name, company name, and description
of the program. It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program. To write the
statements in the documentation section, we use comments.
 Single-line Comment: It starts with a pair of forwarding slash (//). For example://First Java Program
 Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For
example:· /*It is an example of multiline comment*/
 Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:/**It is an example of documentation comment*/
 Package Declaration
we declare the package name in which the class is placed.There can be only one package statement in a
Java program.It is necessary because a Java class can be placed in different packages and directories
based on the module they are used. For all these classes package belongs to a single parent directory.
We use the keyword package to declare the package name. For example:
 1.package javaprogram; //where javaprogram is the package name
 2.package com.javaprogram; //where com is the root directory and javaprogram is the subdirectory
CONTD...
 Import Statements
 The package contains the many predefined classes and interfaces. If we want to use any class of a particular package,
we need to import that class. The import statement represents the class stored in the other package. We use the import
keyword to import the class. For example:
1.import java.util.Scanner; //it imports the Scanner class only
2.import java.util.*; //it imports all the class of the java.util package
 Interface Section
 It is an optional section. We can create an interface in this section if required. We use the interface keyword to create an
interface. An interface is a slightly different from the class. It contains only constants and method declarations. Another
difference is that it cannot be instantiated. We can use interface in classes by using the implements keyword. An
interface can also be used with other interfaces by using the extends keyword. For example:
interface car
{
void start();
void stop();
}
 Class Variables and Constants
class Student //class definition {
String sname; //variable
int id;
double percentage; }
Main Method Class

 The execution of all Java programs starts from the main() method. In other words, it is an entry point of the
class. It must be inside the class. Inside the main method, we create objects and call the methods. We use the
following statement to define the main() method:
 public static void main(String args[]) {
}
For example:public class Student //class definition {
public static void main(String args[]) {
//statements
} }
Methods and behavior
 We define the functionality of the program by using the methods. The methods are the set of instructions that

we want to perform. These instructions execute at runtime and perform the specified task. For example:
public class Demo //class definition {
public static void main(String args[]) {
void display() {
System.out.println("Welcome to java");
} statements
} }
Object
 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.
 An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely
class in Java
 A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.
 A class in Java can contain:
 Fields
 Constructors
 Blocks
 Nested class and interface
 Syntax to declare a class:

class <class_name>{
field;
method;
}
Object and Class Example
main within the class main outside the class

//Defining a Student class. Creating Student class.


class Student{ class Student{
//defining fields int id;
int id;//field or data member or instance variable String name;
String name; }
//creating main method inside the Student class //Creating another class TestStudent1 which contains the main method
public static void main(String args[]){ class TestStudent1{
//Creating an object or instance public static void main(String args[]){
Student s1=new Student();//creating an object of Student Student s1=new Student();
//Printing values of the object System.out.println(s1.id);
System.out.println(s1.id);//access .member through ref. variable System.out.println(s1.name);
System.out.println(s1.name); }
} }
} Output:
Output: 0 0
null null
3 Ways to initialize object
1.By reference variable
2.By method
3.By constructor

Initialization through reference Initialization through method


TestStudent4.java
TestStudent2.java
class Student{
class Student{
int rollno;
int id;
String name;
String name;
void insertRecord(int r, String n){
}
rollno=r;
class TestStudent2{
name=n; }
public static void main(String args[]){
void displayInformation()
Student s1=new Student();
{System.out.println(rollno+" "+name);} }
s1.id=101;
class TestStudent4{
s1.name="Sonoo";
public static void main(String args[]){
System.out.println(s1.id+" "+s1.name);//
printing members with a white space
Student s1=new Student();
Student s2=new Student(); Output:
}
s1.insertRecord(111,"Karan"); 111 Karan
}
s2.insertRecord(222,"Aryan"); 222 Aryan
Output:
101 Sonoo
s1.displayInformation();
Java Variables
 Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
 1) Local Variable
 A variable declared inside the body of the method is called local variable. You can use this variable only
within that method A local variable cannot be defined with "static" keyword.
 2) Instance Variable
 A variable declared inside the class but outside the body of the method, is called an instance variable. It
is not declared as static.
 It is called an instance variable because its value is instance-specific and is not shared among instances.
 3) Static variable
 A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Example : Types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Constructors in Java
 constructor is a block of codes similar to the method.
 called when an instance of the class is created.
 At the time of calling constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is called.
 It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
 There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
 Rules for creating Java constructor
1.Constructor name must be the same as its class name
2.A Constructor must have no explicit return type
3.A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
 1.Default constructor (no-arg constructor)
 2.Parameterized constructor

Java Default Constructor


 A constructor is called "Default Constructor" when it doesn't have any

parameter.
Syntax of default constructor:
<class_name>(){}
Java Parameterized Constructor
 A constructor which has a specific number of parameters is called a

parameterized constructor.
 The parameterized constructor is used to provide different values to

distinct objects.
Example of default constructor
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Example of parameterized constructor
//
Java Program to demonstrate the use of the par public static void main(String args[]){
ameterized constructor. //creating objects and passing values
class Student4{ Student4 s1 = new Student4(111,"Karan");
int id; Student4 s2 = new Student4(222,"Aryan");
String name; //
//creating a parameterized constructor calling method to display the values of object
Student4(int i,String n){ s1.display();
id = i; s2.display();
name = n; }
} }
//method to display the values Output:
void display() 111 Karan
{System.out.println(id+" "+name);} 222 Aryan
Constructor Overloading in Java

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different task .
//Java program to overload constructors void display()
class Student5{ {System.out.println(id+" "+name+" "+age);}
int id;
String name; public static void main(String args[]){
int age; Student5 s1 = new Student5(111,"Karan");
//creating two arg constructor Student5 s2 = new Student5(222,"Aryan",25);
Student5(int i,String n){ s1.display();
id = i; s2.display();
name = n; }
} }
//creating three arg constructor Output:
Student5(int i,String n,int a){ 111 Karan 0
id = i; 222 Aryan 25
name = n;
age=a;
Data Types in Java

 Data types specify the different


sizes and values that can be
stored in the variable.
 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.
Access Modifiers in Java
 There are four types of Java access modifiers:
 1.Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
 2.Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access level,
it will be the default.
 3.Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it cannot
be accessed from outside the package.
 4.Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the package.
Private
The private access modifier is accessible only within the class.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Example of default access modifier
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Example of protected access modifier
1.//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
Example of public access modifier

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello"); } }
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
} Output:Hello
Operators in Java

 Operator in Java is a symbol that is used to perform operations. For example: +, -, *, /


etc.
 There are many types of operators in Java which are given below:
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.
Java Operator Precedence

Operator Type Category Precedence


postfix expr++ expr--
Unary
prefix ++expr --expr +expr -expr ~ !
multiplicative */%
Arithmetic
additive +-
Shift shift << >> >>>
comparison < > <= >= instanceof
Relational
equality == !=
bitwise AND &
Bitwise bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
Logical
logical OR ||
Ternary ternary ?:
= += -= *= /= %= &= ^= |=
Assignment assignment
<<= >>= >>>=
Java Unary Operator

 The Java unary operators require only one operand. Unary operators are used to perform various operations
i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a boolean Output:
 Java Unary Operator Example: ++ and -- 10
12
public class OperatorExample{ 12
public static void main(String args[]){ 10
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Java Arithmetic Operators
 Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.
 Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10; Output:
int b=5; 15
System.out.println(a+b);//15 5
50
System.out.println(a-b);//5 2
System.out.println(a*b);//50 0
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Java Left Shift Operator

 The Java left shift operator << is used to shift all of the bits in a value to the
left side of a specified number of times.
Java Left Shift Operator Example

public class OperatorExample{


public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
}}
Output:

40

80
Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
Java Right Shift Operator Example

public OperatorExample{
Output:
public static void main(String args[]){ 2
5
System.out.println(10>>2);//10/2^2=10/4=2 2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Java AND Operator Example: Logical && and Bitwise &

 The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
 The bitwise & operator always checks both conditions whether first condition is true or false.

public class OperatorExample{


public static void main(String args[]){
int a=10; Output:
int b=5; False
false
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Java OR Operator Example: Logical || and Bitwise |

 The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
 The bitwise | operator always checks both conditions whether first condition is true or false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
Output:
int b=5; True
int c=20; true
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
}}
Java Ternary Operator

 Java Ternary operator is used as one line replacement for if-then-else statement and
used a lot in Java programming. It is the only conditional operator which takes three
operands.
 Java Ternary Operator Example

public class OperatorExample{


Output:
public static void main(String args[]){ 2
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Java Assignment Operator
 Java assignment operator is one of the most common operators. It is used to assign the value on
its right to the operand on its left.
 Java Assignment Operator Example

public class OperatorExample{


public static void main(String[] args){
int a=10; Output:
a+=3;//10+3 13
System.out.println(a); 9
a-=4;//13-4 18
9
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
STRUCTURAL PROGRAMMING
PARADIGM

Branching, Iteration, Decision making, and Arrays


Java Control Statements | Control Flow in Java

 Java provides three types of control flow statements.


 Decision Making statements
 if statements

 switch statement

 Loop statements
 do while loop

 while loop

 for loop

 for-each loop

 Jump statements
 break statement

 continue statement
Decision-Making statements:

 Decision-making statements evaluate the Boolean expression and


control the program flow depending upon the result of the condition
provided.
 There are two types of decision-making statements in Java, i.e., If
statement and switch statement
1) Simple if statement
 It evaluates a Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Output:
Student.java
x + y is greater
public class Student { than 20
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
if-else statement
 Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements
Student.java
public class Student {
public static void main(String[] args) {
String city = "Delhi";
Output:
if(city == "Meerut") {
Delhi
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
Syntax of Nested if-statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Switch Statement
 The switch statement contains multiple blocks of code called cases
and a single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.
 Cases cannot be duplicate
 Default statement is executed when any of the case doesn't match
the value of expression. It is optional.
 Break statement terminates the switch block when the condition is
satisfied.It is optional, if not used, next case is executed.
The syntax to use the switch statement
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Example switch statement
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0"); Output:
break; 2
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Loop Statements

 In programming, sometimes we need to execute the block


of code repeatedly while some condition evaluates to
true. In Java, we have three types of loops that execute
similarly.
 forloop
 while loop

 do-while loop
Java for loop
 It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know the number of times, we want
to execute the block of code.
for(initialization, condition, increment/decrement) {
//block of statements
}

Calculation.java
public class Calculattion {
public static void main(String[] args) {
int sum = 0; Output:
for(int j = 1; j<=10; j++) { The sum of first 10 natural numbers is
sum = sum + j; 55
}
System.out.println("The sum of first 10 na
tural numbers is " + sum);
}
}
Java for-each loop

for(data_type var : array_name/collection_name){


//statements
}
E.g
public class Calculation { Output:
public static void main(String[] args) { Printing the content of the
// TODO Auto-generated method stub array names:
Java
String[] names = {"Java","C","C++","Python","JavaScript"}; C
System.out.println("Printing the content of the array names:\n"); C++
for(String name:names) { Python
JavaScript
System.out.println(name);
}
}
}
Java while loop
 It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
If the condition is true, then the loop body will be executed; otherwise, the statements after the
loop will be executed.
The syntax of the while loop is given below.
while(condition){
//looping statements
}
public class Calculation {
public static void main(String[] args) { Output:
// TODO Auto-generated method stub Printing the list of first 10
int i = 0; even numbers
System.out.println("Printing the list of fir 0
st 10 even numbers \n"); 2
while(i<=10) { 4
System.out.println(i); 6
i = i + 2; 8
} 10
}
}
Java do-while loop
 The do-while loop checks the condition at the end of the loop after executing the loop statements. When the
number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.It is also
known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop
do
{
//statements
} while (condition);
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do { Printing the list of first 10 even
System.out.println(i); numbers
0
i = i + 2; 2
}while(i<=10); 4
} 6
} 8
10
Jump Statements
 Jump statements are used to transfer the control of the program to the specific statements
 Java break statement

The break statement is used to break the current flow of the program and transfer the control to the
next statement outside a loop or switch statement
BreakExample.java
public class BreakExample {
public static void main(String[] args) { Output:
0
for(int i = 0; i<= 10; i++) { 1
System.out.println(i); 2
if(i==6) { 3
4
break;
5
} 6
}
}
}
Java continue statement

The continue statement doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next
iteration of the loop immediately.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub Output:
for(int i = 0; i<= 2; i++) { 0
1
for (int j = i; j<=5; j++) { 2
if(j == 4) { 3
continue; 5
} 1
2
System.out.println(j); 3
} 5
}
}
}
Java - Arrays

 An array is a collection of similar type of elements which has


contiguous memory location.

Advantages
 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
 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.
Types of Array in java

 There are two types of array.


 Single Dimensional Array
 Multidimensional Array
 Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or) dataType []arr; (or) dataType arr[];
 Instantiation of an Array in Java
arrayRefVar=new datatype[size];
 Multidimensional Array in Java
 In such case, data is stored in row and column based index (also known as matrix form).
 Syntax to Declare Multidimensional Array in Java
 dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or)
 dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];
//Java Program to illustrate how to declare, instantiate, initialize
and traverse the Java array.

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20; Output:
10
a[2]=70; 20
a[3]=40; 70
40
a[4]=50; 50
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Example of Multidimensional Java Array

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; Output:
//printing 2D array 123
245
for(int i=0;i<3;i++){ 445
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Java Functions
Java Functions

• Java is one of the most popular programming languages


in the world, and one of its key features is its ability to
define and use functions.
• Functions in Java are blocks of code that perform a
specific task, and they are used to organize code and
make it more modular and reusable.
Defining a Java Function

In order to define a function in Java, you use the keyword


"public" (or "private" or "protected") followed by the return
type of the function, then the name of the function, and
finally a set of parentheses containing any parameters the
function may take. For example, here is a simple function
that takes no parameters and returns nothing:
1.public void sayHello() {
2. System.out.println("Hello, world!");
3.}
sayHello();
FunctionExample.java
1.import java.util.Scanner;
2.public class FunctionExample {
3. public static void main(String[] args) {
4. Scanner scanner = new Scanner(System.in);
5. System.out.print("Enter a number: ");
6. int num1 = scanner.nextInt();
7. System.out.print("Enter another number: ");
8. int num2 = scanner.nextInt();
9. int sum = add(num1, num2);
10. System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum + ".");
11. public static int add(int a, int b) {
12. return a + b;
13. }
14.}
Output:
Enter a number: 5
Enter another number: 7
The sum of 5 and 7 is 12.
How to Call a Method in Java
• In Java, the method is a collection of statements that
performs a specific task or operation. It is widely used
because it provides reusability of code means that write
once and use it many times.
• It also provides easy modification. Each method has its
own name by which it is called. When the compiler reads
the method name, the method is called and performs the
specified task.
• In this section, we will learn how to call pre-defined,
user-defined, static, and abstract methods in Java.
Calling Static Method in Java
• In Java, a static method is a method that is
invoked or called without creating the object of the
class in which the method is defined.
• All the methods that have static keyword before
the method name are known as static methods.
We can also create a static method by using the
static keyword before the method name. We can
call a static method by using the
ClassName.methodName.
• The best example of the static method is the
main() method. It is called without creating the
object.
StaticMethodCallExample.java
1.import java.util.*;
2.public class StaticMethodCallExample
3.{
4.public static void main(String args[])
5.{
6.int a;
7.//calling static method of the Math class
8.a=Math.min(23,98);
9.System.out.println("Minimum number is: " + a);
10.}
11.}
Output:
Minimum number is 23
Calling User-Defined Method in Java
• To call a user-defined method, first, we create a
method and then call it. A method must be
created in the class with the name of the
method, followed by parentheses (). The method
definition consists of a method header and
method body.
• We can call a method by using the following:
• 1.method_name(); //non static method calling
• If the method is a static method, we use the
following:
• 1.obj.method_name(); //static method calling
• Where obj is the object of the class.
• In the following example, we have created two
user-defined methods named showMessage()
and displayMessage(). The showMessage()
method is a static method and displayMessage()
method is a non-static method.
• Note that we have called the showMessage()
method directly, without using the object. While
the displayMessage() method is called by using
the object of the class.
MethodCallExample.java
1.public class MethodCallExample
2.{
3.//user-defined static method
4.static void showMessage()
5.{
6.System.out.println("The static method invoked.");
7.}
8.//user-defined non-static method
9.void displayMessage()
10.{
11.System.out.println("Non-static method invoked.");
12.}
13.public static void main(String[] args)
14.{
15.//calling static method without using the object
16.showMessage(); //called method
17.//creating an object of the class
18.MethodCallExample me=new MethodCallExample();
19.//calling non-static method
20.me.displayMessage(); //called method
21.}
22.}
• Output:
• The static method invoked.
• Non-static method invoked.
• When a class has two or more methods with the same
name it is differentiated by either return type or types of
parameter or number of parameters. This concept is
called method overloading. For example:
• 1.int sum(int x, int y);
• 2.double sum(double x, double y);
• The above two methods have the same name sum() but
both are different. The first sum() method returns an int
value and parses two integer x and y as parameters.
While the second sum() method returns a double value
and parses two double values a and y as parameters.
• Let's create a program that overloads sub() method.
MethodOverloadingExample.java
1.public class MethodOverloadingExample
2.{
3.static int sub(int x, int y)
4.{
5.return x - y;
6.}
7.static double sub(double x, double y)
8.{
9.return x - y;
10.}
11.public static void main(String[] args)
12.{
13.int a = sub(45, 23);
14.double b = sub(23.67,10.5);
15.System.out.println("subtraction of integer values:
" +a);
16.System.out.println("subtraction of double values:
" +b);
17.}
18.}
Output:
subtraction of integer values: 22
subtraction of double values: 13.170000000000002
Object-Oriented Programming Paradigm
Abstraction
• Abstract class in Java
• A class which is declared with the abstract keyword is
known as an abstract class in Java. It can have abstract
and non-abstract methods (method with the body).
• Abstraction in Java
• Abstraction is a process of hiding the implementation
details and showing only functionality to the user.
• Another way, it shows only essential things to the user
and hides the internal details, for example, sending SMS
where you type the text and send the message. You
don't know the internal processing about the message
delivery.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1.Abstract class (0 to 100%)
2.Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as
an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.
• Points to Remember
• An abstract class must be declared with an abstract
keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass
not to change the body of the method.
• Example of abstract class
• 1.abstract class A{}
Abstract Method in Java
A method which is declared as abstract and
does not have implementation is known as
an abstract method.
Example of abstract method
1.abstract void printStatus();//
no method body and abstract
Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only
one abstract method run. Its implementation is provided by
the Honda class.
1.abstract class Bike{
2. abstract void run();
3.}
4.class Honda4 extends Bike{
5.void run(){System.out.println("running safely");}
6.public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9.}
10.}
output
Encapsulation in Java
• Encapsulation in Java is a process of wrapping code and
data together into a single unit.
• Advantage of Encapsulation in Java
• By providing only a setter or getter method, you can
make the class read-only or write-only.
• It provides you the control over the data.
• It is a way to achieve data hiding in Java because other
class will not be able to access the data through the
private data members.
• The encapsulate class is easy to test. So, it is better for
unit testing.
• The standard IDE's are providing the facility to generate
the getters and setters. So, it is easy and fast to create
an encapsulated class in Java.
Test.java
1.//A Java class to test the encapsulated class.
2.package com.javatpoint;
3.class Test{
4.public static void main(String[] args){
5.//creating instance of the encapsulated class
6.Student s=new Student();
7.//setting value in the name member
8.s.setName("vijay");
9.//getting value of the name member
10.System.out.println(s.getName());
11.}
12.}
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output:
vijay
Read-Only class
1.//A Java class which has only getter methods.
2.public class Student{
3.//private data member
4.private String college="AKG";
5.//getter method for college
6.public String getCollege(){
7.return college;
8.}
9.}
Now, you can't change the value of the college data member which is
"AKG".
1.s.setCollege("KITE");//will render compile time error
Write-Only class

1.//A Java class which has only setter methods.


2.public class Student{
3.//private data member
4.private String college;
5.//getter method for college
6.public void setCollege(String college){
7.this.college=college;
8.}
9.}
Inheritance in Java
• Inheritance in Java is a mechanism in which one object
acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented
programming system).
• The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also
known as a parent-child relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can
be achieved).
• For Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have
common properties. It is a template or blueprint from
which objects are created.
• 
• Sub Class/Child Class: Subclass is a class which inherits
the other class. It is also called a derived class, extended
class, or child class.
• Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a
base class or a parent class.
• Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new
class. You can use the same fields and methods already
defined in the previous class.
The syntax of Java Inheritance
1.class Subclass-name extends Superclass-name
2.{
3. //methods and fields
4.}
The extends keyword indicates that you are making a new
class that derives from an existing class. The meaning of
"extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is
called a parent or superclass, and the new class is called
child or subclass.
• Java Inheritance Example

• Programmer is the subclass and Employee is the


superclass. The relationship between the two
classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.
1.class Employee{
2. float salary=40000;
3.}
4.class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus
);
10.}
11.}
OUTPUT
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can
access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
There can be three types of inheritance in
java: single, multilevel and hierarchical.In java
programming, multiple and hybrid inheritance is
supported through interface only.
• Note: Multiple inheritance is not supported in
Java through class.
• When one class inherits multiple classes, it is
known as multiple inheritance. For Example:
Single Inheritance Example
• When a class inherits another class, it is known
as a single inheritance. In the example given
below, Dog class inherits the Animal class, so
there is the single inheritance.
• File: TestInheritance.java
1.class Animal{
2.void eat(){System.out.println("eating...");}
3.}
4.class Dog extends Animal{
5.void bark(){System.out.println("barking...");}
6.}
7.class TestInheritance{
8.public static void main(String args[]){
9.Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known
as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the
Dog class which again inherits the Animal class,
so there is a multilevel inheritance.
File: TestInheritance2.java
1.class Animal{
2.void eat(){System.out.println("eating...");}
3.}
4.class Dog extends Animal{
5.void bark(){System.out.println("barking...");}
6.}
7.class BabyDog extends Dog{
8.void weep(){System.out.println("weeping...");}
9.}
10.class TestInheritance2{
11.public static void main(String args[]){
12.BabyDog d=new BabyDog();
13.d.weep();
14.d.bark();
15.d.eat();
16.}}
Output:
weeping...
barking...
eating...
7.class TestInheritance{
8.public static void main(String args[]){
9.Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}
Output:
barking...
eating...
Hierarchical Inheritance
Example
When two or more classes inherits a single class, it is
known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so
there is hierarchical inheritance.
File: TestInheritance3.java
1.class Animal{
2.void eat(){System.out.println("eating...");}
3.}
4.class Dog extends Animal{
5.void bark(){System.out.println("barking...");}
6.}
7.class Cat extends Animal{
8.void meow(){System.out.println("meowing...");}
9.}
10.class TestInheritance3{
11.public static void main(String args[]){
12.Cat c=new Cat();
13.c.meow();
14.c.eat();
15.//c.bark();//C.T.Error
16.}}
Output:
meowing...
eating...
Why multiple inheritance is not supported in java?

• To reduce the complexity and simplify the language,


multiple inheritance is not supported in java.
• Consider a scenario where A, B, and C are three classes.
The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B
class.
• Since compile-time errors are better than runtime errors,
Java renders compile-time error if you inherit 2 classes.
So whether you have same method or different, there will
be compile time error.
Polymorphism
Method Overloading in Java
• If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.
• If we have to perform only one operation, having same
name of the methods increases the readability of the
program.
• Suppose you have to perform addition of the given
numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to
understand the behavior of the method because its
name differs.
Advantage of method overloading
• Method overloading increases the readability of the
program.
• Different ways to overload the method
There are two ways to overload the method in java
• 1.By changing number of arguments
• 2.By changing the data type
Method Overloading
In Java, Method Overloading is not possible by changing
the return type of the method only.
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add()
method performs addition of two numbers and second add
method performs addition of three numbers.
In this example, we are creating static methods so that we
don't need to create instance for calling methods.
1.class Adder{
2.static int add(int a,int b){return a+b;}
3.static int add(int a,int b,int c){return a+b+c;}
4.}
5.class TestOverloading1{
6.public static void main(String[] args){
7.System.out.println(Adder.add(11,11));
8.System.out.println(Adder.add(11,11,11));
9.}}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs
in data type. The first add method receives two integer
arguments and second add method receives two double
arguments.
1.class Adder{
2.static int add(int a, int b){return a+b;}
3.static double add(double a, double b){return a+b;}
4.}
5.class TestOverloading2{
6.public static void main(String[] args){
7.System.out.println(Adder.add(11,11));
8.System.out.println(Adder.add(12.3,12.6));
9.}}
Output:
22
24.9
Why Method Overloading is not possible by changing the
return type of method only?

In java, method overloading is not possible by changing the


return type of the method only because of ambiguity. Let's
see how ambiguity may occur:
1.class Adder{
2.static int add(int a,int b){return a+b;}
3.static double add(int a,int b){return a+b;}
4.}
5.class TestOverloading3{
6.public static void main(String[] args){
7.System.out.println(Adder.add(11,11));//ambiguity
8.}}
Output:
Compile Time Error: method add(int,int) is already defined
in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java
determine which sum() method should be called?
Method Overriding in Java
If subclass (child class) has the same method as declared
in the parent class, it is known as method overriding in
Java.
In other words, If a subclass provides the specific
implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
Method overriding is used to provide the specific
implementation of a method which is already provided by
its superclass.
1.The method must have the same name as in the parent
class
2.The method must have the same parameter as in the
parent class.
3.There must be an IS-A relationship (inheritance).
A real example of Java Method
Overriding
• Consider a scenario where Bank is a class that provides
functionality to get the rate of interest. However, the rate of
interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of
interest.
Interface in Java
• An interface in Java is a blueprint of a class. It has static
constants and abstract methods.
• The interface in Java is a mechanism to achieve
abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method
body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract
class.
• Since Java 8, we can have default and static
methods in an interface.
• Since Java 9, we can have private methods in an
interface.
• Why use Java interface?
• There are mainly three reasons to use interface.
They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of
multiple inheritance.
• It can be used to achieve loose coupling.
How to declare an interface?
• An interface is declared by using the interface keyword.
It provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the
fields are public, static and final by default. A class that
implements an interface must implement all the methods
declared in the interface.
• Syntax:
• 1.interface <interface_name>{
• 2.
• 3. // declare constant fields
• 4. // declare methods that abstract
• 5. // by default.
• 6.}
interface

The relationship between classes and interfacesAs shown in the figure given
below, a class extends another class, an interface extends another interface, but a
class implements an interface.
Java Interface Example: Drawable
In this example, the Drawable interface has only
one method. Its implementation is provided by
Rectangle and Circle classes.
1.//Interface declaration: by first user
2.interface Drawable{
3.void draw();
4.}
5.//Implementation: by second user
6.class Rectangle implements Drawable{
7.public void draw()
{System.out.println("drawing rectangle");}
8.}
9.class Circle implements Drawable{
10.public void draw(){System.out.println("drawing circle");}
11.}
12.//Using interface: by third user
13.class TestInterface1{
14.public static void main(String args[]){
15.Drawable d=new Circle();//
In real scenario, object is provided by method e.g. getDraw
able()
16.d.draw();
17.}}
Output:
drawing circle
Multiple inheritance in Java by interface

• If a class implements multiple interfaces, or an


interface extends multiple interfaces, it is known
as multiple inheritance.
1.interface Printable{
2.void print();
3.}
4.interface Showable{
5.void show();
6.}
7.class A7 implements Printable,Showable{
8.public void print(){System.out.println("Hello");}
9.public void show(){System.out.println("Welcome");}
10.public static void main(String args[]){
11.A7 obj = new A7();
12.obj.print();
13.obj.show();
14. }
15.}
Output:
Hello
Welcome
Nested Interface in Java
Note: An interface can have another interface which is
known as a nested interface. We will learn it in detail in the
nested classes chapter. For example:

1.interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6.}
Java Package
• A java package is a group of similar types of classes,
interfaces and sub-packages.
• Package in java can be categorized in two form, built-in
package and user-defined package.
• There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and
using user-defined packages.
• Advantage of Java Package
• 1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
• 2) Java package provides access protection.
• 3) Java package removes naming collision.
Simple example of java
The package keyword package
is used to create a package in java.
1.//save as Simple.java
2.package mypack;
3.public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7.}
How to compile java package
If you are not using any IDE, you need to follow the syntax
given below:
1.javac -d directory javafilename
For example
1.javac -d . Simple.java
The -d switch specifies the destination where to
put the generated class file. You can use any
directory name like /home (in case of Linux),
d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you
can use . (dot).
How to run java package program
You need to use fully qualified name e.g.
mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to
put the class file i.e. it represents destination. The .
represents the current folder.
How to access package from another package?

There are three ways to access the package from


outside the package.
1.import package.*;
2.import package.classname;
3.fully qualified name.
1) Using packagename.*

• If you use package.* then all the classes and


interfaces of this package will be accessible but
not subpackages.
• The import keyword is used to make the classes
and interface of another package accessible to
the current package.
Example of package that import the packagename.*
1.//save by A.java
2.package pack;
3.public class A{
4. public void msg(){System.out.println("Hello");}
5.}
1.//save by B.java
2.package mypack;
3.import pack.*;
4.
5.class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
2) Using packagename.classname
• If you import package.classname then only
declared class of this package will be accessible.
Example of package by import package.classname
1.//save by A.java
2.
3.package pack;
4.public class A{
5. public void msg(){System.out.println("Hello");}
6.}
• 1.//save by B.java
• 2.package mypack;
• 3.import pack.A;
• 4.
• 5.class B{
• 6. public static void main(String args[]){
• 7. A obj = new A();
• 8. obj.msg();
• 9. }
• 10.}
• Output:Hello
3) Using fully qualified name
• If you use fully qualified name then only declared
class of this package will be accessible. Now
there is no need to import. But you need to use
fully qualified name every time when you are
accessing the class or interface.
• It is generally used when two packages have
same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import
fully qualified name
1.//save by A.java
2.package pack;
3.public class A{
4. public void msg(){System.out.println("Hello");}
5.}
1.//save by B.java
2.package mypack;
3.class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//
using fully qualified name
6. obj.msg();
7. }
8.}
Output:Hello
Subpackage in javaPackage inside the package is called the
subpackage. It should be created to categorize the package further.
Example of Subpackage

1.package com.javatpoint.core;
2.class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6.}
How to put two public classes in a package?
If you want to put two public classes in a package,
have two java source files containing one public
class, but keep the package name same. For
example:
1.//save as A.java
2.package javatpoint;
3.public class A{}
1.//save as B.java
2.package javatpoint;
3.public class B{}

You might also like