0% found this document useful (0 votes)
27 views24 pages

Jbad 3

Uploaded by

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

Jbad 3

Uploaded by

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

Data Types in Java

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

1) Java static variable


If you 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.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the 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 the object is created.

All students have its unique rollno and name, so instance data member
is good in such case.
Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.

Java static property is shared to all objects.


Example of static variable
//Java Program to demonstrate the use of static variable
class Student
{
int rollno;
String name;
static String college ="ITS";//static variable

Student(int r, String n){


rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects

public class TestStaticVariable1


{
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");

//we can change the college of all objects by the single line of code
//Student.college="BBDIT";

s1.display();
s2.display();
} }

Program of the 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 other objects.

So each object will have the value 1 in the count variable.

//Java Program to demonstrate the use of an instance variable


//which get memory each time when we create an object of the
class.

class Counter
{
int count=0;//will get memory each time when the instance is created
Counter()
{
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[])
{
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

2) 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 the object of a
class.
o A static method can be invoked without the need for creating
an instance of a class.
o A static method can access static data member and can change
the value of it.
class Student
{
int rollno;
String name;
static String college = "ITS";

//static method to change the value of static variable


static void change()
{
college = "BBDIT";
}
//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);
}
}
public class TestStaticMethod
{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");

//calling display method


s1.display();
s2.display();
s3.display();
}
}

Restrictions for the static method


There are two main restrictions for the static method. They are:

 The static method can not use non static data member or call
non-static method directly.

 this and super cannot be used in static context.

class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}
O/P :: Compile Time Error

Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of class
loading.
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

Types of Variables in Java

1. Local Variables
 A variable defined within a block or method or constructor is called a
local variable.
 These variables are created when the block is entered, or the
function is called and destroyed after exiting from the block or
when the call returns from the function.
 The scope of these variables exists only within the block in which
the variables are declared, i.e., we can access these variables only
within that block.
Initialization of the local variable is mandatory before using it in the
defined scope.

2. Instance Variables
 Instance variables are non-static variables and are declared in a
class outside of any method, constructor, or block.
 As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when
the object is destroyed.
 Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier, then the default
access specifier will be used.

 Initialization of an instance variable is not mandatory. Its default


value is dependent on the data type of variable. For String it
is null, for float it is 0.0f, for int it is 0, for Wrapper classes
like Integer it is null, etc.
 Instance variables can be accessed only by creating objects.
 We initialize instance variables using constructors while creating
an object

3. Static Variables
 Static variables are also known as class variables.
 These variables are declared similarly to instance variables.
The difference is that static variables are declared using the static
keyword within a class outside of any method, constructor, or block.
 Unlike instance variables, we can only have one copy of a static
variable per class, irrespective of how many objects we create.
 Static variables are created at the start of program execution and
destroyed automatically when execution ends.
 Initialization of a static variable is not mandatory.
Its default value is dependent on the data type of variable.

For String it is null, for float it is 0.0f, for int it is 0.

 If we access a static variable like an instance variable (through an


object), the compiler will show a warning message, which won’t
halt the program.
 Static variables cannot be declared locally inside an instance
method.
 Static blocks can be used to initialize static variables.

How to use these 2 keywords ?


 this
 super

this keyword and this() constructor

this keyword
It is a reserved keyword in Java that is used to refer to the current class
object.

It is a reference variable through which the method is called.


Other uses of this keyword are:

 We can use it to refer current class instance variable.


 We can use it to invoke the current class method (implicitly).
 We can pass it as an argument in the method and constructor calls.
 We can also use it for returning the current class instance from the
method.

this() Constructor
The constructor is used to call one constructor from the other of the same
class.
Let's take an example of both this keyword and this() to understand how
they work.

ThisExample1.java
// import required classes and packages

// create ThisExample1 class to understand the working of this() and


this

class ThisExample1 {

// initialize instance and static variable


int x = 5;
static int y = 10;

// default constructor of class ThisExample1


ThisExample1()
{
// invoking current class constructor
this(5);
System.out.println("We are insie of the default constructor.");
System.out.println("The value of x = "+x);
}

ThisExample1(int x)
{
this.x = x; // override value of the current class instance variable
System.out.println("We are inside of the parameterized constructo
r.");
System.out.println("The value of y = "+y);
}
public static void main(String[] args)
{
// invoking constructor of the current class
new ThisExample1();
System.out.println("Inside Main");
}
}

Output:

We are inside of the parameterized constructor.


The value of y =10
We are inside if the default constructor.
The value of x = 5
Inside Main

super Keyword
 A reserved keyword used to call the base class method or variable is
known as a super keyword. We cannot use the super keyword as
an identifier. The super keyword is not only used to refer to the base
class instance but also static members too.
 super() Constructor
 The super() is mainly used for invoking base class member functions
and constructors.
Let's take an example of both the super keyword and super() to understand
how they work.

SuperExample1.java

// import required classes and packages

// create Animal class which is base class of Animal


class Animal{
// data member of Animal class
String color = "white";

}
// create child class of Animal
class Cat extends Animal{
//default constructor
Cat()
{
// data members of the Cat class
String color = "Brown";
System.out.println("The cat is of color "+super.color); // calling parent class
data member
System.out.println("The cat is of color "+color);
}
}
// create child class for Car
class SuperExample1 extends Cat
{
// default constructor
SuperExample1()
{
// calling base class constructor
super();
System.out.println("The eyes of the cat is blue.");
}
// main() method start
public static void main(String[] args)
{
// call default constructor of the SuperExample1
new SuperExample1();
System.out.println("Inside Main");
}
}

Increment and Decrement


1) Increment Operator (++):
The increment operator in Java is denoted
by ++. It adds 1 to the current value of a
variable. There are two ways to use the
increment operator:
int x = 5;
x++; // Equivalent to x = x + 1;
or
int x = 5;
++x; // Equivalent to x = x + 1;
Both of these statements increase the
value of x by 1.
i. Prefix Increment Operator:

