Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Module 2

Uploaded by

Zaryab Ahmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Module 2

Uploaded by

Zaryab Ahmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

OOPDP MODULE II

 Control Statements, Methods and Arrays


 Basic selection statements, Iterative constructs,
Relative and Logical operators, break, continue,
Module II- Methods, static methods, parameter passing,
argument promotion and casting, scopes, method
Syllabus overloading. Arrays and ArrayList in Java,
Enhanced for statement, Passing arrays to
methods, Multidimensional arrays, Using command
line arguments.
JAVA CONTROL STATEMENTS
 The Java if statement is used to test the condition.
 It checks boolean condition: true or false.
 There are various types of if statement in Java.

Java If-else  if statement


 if-else statement
Statement  if-else-if ladder
 nested if statement
 The Java switch statement executes one statement
from multiple conditions.
 It is like if-else-if ladder statement.
 The switch statement works with byte, short, int, long,
enum types,
 String and some wrapper types like Byte, Short, Int, and
Java Long.

Switch  Since Java 7, you can use strings in the switch


statement.
Statement  In other words, the switch statement tests the equality of
a variable against multiple values.
public class SwitchStringExample {
public static void main(String[] args) {
String levelString="Expert";
int level=0;
switch(levelString){
//Using String Literal in Switch case
case "Beginner": level=1;
break;
case "Intermediate": level=2;
Example break;
case "Expert": level=3;
break;
default: level=0;
break;
}
System.out.println("Your Level is: "+level);
}
}
 Output

Your Level is: 3


 In programming languages, loops are used to execute
a set of instructions/functions repeatedly when some
conditions become true.
 There are three types of loops in Java.

Java Loops 1. for loop


2. while loop
3. do-while loop
 Java Break Statement
 When a break statement is encountered inside a loop,
the loop is immediately terminated and the program
control resumes at the next statement following the
loop.

Loop  Java Continue Statement


Control  The continue statement is used in loop control structure
Statements when you need to jump to the next iteration of the loop
immediately.
Static Methods in Java
When a method is static, it is really part of the class
and not part of the individual objects in the class.

It means that static methods exist even before


creating any objects.

The best example of a static method is


the main() method.

Properties of Static Function


• It can access only static members.
• It can be called without an instance.
• It is not associated with the object.
• Non-static data members cannot be accessed by the static
function.
class Demo
{
//non-static function
void display()
{
System.out.println("A non-static function is called.");
}
Example1 //static function
static void show()
{
System.out.println("The static function is called.");
}
}
public class Main
{
public static void main(String args[])
{
//creating an object of the class A
Demo obj = new Demo();
obj.display();
Demo.show();
}
}
 Output:
A non-static function is called.

The static function is called.


public class Test
{ //instance var
public int instanceVariable = 10;
public static void main(String args[])
//static method
{

Example2
Test test = new Test();
System.out.println(test.instanceVariable);
}
}

 Output
10
Method Overloading
If a class has multiple methods having
same name but different in
parameters, it is known as Method
Overloading.

There are two ways to overload the


method in java
By changing number By changing the
of arguments data type
class Adder{
static int add(int a,int b)
{return a+b;}
static int add(int a,int b,int c)
{return a+b+c;}
}
Example: class TestOverloading1{
Changing public static void main(String[] args){
no. of System.out.println(Adder.add(11,11));
arguments System.out.println(Adder.add(11,11,11));
}}
 Output:
22
33
class Adder{
static int add(int a, int b)
{return a+b;}
static double add(double a, double b)
{return a+b;}
}
Example: class TestOverloading2{

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

Data Type System.out.println(Adder.add(11,11));


System.out.println(Adder.add(12.3,12.6));
}}
 Output:
22
24.9
Parameter Passing Techniques in Java
 Important methods of Parameter Passing

 Pass by Value
 Any modifications to the formal parameter variable inside the called
function or method affect only the separate storage location and will not
be reflected in the actual parameter in the calling environment.

 Pass by reference
 Any changes to the formal parameter are reflected in the actual
parameter in the calling environment as formal parameter receives a
reference (or address) to the actual data.
class CallByValue {

// Function to change the value


// of the parameters
public void Example(int x, int y)

Pass by
{
x++;
Value y++;
}
}
public class Main {
public static void main(String[] args)
{

int a = 10;
int b = 20;
CallByValue object = new CallByValue();

System.out.println("Value of a: " + a + " & b: " + b);

object.Example(a, b);

System.out.println("Value of a: "+ a + " & b: " + b);


}
}
 Output:
