Java Programming - Module 2
Java Programming - Module 2
Arrays
Static Block
Ex:
Ex:
int[] x = new int[10];
int x_len = x.length;
Array - Example
public class ArrayDemo {
public static void main(String[] args) {
int[] x; // declares an array of integers
x = new int[5]; // allocates memory for 5integers
x[0] = 11;
X[4] = 22;
System.out.println("Element at index 0: " + x[0]);
System.out.println("Element at index 1: " + x[1]);
System.out.println("Element at index 4: " + x[4]);
}
}
Output:
Element at index 0: 11
Element at index 1: 0
Element at index 4: 22
Array Bounds, Array Resizing
• Can't resize an array. Can use the same reference variable to refer
new array
• To copy array elements from one array to another array, we can use
arraycopy static method from System class
• Syntax:
public static void arraycopy(Object s,int
sIndex,Object d,int dIndex,int lngth)
• Ex:
int source[] = {1, 2, 3, 4, 5, 6};
System.arraycopy(source,0, dest,0,source.length);
Array copy
Java's API class contains a class called System, which in turn contains a method
called arraycopy(). This method is used to copy data from an array into another
array. We have to pass parameters to this method. The syntax is
public static void arraycopy(source, source-index, destination, destination-
index, length)
source is the source array from where we are going to copy elements.
destination is the array to where we are going to copy elements.
source-index tells us starting location from where copy will begin.
destination-index is about starting location in the destination array.
Array Copy - Example
The 1st dimension represent rows or number of one dimension, the 2nd
dimension represent columns or number of elements in the each one
dimensions
• The curly braces { } may also be used to initialize two dimensional
arrays
• Ex:
int[][] y = { {1,2,3}, {4,5,6}, {7,8,9} };
• You can initialize the row dimension without initializing the columns
but not vice versa
int[][] x = new int[3][];
• The length of the columns can vary for each row and initialize
number of columns in each row
• Ex1:
int [][]x = new int [2][];
x[0] = new int[5];
x 0 0 0 0 0
x[1] = new int [3]; 0 0 0
1
Two-Dimensional Arrays (Contd.).
Ex2:
int [][]x = new int [3][];
x[0] = new int[]{0,1,2,3};
x[1] = new int []{0,1,2};
x[2] = new int[]
{0,1,2,3,4};
Two-Dimensional Array - Example
1.int[] a;
a = new int[5];
2.int a[] = new int[5]
3.int a[5] = new int[5];
4.int a[] = {1,2,3};
5.int[] a = new int[]{1,2,3};
6.int[] a = new int[5]{1,2,3,4};
Array copy
Quiz (Contd.).
class Sample{
public static void main(String[] args){
int[] a = new int[5]{1,2,3};
for(int i : a)
System.out.println(i);
}
}
Classes & Objects
Classes
Variable declarations
Variable
declarations (variable describes the
attributes)
Variable may be: instance variables or static variables or final
variables
Methods
Method definitions
definitions
(methods handle the behavior)
Methods may be: instance methods or static methods
Defining a Class in java
• id void setId(int i) {
• name id = i;
•salary }
void setName(String n) {
name = n;
Instance methods
}
• setId(…) void setSalary(int s) {
salary = s;
• setName(…)
}
• setSalary(…) void getEmployeeDetails( ) {
• getEmployeeDetails() System.out.println (name + “ salary is
“ + salary);
}
}
Basic information about a class
public class Account { Instance
double balance; Variable
public void deposit( double amount ){
Parameter
balance += amount;
or
} argument
public double withdraw( double amount ){
int minimum_balance=5000;
local
if (balance >= (amount+minimum_balance)){ Variable
balance -= amount;
return amount;
}
else {
System.out.println(“Insufficient Balance”);
return 0.0;
} }
public double getbalance(){
return balance;
} }
Basic information about a class (Contd.).
else {
System.out.println(“Insufficient Balance”);
return 0.0;
}
}
public double getbalance(){
return balance;
}
}
Member variables
The previous slide contains definition of a class called Accounts.
When a number of objects are created from the same class, each instance
has its own copy of class variables.
A local variable has to be initailized before being used. It does not get
initialized with any default value.
Objects and References
Returns a reference to it
• While designing a class, the class designer can define within the
class, a special method called ‘constructor’
• Constructor is automatically invoked whenever an object of the class
is created
• Rules to define a constructor
class Sample{
private int id;
Sample(){
id = 101;
System.out.println("No Arg constructor, with ID: "+id);
}
Sample(int no){
id = no;
System.out.println("One argument constructor,with ID: "+ id);
}
}
public class ConstDemo {
public static void main(String[] args) {
Sample s1 = new Sample();
Sample s2 = new Sample(102); Output:
No Arg constructor, with ID: 101
}
One argument constructor,with ID: 102
}
this reference keyword
• Static class members are the members of a class that do not belong
to an instance of a class
• We can access static members directly by prefixing the members
with the class name
ClassName.staticVariable
ClassName.staticMethod(...)
Static variables:
• Shared among all objects of the class
• Stored within the class code, separately from instance variables that
describe an individual object
• Public static final variables are global constants
Static methods:
• Static methods can only access directly the static members and
manipulate a class’s static variables
• Static methods cannot access non-static members(instance
variables or instance methods) of the class
• Static method cant access this and super references
Static Class Members (Contd.).
• Static methods: Static methods have no “this” and “super” reference. It
is only natural that static methods cannot access instance members.
• Again, instance methods and constructors can access all variables
(both static and instance variables) and call all methods (both static and
instance methods) of the class. Static methods can access only static
variables and call only static methods. The main is static and therefore
cannot access non-static variables or call non-static methods of its
class. If you want to call non-static methods or access non-static
variables in main, you have to first create an object of the class, then
call its methods or access its fields.
• A non-static method is called for a particular object using “dot notation”:
objName.instMethod(...);
• Non-static methods can access all fields and call all methods of their
class — both static and non-static.
• Static methods are convenient because they may be called at the class
level. They are typically used to create utility classes, such as the Math
class in the Java Standard Library.
Static Class Members – Example
class StaticDemo
{
private static int a = 0;
private int b;
public void set ( int i, int j)
{
a = i; b = j;
}
public void show( )
{
System.out.println("This is static a: " + a );
System.out.println( "This is non-static b: " + b );
}
Static Class Members – Example (Contd.).
This is static a: 2
This is non-static b: 1
Discussion
Ex :
static {
System.out.println(“Within static
block”);
}
• You can invoke static methods from the static block and
they will be executed as and when the static block gets
executed
Example on the “static” block
class StaticBlockExample {
StaticBlockExample() {
System.out.println("Within constructor");
}
static {
System.out.println("Within 1st static block");
}
static void m1() {
System.out.println("Within static m1 method");
}
static {
System.out.println("Within 2nd static block");
m1();
} contd..
Example on the “static” block (Contd.).
public static void main(String [] args) {
System.out.println("Within main");
StaticBlockExample x = new
StaticBlockExample();
}
static {
System.out.println("Within 3rd static
block");
Output:
}
Within 1st static block
}
Within 2nd static block
Within static m1 method
Within 3rd static block
Within main
Within constructor
Quiz
• String s1 = “HELLO”;
• String s2 = “HELLO”;
HELLO
3e25ae
s1
3e25ae
s2
Comparing Strings using == operator
HELLO
3e25ad
s1
HELLO
3e25ae
s2
Comparing Strings using == operator
This method is similar to compareTo() method but this does not take
the case of strings into consideration.
String class Methods (Contd.).
• public String
substring(int beginIndex,
int endIndex)
Eg: "smiles".substring(1, 5) returns
"mile“
String class Methods (Contd.).
"wipra technalagies".replace('a',
'o') returns "Talearnt technologies"
String class Methods (Contd.).
– StringBuffer()//empty object
– StringBuffer(int capacity)//creates an empty object with a capacity
for storing a string
– StringBuffer(String str)//create StringBuffer object by using a
string
String Buffer Operations
public StringBuffer
delete(int start, int end)
StringBuffer Operations (Contd.).
What is capacity ?
The capacity is the amount of storage available for the
characters that have just been inserted
public int capacity()