0% found this document useful (0 votes)
3 views39 pages

Java Unit1

The document provides an introduction to Java programming, covering its definition, applications, and types of Java applications such as standalone, web, enterprise, and mobile applications. It also compares Java with C++, discusses variables, data types, control statements, loops, and object-oriented programming concepts like inheritance and polymorphism. Additionally, it includes examples of Java syntax and how to compile and run Java programs.

Uploaded by

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

Java Unit1

The document provides an introduction to Java programming, covering its definition, applications, and types of Java applications such as standalone, web, enterprise, and mobile applications. It also compares Java with C++, discusses variables, data types, control statements, loops, and object-oriented programming concepts like inheritance and polymorphism. Additionally, it includes examples of Java syntax and how to compile and run Java programs.

Uploaded by

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

Java Programming and Dynamic Webpage Design- (502)

Unit 1

Java

Java Tutorial or Core Java Tutorial or Java Programming Tutorial is a widely


used robust technology. Let's start learning of java from basic questions like
what is java tutorial, core java, where it is used, what type of applications
are created in java and why use java.

Java is a programming language and a platform.

Java is a high level, robust, secured and object-oriented programming


language.

Platform: Any hardware or software environment in which a program runs,


is known as a platform. Since Java has its own runtime environment (JRE)
and API, it is called platform.

Java Example

Let's have a quick look at java programming example. A detailed description


of hello java example is given in next page.

class Simple

public static void main(String args[]){

System.out.println("Hello Java");

1
}

Where java is used?

According to Sun, 3 billion devices run java. There are many devices where
java is currently used. Some of them are as follows:

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

It is also known as desktop application or window-based application. An


application that we need to install on every machine such as 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 dynamic page, is
called web application. Currently, servlet, jsp, struts, jsf etc. technologies
are used for creating web applications in java.

2
3) Enterprise Application

An application that is distributed in nature, such as banking applications etc.


It has the advantage of high level security, load balancing and clustering. In
java, EJB is used for creating enterprise applications.

4) Mobile Application

An application that is created for mobile devices. Currently Android and Java
ME are used for creating mobile applications.

There are many differences and similarities between C++ programming


language and Java. A list of top differences between C++ and Java are given
below:

3
Comparison Index C++ Java

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for Java is mainly used for application
system programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.

Goto C++ supports goto Java doesn't support goto statement.


statement.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by interfaces in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You Java supports pointer internally. But
can write pointer program in you can't write the pointer program in
C++. java. It means java has restricted
pointer support in java.

Compiler and C++ uses compiler only. Java uses compiler and interpreter
Interpreter both.

Call by Value and C++ supports both call by Java supports call by value only. There
Call by reference value and call by reference. is no call by reference in java.

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies
on third-party libraries for
thread support.

Documentation C++ doesn't support Java supports documentation comment


comment documentation comment. (/** ... */) to create documentation for
java source code.

Virtual Keyword C++ supports virtual Java has no virtual keyword. We can
keyword so that we can override all non-static methods by

4
decide whether or not default. In other words, non-static
override a function. methods are virtual by default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for
the negative numbers. For positive
numbers, it works same like >>
operator.

Inheritance Tree C++ creates a new Java uses single inheritance tree
inheritance tree always. always because all classes are the child
of Object class in java. Object class is
the root of inheritance tree in java.

Requirement for Hello Java Example


For executing any java program, you need to

 install the JDK if you don't have installed it,


 set path of the jdk/bin directory
 create the java program
 compile and run the java program

save this file as Simple.java

To compile: javac Simple.java


To execute: java Simple

Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

 class keyword is used to declare a class in java.


 public keyword is an access modifier which represents visibility, it
means it is visible to all.

5
 static is a keyword, if we declare any method as static, it is known as
static method. The core advantage of static method is that there is no
need to create object to invoke the static method. The main method is
executed by the JVM, so it doesn't require to create object to invoke
the main method. So it saves memory.
 void is the return type of the method, it means it doesn't return any
value.
 main represents startup of the program.
 String[] args is used for command line argument. We will learn it
later.
 System.out.println() is used print statement. We will learn about the
internal working of System.out.println statement later.

To write the simple program, open notepad by start menu -> All
Programs -> Accessories -> notepad and write simple program as
displayed below:

6
As displayed in the above diagram, write the simple program of java in
notepad and saved it as Simple.java. To compile and run this program, you
need to open command prompt by start menu -> All Programs ->
Accessories -> command prompt.

7
To compile and run the above program, go to your current directory first;
my current directory is c:\new . Write here:
To compile: javac Simple.java
To execute: java Simple

Internal Details of Hello Java Program

In the previous page, we have learned about the first program, how to
compile and how to run the first java program. Here, we are going to learn,
what happens while compiling and running the java program. Moreover, we
will see some question based on the first program.

8
What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact
with OS) and converts the java code into bytecode.

Variable and Datatype in Java

In this page, we will learn about the variable and java data types. Variable
is a name of memory location. There are three types of variables: local,
instance and static. There are two types of datatypes in java, primitive
and non-primitive.

