Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 27

Contents

 Arrays

 Methods

 Constructors

 Class & Objects


ARRAYS
Objects that help us organize large amounts of information
It is an ordered list of values
Each value has a numeric index
The entire array
has a single name 0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91

scores
An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

Value in an array is referenced by the array name followed by the index in brackets.

For example, scores[2]: refers to the value 94 (the 3rd value in the array)

• Element type can be a primitive type or an object reference


Types of Array: Single Dimensional & Multidimensional Array
•Single Dimensional Array Instantiation:
Syntax to declare: arrayRefVar=new datatype[size];
1. dataType[] arr; (or)
2. dataType arr[];
//Declaration, instantiation & initialization of array in a single line
class Testarray{
public static void main(String args[]){
int a[]=new int[5]; class array1{
//declaration and instantiation
a[0]=10; //initialization public static void main(String args[]){
a[1]=20; int a[]={33,3,4,5};//declaration, instantiation and initialization
a[2]=70;
a[3]=40; //printing array
a[4]=50; for(int i=0;i<a.length;i++)//length is the property of array
//traversing array
for(int i=0;i<a.length;i++)//length is array’s
System.out.println(a[i]);
property }}
System.out.println(a[i]);
}}
MultiDimensional Array:
Data is stored in row & column based index (also known as matrix form).

Syntax to declare:
1.dataType[][] arrayRefVar; (or) Instantiation:
2.dataType arrayRefVar[][]; (or)
3.dataType []arrayRefVar[]; int[][] arr=new int[3][3]; //3 row,3 column

//Example of multidimensional array


class Testarray3{
public static void main(String args[]){
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D array

//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(); } }}
CLASS AND OBJECT
Classes and objects are the two main aspects of OOP
OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
OOP is a methodology or paradigm to design a program using classes and objects. It simplifies s/w development and
maintenance by providing some concepts:
•Object
•Class
•Inheritance
•Polymorphism
•Abstraction
•Encapsulation
a) object
• An entity that has state and behavior is known as an object
e.g., chair, bike, marker, pen, table, car, etc.

• An object has three characteristics:

Example: Pen is an object. Its name is Rotomac; color is white, known


as its state. It is used to write, so writing is its behavior.

An object is an instance of a class.

A class is a template or blueprint from which objects are created. So, an object is the
instance(result) of a class.
b) class
 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. Syntax to declare a class:
class <class_name>{
 A class in Java can contain:
field;
 Fields method;
 Methods }
 Constructors
 Blocks
 Nested class and interface

Create an Object
An object is created from a class.
To create an object, specify the class name, followed by the object name, and use keyword new:

new keyword is used to allocate memory at runtime


Rules for Java Class

• A class can have only public or default access specifier.


• It can be either abstract, final or concrete (normal class).
• It must have the class keyword, and class must be followed by a legal identifier.
• It may optionally extend only one parent class. By default, it extends Object class.
• The variables and methods are declared within a set of curly braces.
• A Java class can contains fields, methods, constructors, and blocks.

class Student.
A simple class example {
Suppose, Student is a class and student's name, roll number, age are its String name;
fields and info() is a method. Then class will look like below. int rollno;
int age;
void info(){
// some code
}
}
Ex: Create Student class
Student class has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's value.

File: Student.java Output: 0


//Defining a Student class.
class Student{ null
int id; //field or data member or instance variable
String name;

public static void main(String args[]){


Student s1=new Student(); //Creating an object or instance

//Printing values of the object


System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
Another Ex.

public class Student{

String name; int rollno; int age;


void info(){
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args) {
Student student = new Student();
student.name = "Ramesh";
student.rollno = 253; Output:
student.age = 25;
student.info(); Name: Ramesh
}} Roll Number: 253
Age: 25
METHODS
A method is a block of code grouped together to perform a certain task or operation.

• It is used to achieve the reusability of code.


• We write a method once and use it many times.
• It also provides the easy modification and readability of code
• The method is executed by its name and only when we call or invoke it.
• The most important method in Java is the main() method.
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: includes the method name and parameter list.


• Access Specifier: specifies the visibility of the method
java has 4 access specifier: Public, Private, Protected, Default
• Return Type: a data type that a method returns, give void if it does not return anything.
• Method Name: a unique name to define name of a method.
• Parameter List: list of parameters separated by a comma and enclosed in the pair of ().
• Method Body: contains all the actions to be performed, enclosed within pair of {}
Types of Method
Types of methods: (1) Predefined Method (2) User-defined Method

(1) Predefined Method: Methods that is already defined in the Java class libraries.
•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.

• Each and every predefined method is defined inside a class.


Example of the predefined method
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print(“Maximum number is: " + Math.max(9,7));
}

Output:
Maximum number is: 9
2. User-defined Method
Method written by the user or programmer. These methods are modified according to the requirement.

Ex: Create and call user defined method(findEvenOdd) that checks the number is even or odd:

import java.util.Scanner;
public class EvenOdd {

public static void findEvenOdd(int num) //user defined method Output 1:


{ Enter the number: 16
if(num%2==0)
System.out.println(num+" is even");
16 is even
else
System.out.println(num+" is odd"); Output 2:
} Enter the number: 11
11 is odd
public static void main (String args[]) {
Scanner scan=new Scanner(System.in); //creating Scanner class object
System.out.print("Enter the number: ");
int num=scan.nextInt(); //reading value from user
findEvenOdd(num); //method calling
}

}
Call by Value and Call by Reference in Java

There are two ways to pass an argument to a method

1)call-by-value :
In this approach copy of an argument value is pass to a method.
Changes made to the argument value inside the method will have no
effect on the arguments.

2) call-by-reference :
Java does not support call by reference directly. However, we can
achieve similar behavior by passing objects as arguments since object
references are passed by value.
original value is not changed, because a copy of the argument is passed to the method, and
modifications to the parameter inside the method do not affect the original argument.)