Value of a: 10 & b: 20
Value of a: 10 & b: 20
class CallByReference {
int a, b;
CallByReference(int x, int y)
{
a = x;
b = y;
}
Call by void ChangeValue(CallByReference obj)

Reference {
obj.a += 10;
obj.b += 20;
}
}
public class Main {

public static void main(String[] args)


{
CallByReference object = new CallByReference(10, 20);

System.out.println("Value of a: " +object.a + " & b: "+


object.b);

object.ChangeValue(object);

System.out.println("Value of a: "+ object.a + " & b: "+


object.b);
}
}
 Output
Value of a: 10 & b: 20
Value of a: 20 & b: 40
Argument Promotion and Casting
 An important feature of method calls in java is argument
promotion.

 Converting an argument's value to the type that the


method expects to receive in its corresponding
parameter.

Argument
 For example, a program can call Math method sqrt with
promotion an integer argument even though the method expects
to receive a double argument (but, as we will soon see,
not vice versa).

 Attempting these conversions may lead to compilation


errors if Java's promotion rules are not satisfied.
Promotions
allowed for
primitive types
 In cases where information may be lost due to
conversion, the Java compiler requires the programmer
to use a cast operator (introduced in ) to explicitly force
the conversion to occur ,otherwise a compilation error
occurs.
 This enables the programmer to "take control" from the
Casting compiler.
 The programmer essentially says, "I know this conversion
might cause loss of information, but for my purposes
here, that's fine."
public class Main
{
void display(double a)
{
System.out.println(a);
}
void show(int b)
{
System.out.println(b);
Example }
public static void main(String[] args) {
Main ob=new Main();
ob.display(4); //promotion
ob.show((int)5.0); //casting

}
}
 Output
4.0
5
Scope of Variables In Java
 Scope of a variable is the part of the program where the
variable is accessible.

 ava programs are organized in the form of classes. Every


class is part of some package.

 Java scope rules can be covered under following


categories.

 Class Level
 Method Level
 Block Level
 We can declare class variables anywhere in class, but
outside methods.

 Access specified of member variables doesn’t affect


scope of them within a class.

 The scope of Member variables can be defined using


Class Level the available access modifiers
Scope
 Public
 Private
 Protected
 Default
Understanding
Java Access
Modifiers
 Variables declared inside a method have method level
scope and can’t be accessed outside the method.

 public class Test


 {
 void method1()
Method  {
Level Scope  // Local variable (Method level scope)
 int x;
 }
 }
 A variable declared inside pair of brackets “{” and “}” in
a method has scope within the brackets only.
Block Scope
public class Main
{
public static void main(String[] args) {
System.out.println("Start");
{
int x=10;
System.out.println(x);

Example
}
//System.out.println(x);generate error if removes
comment
System.out.println("End");
}
}
 Output
Start
10
End
Arrays and Array List in Java
 An array is a group of like-typed variables that are
referred to by a common name.
 Arrays in Java work differently than they do in C/C++.

 Following are some important points about Java arrays.


 Since arrays are objects in Java, we can find their length
using the object property length.

Array  A Java array variable can also be declared like other


variables with [] after the data type.
 The variables in the array are ordered and each have an
index beginning from 0.
 Java array can be also be used as a static field, a local
variable or a method parameter.
 The size of an array must be specified by an int or short
value and not long.
 An array declaration has two components: the type
and the name.
 int intArray[];
 or int[] intArray;
Declaration  Although the first declaration above establishes the fact
that intArray is an array variable, no actual array exists.
 It merely tells the compiler that this variable (intArray)
will hold an array of the integer type.
 When an array is declared, only a reference of array is
created.
 To actually give memory to array, you create an array
like this:
 The general form of new as it applies to one-dimensional
arrays appears as follows:
 var-name = new type [size];

Instantiation  int intArray[]; //declaring array


 intArray = new int[20]; // allocating memory to
array

 Or

 int[] intArray = new int[20]; // combining both


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

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


String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(intArray[2]);
System.out.println(cars[2]);
Example
}
}

Output
3
Ford
Multidimensional  A multidimensional array is an array of arrays.
Arrays  Each element of a multidimensional array is an array
itself.
 For example,
 int[][] a = new int[3][4];