When the increment operator is placed


before the variable (++x), it increments
the value of the variable before the value
is used in the expression. For example:
int a = 3;
int b = ++a; // Now, a is 4 and b is also 4
In this case, a is incremented before its
value is assigned to b.

ii. Postfix Increment Operator:

When the increment operator is placed


after the variable (x++), it increments the
value of the variable after its current value
is used in the expression. For example:

int c = 3;
int d = c++; // Now, c is 4, but d is 3
Here, d is assigned the current value of c
before c is incremented.

2) Decrement Operator (--):


The decrement operator in Java is denoted
by --. It subtracts 1 from the current value
of a variable. Similar to the increment
operator, there are two ways to use the
decrement operator:
int y = 8;
y--; // Equivalent to y = y - 1;
or

int y = 8;
--y; // Equivalent to y = y - 1;546yhb `
Both of these statements decrease the
value of y by 1.

i. Prefix Decrement Operator:

Similar to the increment operator, the


prefix decrement operator (--x) decrements
the value of the variable before its value is
used in the expression.

int m = 7;
int n = --m; // Now, m is 6 and n is also 6
ii. Postfix Decrement Operator:

The postfix decrement operator (x--)


decrements the value of the variable after
its current value is used in the expression.
Arrays in Java
 In Java, all arrays are dynamically allocated.
 Arrays may be stored in contiguous memory [consecutive memory
locations].
 Since arrays are objects in Java, we can find their length using the object
property length.
 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 has an index beginning
with 0.
 Java array can also be used as a static field, a local variable, or a method
parameter.
Creating, Initializing, and Accessing an Arrays
One-Dimensional Arrays
The general form of a one-dimensional array declaration is

-- type var-name[];
-- type[] var-name;

An array declaration has two components: the type and the


name. type declares the element type of the array.

The element type determines the data type of each element that
comprises the array.

// both are valid declarations


int intArray[];
int[] intArray;
// an array of references to objects of
// the class MyClass (a class created by user)

MyClass myClassArray[];

// array of Object
Object[] ao,

// array of Collection
// of unknown type
Collection[] ca;

Instantiating an Array in Java


When an array is declared, only a reference of an array is
created.
To create or give memory to the 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];


Here, type specifies the type of data being allocated, size
determines the number of elements in the array, and var-name
is the name of the array variable that is linked to the array.
To use new to allocate an array, you must specify the type and
number of elements to allocate.
Example:

//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new will
automatically be initialized to zero (for numeric types), false (for
boolean), or null (for reference types).
Obtaining an array is a two-step process.
First, you must declare a variable of the desired array type.
Second, you must allocate the memory to hold the array, using
new, and assign it to the array variable.
Thus, in Java, all arrays are dynamically allocated.

Array Literal in Java


In a situation where the size of the array and variables of the
array are already known, array literals can be used.

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
 The length of this array determines the length of the
created array.
 There is no need to write the new int[] part in the latest
versions of Java.
Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index
begins with 0 and ends at (total array size)-1.

All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+
arr[i]);

Arrays of Objects in Java


An array of objects is created like an array of primitive-type
data items in the following way.

Student[] arr = new Student[5]; //student is a user-defined class


Syntax:

-- data type[] arrName;


-- datatype arrName[];
-- datatype [] arrName;
import java.io.*;

class Demo {
public static void main (String[] args) {
int [] arr=new int [4];
// 4 is the size of arr
System.out.println("Array Size:"+arr.length);
}
}
The student Array contains five memory spaces each of the size of
student class in which the address of five Student objects can be stored.

The Student objects have to be instantiated using the constructor of the


Student class, and their references should be assigned to the array
elements in the following way.

class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}

// Elements of the array are objects of a class Student.


public class StudentTest {
public static void main(String[] args)
{
// declares an Array of Students
Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1, "aman");

// initialize the second elements of the array


arr[1] = new Student(2, "vaibhav");

// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].name);
}
}

Multidimensional Arrays in Java


Multidimensional arrays are arrays of arrays with each element of the
array holding the reference of other arrays. These are also known as
Jagged Arrays. A multidimensional array is created by appending one
set of square brackets ([]) per dimension.

Syntax of Java Multidimensional Array


There are 2 methods to declare Java Multidimensional Arrays as
mentioned below:

-- datatype [][] arrayrefvariable;


-- datatype arrayrefvariable[][];
import java.io.*;

// Driver class
class Demo {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column

arr[][]= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// 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();

// Number of Rows
System.out.println("Number of Rows:"+
arr.length);
// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy