The new keyword in Java programming language
In this tutorial, we will learn about the new keyword in Java programming language
new is a keyword in Java which is used to create a Java object and allocate memory space in memory disk. new is also used for array creation.
new keyword is used in many ways in Java.
- Array declaration
- Object creation
Array declaration
syntax
The syntax of new keyword of array declaration
<data_type> <array_name>=new <datatype>[size];
Example
Example of array declaration using new keyword
int marks=new int[5]; String [][] stu_name=new String[5][10];
object declaration using new keyword
Syntax
<class_name> <object_name>=new <class_name>
Example
class school{
}
class student{
school obj=new school();
//this is an object for school class }
Example
Program 1
program for using new keyword in Array
class new_keyword1{
public static void main(String args[]){
int number[]=new int[4];
//Array declaration used bew keyword
System.out.println("Value of index number[0] ="+number[0]);
System.out.println("Value of index number[1] ="+number[1]);
System.out.println("Value of index number[2] ="+number[2]);
System.out.println("Value of index number[3] ="+number[3]);
//display element of every cells of array
}
}
When the above code is compiled and executed, it will produce the following results
Value of index number[0]= 0 Value of index number[1]= 0 Value of index number[2]= 0 Value of index number[3]= 0
Program 2
program for using new keyword in create object
class Stu_marks{
int marks=78;
public static void main(String args[]){
Stu_marks stu=new Stu_marks();
System.out.println("Student marks :"+stu.marks);
}
}
When the above code is compiled and executed, it will produce the following results
student marks :78
New keyword in Scanner class
New keyword is used in Scanner class for memory allocation when create Scanner object
Example
Scanner scan=new Scanner(System.in); //predefined standed input object
There are other Java language keywords that are similar to this keyword
Suggested for you
Usage of this statement in the Java language
F*ckin?remarkable things here. I抦 very glad to see your post. Thanks a lot and i am looking forward to contact you. Will you please drop me a mail?