int[][] a = new int[3][4];
Memory Layout view
 Here is how we can initialize a 2-dimensional array in
Java.
 int[][] a = {
 {1, 2, 3},
 {4, 5, 6, 9},
 {7},

Initializing  };

2D Array  As we can see, each element of the multidimensional


array is an array itself.
 And also, unlike C/C++, each row of the
multidimensional array in Java can be of different
lengths.
 class MultidimensionalArray {
 public static void main(String[] args) {

 // create a 2d array
 int[][] a = {
 {1, 2, 3},
 {4, 5, 6, 9},
 {7},
 };

Example

 // calculate the length of each row
 System.out.println("Length of row 1: " + a[0].length);
 System.out.println("Length of row 2: " + a[1].length);
 System.out.println("Length of row 3: " + a[2].length);
 }
 }
 Output:
 Length of row 1: 3
 Length of row 2: 4
 Length of row 3: 1
public class Main
{
public static void main(String[] args) {

int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);

}
Array and }

For Loop Output


33
3
4
5
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
2D Array }
and For }

Loop }
}
 Output
1
2
3
4
5
6
7
import java.util.Scanner;
public class ArrayInputExample1
{
public static void main(String[] args)
{
int n;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
n=sc.nextInt();
int[] array = new int[n];
System.out.println("Enter the elements of the array: ");

Input from for(int i=0; i<n; i++)


{

Keyboard array[i]=sc.nextInt();
}
System.out.println("Array elements are: ");
for (int i=0; i<n; i++)
{
System.out.println(array[i]);
}
}
}
 Output
Enter the number of elements you want to store:
5
Enter the elements of the array:
12345
Array elements are:
1
2
3
4
5
 You can pass arrays to a method just like normal
variables.
 When we pass an array to a method as an argument,
actually the address of the array in the memory is
Passing passed (reference).
Arrays to  Therefore, any changes to this array in the method will
affect the array.
Methods
import java.util.Scanner;
class Example{
void Change(int[] a,int size)
{
for(int i=0;i<size;i++)
Example {
a[i]=a[i]+10;
}
}
}
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++)
myArray[i] = sc.nextInt();
System.out.println("Array before function call");
for(int i=0; i<size; i++)
System.out.println(myArray[i]);
Example ob=new Example();
ob.Change(myArray,size);
System.out.println("Array after function call");
for(int i=0; i<size; i++)
System.out.println(myArray[i]);
}
}
Output

Enter the size of the array that is to be created::

5
Enter the elements of the array ::
12345
Array before function call
1
2
3
4
5
Array after function call
11
12
13
14
15
public class Main{
public static void main(String[] args) {
int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
acceptIt(a); // pass it to the method
}

public static void acceptIt(int[][] a) {


System.out.println("Elements are :");

Passing 2D
for (int i = 0; i< a.length; i++) {
Array to for (int j = 0; j < a[i].length; j++) {
Method System.out.print(a[i][j] + "\t");
}
System.out.println("");
}
}
}
Output

Elements are :
1 2 3
4 5 6
7 8 9
 ArrayList is a part of collection framework and is present
in java.util package.
 Java ArrayList class uses a dynamic array for storing the
elements.

Array List  It is like an array, but there is no size limit.


 We can add or remove elements anytime.
 So, it is much more flexible than the traditional array.
 The important points about Java ArrayList class are:
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array
works at the index basis.
 In ArrayList, manipulation is little bit slower than the
LinkedList in Java because a lot of shifting needs to
occur if any element is removed from the array list.
Constructor Description
ArrayList() It is used to build an empty
array list.

ArrayList(Collection<? It is used to build an array


extends E> c) list that is initialized with the
Constructors elements of the collection
of ArrayList c.

ArrayList(int capacity) It is used to build an array


list that has the specified
initial capacity.
 import java.util.ArrayList;
Creating  ArrayList<String> cars = new ArrayList<String>();

ArrayList
 import java.util.ArrayList;

 public class Main {
 public static void main(String[] args) {
 ArrayList<String> cars = new ArrayList<String>();
 cars.add("Volvo");
 cars.add("BMW");
 cars.add("Ford");
Adding  cars.add("Mazda");
elements  System.out.println(cars);
 }
 }

 Output
 [Volvo, BMW, Ford, Mazda]
 Access an Item
 To access an element in the ArrayList, use