public class CallByValueExample {


Example of call by value:
public static void main(String[] args) {
int x = 10;
System.out.println("Before calling method, x = " + x);
modifyValue(x);
System.out.println("After calling method, x = " + x);
}

public static void modifyValue(int num) {


num = num * 2;
System.out.println("Inside method, num = " + num);
}
}

Output: Before calling method, x = 10


Inside method,num=20;
After calling method, x = 10
Example: Call by Reference : changes are reflected
class Person {
String name="aru"; }

public class cbr {


public static void main(String[] args) {
Person person = new Person();
System.out.println("Before calling method, person.name = " + person.name);
modifyObject(person);
System.out.println("After calling method, person.name = " + person.name);
}

public static void modifyObject(Person p) {


p.name = "Alice";
System.out.println("Inside method, p.name = " + p.name);
}
}
Another Example: Call by Reference using an array:

public class cbr{


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Before calling method, numbers[0] = " + numbers[0]);
modifyArray(numbers);
System.out.println("After calling method, numbers[0] = " + numbers[0]);
}

public static void modifyArray(int[] arr) {


arr[0] = 100;
System.out.println("Inside method, arr[0] = " + arr[0]);
}
}
Method overloading
(1) Method overloading by changing data type of arguments.
Example:
class Calculate {
void sum (int a, int b) {
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b) {
System.out.println("sum is"+(a+b));
}
public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
(2) Method overloading by changing no. of argument.
Example:
class Demo
{
void multiply(int l, int b)
{
System.out.println("Result is"+(l*b)) ;
}
void multiply(int l, int b,int h)
{
System.out.println("Result is"+(l*b*h));
}
public static void main(String[] args) {
Demo ar = new Demo();
ar.multiply(8,5); //multiply(int l, int b) is method is called
ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
} }
Overloading main Method
In Java, we can overload the main() method using different number and types of
parameter but the JVM only understand the original main() method.

Example:we created three main() methods having different parameter types.


public class MethodDemo{
public static void main(int args) {
System.out.println("Main Method with int argument Executing");
System.out.println(args); }
public static void main(char args) {
System.out.println("Main Method with char argument Executing");
System.out.println(args); }
public static void main(double args) {
System.out.println("Main Method with Double Executing");
System.out.println(args); }
public static void main(String[] args) {
System.out.println("Original main Executing");
MethodDemo.main(12);
MethodDemo.main('c');
MethodDemo.main(12.36); } }
Static Fields and Methods
• The static keyword in java is used for memory management mainly.
• Can be applied with variables, methods, blocks and nested class.
• Belongs to the class than instance of the class.
The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class
Static variable
• If any variable declared as static, it is known static variable.
• Static variable can be used to refer the common property of all objects e.g. company name of employees, college, name of students etc.
• Gets memory only once in class area at the time of class loading.
Advantage of static variable
• It makes your program memory efficient (i.e it saves memory).

class Student{
Example: int rollno; String name; static String college =“KIET";
Student(int r,String n)
{ rollno = r; name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[])
{ Student s1 = new Student(111,"KIran");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display(); } }
Static method
• It is applying a static keyword with any method.
• Belongs to the class rather than object of a class.
• Can be invoked without the need for creating an instance of a class.
• Can access static data member and can change the value of it.
Example: Changing the common property of all objects(static field)
class Student { int rollno; String name;
static String college = “KIET";
static void change()
{ college = “KRISHNA"; }

Student(int r, String n)
{ rollno = r; name = n; }

void display ()
{System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[])
{ Student.change();
Student s1 = new Student (111,"Kiran"); Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,“Avi");
s1.display(); s2.display(); s3.display(); } }
Static block

• Used to initialize the static data member.


Example 2:
• Executed before main method at the time of class loading. class Test {
• Also, static blocks are executed before constructors static int i; int j;
static {
public class Demo { i = 10;
Example 1: static int a; System.out.println("static block called ");
static int b; }
static { Test(){
a = 10; System.out.println("Constructor called"); }
b = 20; }
}
public static void main(String args[]) { class Demo {
public static void main(String args[]) {
System.out.println("Value of a = " + a); // Although we have two objects, static block is
System.out.println("Value of b = " + b); executed only once.
Test t1 = new Test();
} Test t2 = new Test();
} } }
Output:
Output:
static block called
Value of a = 10
Constructor called
Value of b = 20
Constructor called

You might also like