Java Programming
Er. Mohit Paul
Java For Each Loop
Java For-Each Loop (Enhanced For Loop)
•Introduced in: J2SE 5.0
•Purpose: Simplifies traversal of arrays and collections.
•Advantages:
•Easier and more readable than traditional for loop.
•Reduces chances of bugs (no index handling).
•Limitations:
•Cannot traverse in reverse order.
•Cannot skip elements or access specific indexes.
•Cannot traverse only odd/even elements.
•Recommendation:
•Best used for simple element-by-element traversal of arrays and collections.
for(data_type variable : array | collection)
{
//body of for-each loop
}
class Main
{
public static void main(String args[])
{
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each
loop
for(int i:arr){
System.out.println(i);
}
}
}
Java Methods
Types of Methods
There are two types of methods in Java:
•Predefined Method
•User-defined Method
Access Specifier
 Access Specifier: Access specifier or modifier is the access type of the
method. It specifies the visibility of the method. Java provides four types of
access specifiers:
• public: The method is accessible to all classes when we use the public
specifier in our application.
• private: When we use a private access specifier, the method is accessible only
in the classes in which it is defined.
• protected: When we use a protected access specifier, the method is
accessible within the same package or subclasses in a different package.
• default: When we do not use any access specifier in the method declaration,
Java uses the default access specifier by default. It is visible only from the
same package.
Java Constructors
Definition:
A constructor is a special block of code (like a method) that is called automatically when an object is
created using the `new` keyword.
It is used to initialize objects.
Object Creation:
* Memory for the object is allocated when the constructor is called.
* If no constructor is defined, the **Java compiler provides a default constructor automatically.
Why Called Constructor:
* It “constructs” values (initializes data) at the time of object creation.
Need of Constructor:
* Not mandatory to define one manually.
* Java creates a default constructor if none exists.
Rules for Creating a Constructor
1. Constructor name must match the class name.
2. It has no explicit return type (not even `void`).
3. It cannot be abstract, static, final, or synchronized.
4. Access modifiers (`public`, `private`, `protected`, or default) can be used to
control object creation.
Types of Constructors
1. Default Constructor (No-arg Constructor):
* Takes no arguments.
* Automatically provided if no constructor is defined.
2. Parameterized Constructor:
* Takes parameters to initialize objects with specific values.
Difference between Constructor and
Method
Java Constructor Java Method
A constructor is used to initialize the
state of an object.
A method is used to expose the
behavior of an object.
A constructor must not have a return
type.
A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default
constructor if we do not have any
constructor in a class.
The method is not provided by the
compiler in any case.
The constructor's name must be
same as the class name.
The method name may or may not be
same as the class name.
Java Default Constructor
//Java Program to create and call a default
constructor
class Bca
{
//creating a default constructor
Bca()
{
System.out.println(“ Bca Constructor created");
}
}
public class Main
{
//main method
public static void main(String args[])
{
//calling a default constructor
Bca b=new Bca();
}
}
Parameterized Constructor
//Main class to create objects and class
methods
public class Main
{
public static void main(String args[])
{
//creating objects and passing values
Student s1 = new Student(1,“Rohan");
//calling method to display the values of
object
s1.display();
}
}
class Student
{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}
}
Java static keyword
 The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.
 The static can be:
 Variable (also known as a class variable), Method (also known as a class
method), Block, Nested class
Java Static Variable
 If we declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
• The static variable gets memory only once in the class area at the time of
class loading.
• Static variables in Java are also initialized to default values if not explicitly
initialized by the programmer. They can be accessed directly using the class
name without needing to create an instance of the class.
• Static variables are shared among all instances of the class, meaning if the
value of a static variable is changed in one instance, it will reflect the change
in all other instances as well.
class Student{
int rollno;
//instance variable
String name;
static String college =“SHUATS";
//static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display the values
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Main class to show the values of objects
public class Main
{
public static void main(String args[])
{
Student s1 = new Student(11,“Aman");
Student s2 = new Student(22,“Rohan");
//we can change the college of all objects by the
single line of code
//Student. college=“XYZ";
s1.display();
s2.display();
}
}
Java Static Method
 If we apply a static keyword with any method, it is known as a static method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a
class.
• A static method can access static data members and can change their value of
it.
//Java Program to demonstrate the use of a static
method.
class Student{
int rollno;
String name;
static String college = “XYZ";
//static method to change the value of static
variable
static void change(){
college = “SHUATS";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);}
}
//Main class to create and display the values of
object
public class Main{
public static void main(String args[]){
Student.change();
//calling change method
//creating objects
Student s1 = new Student(1,"Kamran");
Student s2 = new Student(2,"Amar");
Student s3 = new Student(3,“Rohan");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Java Static Block
• It is used to initialize the static data member.
• It is executed before the main() method at the time of class loading.
//Java program to illustrate the use of static block
public class Main
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("main() method is invoked");
}
} static block is invoked
main() method is invoked
Java Inner class
 Java inner class or nested class is a class that is declared inside the class or
interface.
 We use inner classes to logically group classes and interfaces in one place to
be more readable and maintainable.
 Additionally, it can access all the members of the outer class, including
private data members and methods. Nested classes represent a particular
type of relationship that is it can access all the members (data members and
methods) of the outer class, including private.
 Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
 Code Optimization: It requires less code to write.
Java Static nested class
 A static class is a class that is created inside a class, is called a static nested
class in Java. It cannot access non-static data members and methods. It
can be accessed by outer class name.
 It can access static data members of the outer class, including private.
 The static nested class cannot access non-static (instance) data members
or
class TestOuter
{
static int data=20;
static class Inner
{
void msg()
{
System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestOuter.Inner obj=new TestOuter.Inner();
obj.msg();
}
}

Java Programming Constructors destructor

  • 1.
  • 2.
    Java For EachLoop Java For-Each Loop (Enhanced For Loop) •Introduced in: J2SE 5.0 •Purpose: Simplifies traversal of arrays and collections. •Advantages: •Easier and more readable than traditional for loop. •Reduces chances of bugs (no index handling). •Limitations: •Cannot traverse in reverse order. •Cannot skip elements or access specific indexes. •Cannot traverse only odd/even elements. •Recommendation: •Best used for simple element-by-element traversal of arrays and collections. for(data_type variable : array | collection) { //body of for-each loop }
  • 3.
    class Main { public staticvoid main(String args[]) { //declaring an array int arr[]={12,13,14,44}; //traversing the array with for-each loop for(int i:arr){ System.out.println(i); } } }
  • 4.
    Java Methods Types ofMethods There are two types of methods in Java: •Predefined Method •User-defined Method
  • 5.
    Access Specifier  AccessSpecifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifiers: • public: The method is accessible to all classes when we use the public specifier in our application. • private: When we use a private access specifier, the method is accessible only in the classes in which it is defined. • protected: When we use a protected access specifier, the method is accessible within the same package or subclasses in a different package. • default: When we do not use any access specifier in the method declaration, Java uses the default access specifier by default. It is visible only from the same package.
  • 6.
    Java Constructors Definition: A constructoris a special block of code (like a method) that is called automatically when an object is created using the `new` keyword. It is used to initialize objects. Object Creation: * Memory for the object is allocated when the constructor is called. * If no constructor is defined, the **Java compiler provides a default constructor automatically. Why Called Constructor: * It “constructs” values (initializes data) at the time of object creation. Need of Constructor: * Not mandatory to define one manually. * Java creates a default constructor if none exists.
  • 7.
    Rules for Creatinga Constructor 1. Constructor name must match the class name. 2. It has no explicit return type (not even `void`). 3. It cannot be abstract, static, final, or synchronized. 4. Access modifiers (`public`, `private`, `protected`, or default) can be used to control object creation. Types of Constructors 1. Default Constructor (No-arg Constructor): * Takes no arguments. * Automatically provided if no constructor is defined. 2. Parameterized Constructor: * Takes parameters to initialize objects with specific values.
  • 8.
    Difference between Constructorand Method Java Constructor Java Method A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object. A constructor must not have a return type. A method must have a return type. The constructor is invoked implicitly. The method is invoked explicitly. The Java compiler provides a default constructor if we do not have any constructor in a class. The method is not provided by the compiler in any case. The constructor's name must be same as the class name. The method name may or may not be same as the class name.
  • 9.
    Java Default Constructor //JavaProgram to create and call a default constructor class Bca { //creating a default constructor Bca() { System.out.println(“ Bca Constructor created"); } } public class Main { //main method public static void main(String args[]) { //calling a default constructor Bca b=new Bca(); } }
  • 10.
    Parameterized Constructor //Main classto create objects and class methods public class Main { public static void main(String args[]) { //creating objects and passing values Student s1 = new Student(1,“Rohan"); //calling method to display the values of object s1.display(); } } class Student { int id; String name; //creating a parameterized constructor Student(int i,String n) { id = i; name = n; } //method to display the values void display() { System.out.println(id+" "+name); } }
  • 11.
    Java static keyword The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.  The static can be:  Variable (also known as a class variable), Method (also known as a class method), Block, Nested class
  • 12.
    Java Static Variable If we declare any variable as static, it is known as a static variable. • The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. • The static variable gets memory only once in the class area at the time of class loading. • Static variables in Java are also initialized to default values if not explicitly initialized by the programmer. They can be accessed directly using the class name without needing to create an instance of the class. • Static variables are shared among all instances of the class, meaning if the value of a static variable is changed in one instance, it will reflect the change in all other instances as well.
  • 13.
    class Student{ int rollno; //instancevariable String name; static String college =“SHUATS"; //static variable //constructor Student(int r, String n) { rollno = r; name = n; } //method to display the values void display () { System.out.println(rollno+" "+name+" "+college); } } //Main class to show the values of objects public class Main { public static void main(String args[]) { Student s1 = new Student(11,“Aman"); Student s2 = new Student(22,“Rohan"); //we can change the college of all objects by the single line of code //Student. college=“XYZ"; s1.display(); s2.display(); } }
  • 14.
    Java Static Method If we apply a static keyword with any method, it is known as a static method. • A static method belongs to the class rather than the object of a class. • A static method can be invoked without the need for creating an instance of a class. • A static method can access static data members and can change their value of it.
  • 15.
    //Java Program todemonstrate the use of a static method. class Student{ int rollno; String name; static String college = “XYZ"; //static method to change the value of static variable static void change(){ college = “SHUATS"; } //constructor to initialize the variable Student(int r, String n){ rollno = r; name = n; } //method to display values void display() { System.out.println(rollno+" "+name+" "+college);} } //Main class to create and display the values of object public class Main{ public static void main(String args[]){ Student.change(); //calling change method //creating objects Student s1 = new Student(1,"Kamran"); Student s2 = new Student(2,"Amar"); Student s3 = new Student(3,“Rohan"); //calling display method s1.display(); s2.display(); s3.display(); } }
  • 16.
    Java Static Block •It is used to initialize the static data member. • It is executed before the main() method at the time of class loading. //Java program to illustrate the use of static block public class Main { static { System.out.println("static block is invoked"); } public static void main(String args[]) { System.out.println("main() method is invoked"); } } static block is invoked main() method is invoked
  • 17.
    Java Inner class Java inner class or nested class is a class that is declared inside the class or interface.  We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.  Additionally, it can access all the members of the outer class, including private data members and methods. Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.  Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.  Code Optimization: It requires less code to write.
  • 18.
    Java Static nestedclass  A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name.  It can access static data members of the outer class, including private.  The static nested class cannot access non-static (instance) data members or
  • 19.
    class TestOuter { static intdata=20; static class Inner { void msg() { System.out.println("data is "+data);} } public static void main(String args[]) { TestOuter.Inner obj=new TestOuter.Inner(); obj.msg(); } }