the get() method and refer to the index number:
 Example
 cars.get(0);

 Change an Item
Other  To modify an element, use the set() method and refer
Operations to the index number:
 Example
 cars.set(0, "Opel");
 Remove an Item
 To remove an element, use the remove() method and
refer to the index number:
 Example
 cars.remove(0);

 To remove all the elements in the ArrayList, use


the clear() method:
 Example
 cars.clear();
 ArrayList Size
 To find out how many elements an ArrayList have, use
the size method:
 Example
 cars.size();
 Elements in an ArrayList are actually objects.
 In the examples above, we created elements (objects)
of type "String".
 Remember that a String in Java is an object (not a
primitive type).
Other  To use other types, such as int, you must specify an
Types equivalent wrapper class: Integer.
 For other primitive types, use: Boolean for
boolean, Character for char, Double for double, etc:
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
Example myNumbers.add(25);
System.out.println(myNumbers);
}
}

 Output
[10, 15, 20, 25]
 public class Main {
 public static void main(String[] args) {
 ArrayList<String> cars = new ArrayList<String>();
 cars.add("Volvo");
 cars.add("BMW");
 cars.add("Ford");
 cars.add("Mazda");
 for (int i = 0; i < cars.size(); i++) {
 System.out.println(cars.get(i));
 }
Loop  }
Through an  }

ArrayList

 Output
Volvo
BMW
Ford
Mazda
 In Java, the for-each loop is used to iterate through
elements of arrays and collections (like ArrayList).
 It is also known as the enhanced for loop.
 The advantage of the for-each loop is that it eliminates
the possibility of bugs and makes the code more
readable.
 It is known as the for-each loop because it traverses
Enhanced each element one by one.
for  The drawback of the enhanced for loop is that it cannot
traverse the elements in reverse order.
Statement  Here, you do not have the option to skip any element
because it does not work on an index basis.
 The syntax of Java for-each loop consists of data_type
with the variable followed by a colon (:), then array or
collection.

for(data_type variable : array | collection)


{
//body of for-each loop
}
//An example of Java for-each loop
class Example1{
public static void main(String args[]){
int arr[]={12,13,14,44};
for(int i:arr){
Example1 System.out.println(i);
}
}
}
 Output:
12
13
14
44
Class Example2{
public static void main(String args[]){
int arr[]={12,13,14,44};
int total=0;
for(int i:arr){
total=total+i;
Example2 }
System.out.println("Total: "+total);
}
}
 Output:
Total: 83
import java.util.*;
class Example3{
public static void main(String args[]){
//Creating a list of elements
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
Example3 //traversing the list of elements using for-each loop
for(String s:list){
System.out.println(s);
}

}
}
 Output:
vimal
sonoo
ratan
Commandline Arguments in Java
 The java command-line argument is an argument i.e.
passed at the time of running the java program.
 The arguments passed from the console can be
Java received in the java program and it can be used as an
input.
Command
Line
arguments
class Example{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
Example1 }
}
 Compile by > javac Example.java
 Run by > java Example hai

 Output:
Your first argument is: hai
class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);
Example2
}
}
 compile by > javac A.java
 run by > java A sonoo jaiswal 1 3 abc

 Output:
sonoo
jaiswal
1
3
abc
class Main {
public static void main(String[] args) {

for(String str: args) {


// convert into integer type
int argument = Integer.parseInt(str);
Numeric
System.out.println(argument);
Command-
}
Line
Arguments }
}
 // compile the code
 javac Main.java

 // run the code
 java Main 11 23

 Output
11
23
Java Packages
 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.
Java  There are many built-in packages such as java, lang,

Package awt, javax, swing, net, io, util, sql etc.


 Advantage of Java Package
 Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
 Java package provides access protection.
 Java package removes naming collision.
Part of Java Package Hierarchy
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
User }

defined }
 Output
Package
Welcome to package
//save by A.java
package pack;
public class A{
Importing public void msg(){System.out.println("Hello");}

Package in }

Java
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

 Output
Hello
Sample Questions

 State the significance of access modifiers


in Java
 Write a program to find the first repeating
element in an array of
integers? Input: input [] = {10, 5, 3, 4, 3, 5,
6} Output: 5 [5 is the first element that
repeats]
 Explain the concept of compile time
polymorphism in java using an example
 Illustrate the significance of ArrayList in java
 Explain the significance of static methods
in Java using example

You might also like