Variable

Variable is name of reserved area allocated in memory.

9
int data=50;//Here data is variable

Types of Variable
There are three types of variables in java

 local variable
 instance variable
 static variable

Local Variable
A variable that is declared inside the method is called local variable.

Instance Variable
A variable that is declared inside the class but outside the method is called
instance variable . It is not declared as static.

Static variable
A variable that is declared as static is called static variable. It cannot be

10
local.

Example to understand the types of variables

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

Data Types in Java


In java, there are two types of data types

 primitive data types


 non-primitive data types

11
Operators in java

Operator in java is a symbol that is used to perform operations. There are


many types of operators in java such as unary operator, arithmetic operator,
relational operator, shift operator, bitwise operator, ternary operator and
assignment operator.

Operators Precedence

Postfix expr++ expr--

Unary ++expr --expr +expr -expr ~ !

multiplicative * / %

additive + -

Shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ? :

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java If-else Statement

12
The Java if statement is used to test the condition. It returns true or false.
There are various types of if statement in java.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

Java IF Statement

The if statement tests the condition. It executes the if statement if condition


is true.

public class IfExample


{
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}

Java IF-else Statement

The if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block.

Syntax:

if(condition){
//code if condition is true
}else{
//code if condition is false
}

Example:

public class IfElseExample {


public static void main(String[] args) {
int number=13;
if(number%2==0){

13
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}

Java IF-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple


statements.

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Example:

public class IfElseIfExample {


public static void main(String[] args) {
int marks=65;

if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}

14
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}

Java Switch Statement

The Java switch statement is executes one statement from multiple


conditions. It is like if-else-if ladder statement.

Syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Example:

public class SwitchExample {


public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;

15
default:System.out.println("Not in 10, 20 or 30");
}
}
}

Output:

20

Java For Loop

The Java for loop is used to iterate a part of the program several times. If
the number of iteration is fixed, it is recommended to use for loop.

There are three types of for loop in java.

o Simple For Loop


o For-each or Enhanced For Loop
o Labeled For Loop

Java Simple For Loop

The simple for loop is same as C/C++. We can initialize variable, check
condition and increment/decrement value.

Syntax:

1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }

Example:

16
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}

Java While Loop

The Java while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed, it is recommended to use while loop.

Syntax:

while(condition){
//code to be executed
}

Example:

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}

Java do-while Loop

The Java do-while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed and you must have to execute
the loop at least once, it is recommended to use while loop.
17
It is executed at least once because condition is checked after loop body.

Syntax:

do{
//code to be executed
}while(condition);

Example:

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}

Java Break Statement

The Java break is used to break loop or switch statement. It breaks the
current flow of the program at specified condition. In case of inner loop, it
breaks only inner loop.

Syntax:

jump-statement;
break;

Example:
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);

18
}
}
}

Java Continue Statement

The Java continue statement is used to continue loop. It continues the


current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.

Syntax:

jump-statement;
continue;

Java Continue Statement Example

Example:

public class ContinueExample {


public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
System.out.println(i);
}
}
}

Java OOPs Concepts

In this page, we will learn about basics of OOPs. Object Oriented


Programming is a paradigm that provides many concepts such as
inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language.


The programming paradigm where everything is represented as an object, is
known as truly object-oriented programming language.

19
Smalltalk is considered as the first truly object-oriented programming
language.

OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc.Object-
Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and
maintenance by providing some concepts:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object

Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of


parent object i.e. known as inheritance. It provides code reusability. It is
used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as


polymorphism. For example: to convense the customer differently, to draw
something e.g. shape or rectangle etc.

20
In java, we use method overloading and method overriding to achieve
polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog
barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as


abstraction. For example: phone call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is
known as encapsulation. For example: capsule, it is wrapped with
different medicines.

A java class is the example of encapsulation. Java bean is the fully


encapsulated class because all the data members are private here.

Advantage of OOPs over Procedure-oriented programming language


1)OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.

2)OOPs provides data hiding whereas in Procedure-oriented prgramming


language a global data can be accessed from anywhere.

3)OOPs provides ability to simulate real-world event much more


effectively. We can provide the solution of real word problem if we are
using the Object-Oriented Programming language.

21
Object and Class in Java

we will learn about java objects and classes. In object-oriented


programming technique, we design a program using objects and classes.

Object is the physical as well as logical entity whereas class is the logical
entity only.

Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tengible and
intengible). The example of integible object is banking system.

An object has three characteristics:

 state: represents data (value) of an object.


 behavior: represents the behavior (functionality) of an object such as
deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. But,it is used
internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc.
known as its state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from

22
which objects are created. So object is the instance(result) of a class.

Class in Java

A class is a group of objects that has common properties. It is a template


or blueprint from which objects are created.

A class in java can contain:

 data member
 method
 constructor
 block
 class and interface

Syntax to declare a class:

class <class_name>
{
data member;
method;
}

Example of Object and Class

In this example, we have created a Student class that have two data
members id and name. We are creating the object of the Student class by
new keyword and printing the objects value.

class Student1
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[])


{
Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}

23
}

Instance variable in Java


A variable that is created inside the class but outside the method, is
known as instance variable.Instance variable doesn't get memory at
compile time.It gets memory at runtime when object(instance) is
created.That is why, it is known as instance variable.

Method in Java
In java, a method is like function i.e. used to expose behaviour of an
object.

Advantage of Method
 Code Reusability
 Code Optimization

new keyword
The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of students


In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord method
on it. Here, we are displaying the state (data) of the objects by invoking
the displayInformation method.

class Student2{
int rollno;
String name;

void insertRecord(int r, String n){ //method


rollno=r;
name=n;
}

24
void displayInformation(){System.out.println(rollno+" "+name);}//method

public static void main(String args[]){


Student2 s1=new Student2();
Student2 s2=new Student2();

s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");

s1.displayInformation();
s2.displayInformation();

}
}

111 Karan
222 Aryan

class Rectangle{
int length;
int width;

void insert(int l,int w){


length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[]){


Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}

25
There are many ways to create an object in java. They are:

By new keyword

By newInstance() method

By clone() method

By factory method etc.

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of


primitives.
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

Let's see the example:


class Rectangle{
int length;
int width;

void insert(int l,int w){


length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[]){


Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}

26
Method Overloading

If a class have multiple methods by same name but different 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 behaviour
of the method because its name differs. So, we perform method overloading
to figure out the program quickly.

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

Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method
performs addition of two numbers and second sum method performs

27
addition of three numbers.

1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
Output:30
40

Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in


data type. The first sum method receives two integer arguments and second
sum method receives two double arguments.

class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){


Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}

Output:21.0
40

Why Method Overloaing is not possible by changing the return type of method

28
In java, method overloading is not possible by changing the return type of
the method because there may occur ambiguity. Let's see how ambiguity
may occur:

class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}

public static void main(String args[]){


Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error

}
}

int result=obj.sum(20,20); //Here how can java determine which sum()


method should be called

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a
class by method overloading. Let's see the simple example:

class Overloading1{
public static void main(int a){
System.out.println(a);
}

public static void main(String args[]){


System.out.println("main() method invoked");
main(10);
}
}

Output: main() method invoked


10

29
Constructor

Constructor in java is a special type of method that is used to initialize the


object.

Java constructor is invoked at the time of object creation. It constructs the


values i.e. provides data for the object that is why it is known as
constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Default Constructor
A constructor that have no parameter is known as default constructor.

30
Syntax of default constructor:
1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class.
It will be invoked at the time of object creation.

class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

Output:

Bike is created

Default constructor provides the default values to the object like 0, null etc.
depending on the type.

Example of default constructor that displays the default values

class Student3{
int id;
String name;

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

31
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Test it Now

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so


compiler provides you a default constructor.Here 0 and null values are
provided by default constructor.

parameterized constructor

A constructor that have parameters is known as parameterized


constructor.

Parameterized constructor is used to provide different values to the


distinct objects.

Example of parameterized constructor

In this example, we have created the constructor of Student class that


have two parameters. We can have any number of parameters in the
constructor.
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

32
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

Constructor Overloading
Constructor overloading is a technique in Java in which a class can have
any number of constructors that differ in parameter lists.The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type.

Example of Constructor Overloading


class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

33
Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method

There are many differences between constructors and methods. They are
given below.

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if Method is not provided by compiler
you don't have any constructor. in any case.

Constructor name must be same as the class name. Method name may or may not be
same as class name.

static keyword

34
The static keyword in java is used for memory management mainly. We
can apply java static keyword with variables, methods, blocks and nested
class. The static keyword 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 you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc.
 The static variable 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).

Understanding problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data
members will get memory each time when object is created.All student have
its unique rollno and name so instance data member is good.Here, college
refers to the common property of all objects.If we make it static,this field
will get memory only once.

Example of static variable


//Program of static variable

class Student8{
int rollno;

35
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS

Program of counter without static variable

In this example, we have created an instance variable named count which is


incremented in the constructor. Since instance variable gets the memory at
the time of object creation, each object will have the copy of the instance
variable, if it is incremented, it won't reflect to other objects. So each
objects will have the value 1 in the count variable.

class Counter{
int count=0;//will get memory when instance is created

Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

36
}
Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only
once, if any object changes the value of the static variable, it will retain its
value.

class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}
Output:1
2
3

Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of a class.


o A static method can be invoked without the need for creating an
instance of a class.
o static method can access static data member and can change the
value of it.

37
Example of static method
//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student9.change();

Student9 s1 = new Student9 (111,"Karan");


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

why java main method is static?

because object is not required to call static method if it were non-static


method, jvm create object first then call main() method that will lead the
problem of extra memory allocation.

38
Java static block
o Is used to initialize the static data member.
o It is executed before main method at the time of classloading.

Example of static block


class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:static block is invoked
Hello main
Can we execute a program without main() method?

Ans) Yes, one of the way is static block but in previous version of JDK not in
JDK 1.7.

class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
} Output:static block is invoked (if not JDK7)

39

You might also like