Java technology is both a programming language and a platform.
Java is an object-oriented programming language developed by James Gosling and colleagues in the early 1990s.
Version
|
Released Year
|
Name
|
1.0
|
Jan-26-1996
|
Oak
|
1.1
|
Feb-19-1997
|
Java 1.1
|
1.2
|
Dec-08-1998
|
Playground
|
1.3
|
May-08-2000
|
Crystal
|
1.4
|
Feb-06-2002
|
Merlin
|
1.5
|
Sep-30-2004
|
Tiger
|
1.6
|
Dec-11-2006
|
Mustang
|
1.7
|
July-07-2011
|
Dolphin
|
Java 1.8 may be expected 2013...
C++
|
Java
|
C++ is not a purely object-oriented programming language, since it is possible to write C++ programs without using a class or an object.
|
Java is purely an object-oriented programming language, since it is not possible to write a Java program using atleast one class.
|
In C++ most confusing concepts like Pointers, Virtual functions, friend functions ,operator overloading are available in C++.
|
In we don't have any those confusing concepts.
|
The memory alloted by the programmer its his/her responsibility to deallocation.
|
The memory allotted by the programmer, if its freely laying then garbage collector will collect the garbage automatically.
|
In C++ there are five types of inheritances like
(single level, multilevel,multiple, hierarchical, hybrid)
|
Java support single level and multilevel inheritances
|
#define, typedef and header files are available in C++
|
#define, typedef and header are not available in Java, but there are means to achieve them.
|
There are 3 access specifiers in C++ private, public, and protected. By default if don't give any access specifiers its private
|
Java supports 4 access specifiers: private, public, protected, and default. By default if don't give any access specifiers its private.
|
There are constructors and destructors in C++
|
Only constructors are there in Java. No destructors are available in this language.
|
C++ is platform dependent
|
Java is platform independent
|
If C++ program compiles its generate machine dependent code.
|
If Java program compiles it generate intermediate code, which is specific to the JVM
|
The Java programming language is a high-level language that can be characterized by all of the following buzzwords:
- Simple
- Object-oriented
- platform-independent
- Secure
- Robust
- Distributed
- Multithread
- Memory ManagementSimple:Java is a simple programming language, The Java is simple because, Java follows and the same syntax of C and C++ and the difficult concepts of C and C++ like pointers, Operator overloading, virtual functions....etc, have been omitted in Java.Object-oriented:Java is an object-oriented programming language. This means Java programs use objects and a classes.ClassA class is template or blueprint for how to build an object.ObjectAn instance of a particular class is called object.
The Java platform differs from most other platforms like windows, unix ...etc. Java software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components:
- The Java Virtual Machine
- The Java Application Programming Interface (API)
In the Java programming language, all source code is first written in plain text files ending with the
.java
extension. Those source files are then compiled into .class
files by the javac
compiler. A .class
file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine.
The JVM is available on many different operating systems. The .class file can run any operating system where ever JVM is available. The JVM makes the java as platform-independent.
Secure:
Security problems like eavesdropping, tampering, impersonation, and virus threats can be eliminated or minimized by using Java on Internet.
Multithreaded:
A thread represents an individual process to execute different blocks of code. Creating multiple threads is called multithreaded.
Robust:
Robust means strong. Java programs are strong and they don’t crash easily like a C or C++ program. There are two reasons for this. Firstly, Java has got excellent inbuilt exception handling features. An exception is an error that occurs at run time. If an exception occurs, the program terminates abruptly giving rise to problems like loss of data. Overcoming such problems is called exception handling. This means that even though an exception occurs in a Java program, no harm will happen.
Distributed:
Information is distributed on various computers on a network. Using Java, we can write programs, which capture information and distribute it to the clients. This is possible because Java can handle the protocols like TCP/IP and UDP.
Memory management:
In Java the memory allocated by the programmer, automatically garbage collected by the garbage collector when it is available for garbage collector.
Java SE Development Kit (JDK)
The JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.
Java SE Runtime Environment (JRE)
The JRE provides the libraries, Java virtual machine, and other components necessary for you to run applets and applications written in the Java programming language. This runtime environment can be redistributed with applications to make them free-standing.
Java Virtual Machines
The Java virtual machine is an abstract computing machine that has an instruction set and manipulates memory at run time. The Java virtual machine is ported to different platforms to provide hardware- and operating system-independence.
The JVM is heart of the java, its provides
- loads code
- verifies code
- Executes code
- provides runtime environment
The .class file is given to the JVM. In JVM, there is a module called class loader sub system, which performs the following functions:
- First of all, it loads the .class file into memory.
- Then it verifies whether all byte code instructions are proper or not. If it finds any instruction suspicious, the execution is rejected immediately.
- If the byte instructions are proper, then it allocates necessary memory to execute the program.
This memory is divided into 5 parts, called un time data areas, which contain the data and results while running the program. These areas are as follows:
Method area: Method area is the memory block, which stores the class code, code of the variables, and code of the methods in the Java program. (Method means functions written in a class)
Heap: This is the area where objects are created. Whenever JVM loads a class, a method and a heap area are immediately created in it.
Java Stacks: Method code is stored on Method area. But while running a method, it needs some more memory to store the data and results. So, Java stacks are memory areas where Java methods are executed. While executing methods, a separate frame will be created in the Java stack. Where the method is executed. JVM uses a separate thread (or process) to execute each method.
PC (Program Counter) registers: These are the registers (memory areas), which contain memory address of the instructions of the methods. If there are 3 methods, 3 PC registers will be used to track the instructions of the methods.
Native method stacks: Java methods are executed on Java stacks. Similarly, native methods (for example C/C++ functions) are executed on Native method stacks. To execute the native methods, generally native method libraries (for example C/C++ header files) are required. These header files are located and connected to JVM by a program, called Native method interface.Method area: Method area is the memory block, which stores the class code, code of the variables, and code of the methods in the Java program. (Method means functions written in a class)
Execution engine: a mechanism responsible for executing the instructions contained in the methods of loaded classes.
Arrays
· An array is an object that is a named set of variables of the same type. Each variable in the array is called an array element.
· All elements in the array must be of the same data type
· Arrays in Java are objects and can be of primitive data types or reference variable type
To reference a particular element in an array, you use the array name combined with an integer value of type int, called an index.
int marks[6]=new int[]{50,80,85,95.80};
Example marks [4]
Here marks is an array and [4] indicates the 4 element of array
50 80 85 90 95 80
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5]
The index value does not need to be an integer literal. It can be any expression that results in a value of type int that is equal to or greater than zero.
arr[(low+high)/2]
An Array index starts with 0 and ends with the size-1
Declaration of the array
int[] marks=new int[5];
String[] names=new String[5 ];
Student[] name=new Student[5];
Note: Array size shouldn't be negative number, if specify negative number it leads to the runtime exception. java.lang.NegativeArraySizeException
Initilization of the array
int[] numbers=new int[]{1,2,3,4,5,6}
Here the integer array is created with numbers and size with 6 and array will be initilized with 1,2,3,4,5,6 values.
int[] num={10,20,30,40,60,70};
Here the integer array is created with name num and initialized with 10,20,30,40,60,70
Length of an array
The number of elements contains in the array can be find using length. Here length is field
Example:
int[] a=new int[]{1,5,10,15};
int len=a.length (which returns the length is 4 )
Storing Array elements
We can store the elements into the array by using index or by running the for loop
Example
int[] a=new int[3]
a[0]=10;
a[1]=20;
a[2]=30;
(or)
for(int i=0;i<a.length;i++){
a[i]=i;
}
ArrayElements can be accessed:
int a[]=new int[3];
System.out.print(a[0]);
System.out.print(a[1]);
System.out.print(a[2]);
(or)
for(int i=0;i<a.length;i++){
System.out.print(a[i]);
}
Array elements can be processed by using the for-each loops
for(int i : a)
System.out.print(i);
In java Arrays are created dynamic memory, that is allocated at runtime by the JVM.
int[] a;
Here just we created reference variable a and its not holding any object later we can initialize this a reference variable with integer array object.
int[] a=new int[]{10,20,30,40};
int[] b=a;
int[] input[]=new int[]{1,2,3,4};
int[] output=new int[4];
int[] temp;
When you want to switch the array referenced by output array to be the new input array, we can write
temp=input;
input=output;
output=temp;
Example:
public class ArrayDemo {
public static void main(String[] args) {
int[] input=new int[]{1,2,3,4};
int[] output=new int[4];
int[] temp;
for(int i=0;i<input.length;i++){
output[i]=input[i]*5;
}
temp=input;
input=output;
output=temp;
for(int i=0;i<input.length;i++)
System.out.println(output[i]);
}
}
Multidimensional Arrays:
Multidimensional arrays are implemented as arrays of arrays.
Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name.
Declaration
int a[][]=new int[3][3]
Initialization of the multidimensional array can be done in this way
int a[][]=new int[][]{ {2,3,4},{3,4,5},{4,5,6}};
Anonymous Arrays
Sometimes we can declare an array without name also such type of arrays are called anonymous arrays. Normally these arrays will be created for temporary usage.
/* program to find the biggest of the four numbers*/
Example:
import java.util.Scanner;
public class ArraysDemo {
public static void main(String[] args) {
int a,b,c,d,big;
System.out.println("Enter the a,b,c");
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=sc.nextInt();
big=biggestElement(new int[]{a,b,c,d});
System.out.println("The biggest element is : "+big);
}
private static int biggestElement(int[] a) {
private static int biggestElement(int[] a) {
int big;
big=a[0];
for(int i=1;i<a.length;i++){
if(a[i]>big)
big=a[i];
}
return big;
}
}
/*Program to Accept N number from the user,create an array with size N and accpt the numbers and storing into array. Find the biggest and smallest elements int the given array */
package com.jsl.array;
import java.util.Scanner;
public class BiggestAndSmallest {
public static void main(String[] args) {
int big,small,array[];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array ");
/* Creating new Array with the user given size */
array=new int[sc.nextInt()];
for(int i=0;i<array.length;i++){
System.out.println("Enter the element "+(i+1)+" value ");
array[i]=sc.nextInt();
}
/* initilizing big and small elements with the initial values */
big=array[0];
small=array[0];
/* Accessing array elements by using for-each loop */
for(int ele:array){
if(ele>big)
big=ele;
if(ele<small)
small=ele;
}
System.out.println("The biggest element is :"+big);
System.out.println("The smallest element is :"+small);
}
}
/*program to search the element in the given array */
package com.jsl.array;
import java.util.Scanner;
public class SearchingElement {
public static void main(String[] args) {
int[] arr=new int[10];
int ele;
Scanner sc=new Scanner(System.in);
for(int i=0;i<arr.length;i++){
System.out.print("Enter the value of "+(i+1)+" value ");
arr[i]=sc.nextInt(); }
System.out.println("Enter the element to search ");
ele=sc.nextInt();
int pos=serarchElement(arr,ele);
if(pos==-1)
System.out.println("The element is not found ");
else
System.out.println("The element is found at loaction : " + pos);
}
private static int serarchElement(int[] arr, int ele) {
int pos=-1;
for(int i=0;i<arr.length;i++){
if(arr[i]==ele){
pos=i;
break;
}
}
return pos;
}
}
/*Program to find the result,grade,average marks of given students marks list*/
package com.jsl.arrays;
public class ArrayDemo {
public static void main(String[] args) {
int marks[][]=new int[][]{
{23,45,56,34},
{45,23,67,78},
{78, 89,90,80},
{53,45,78,61}
};
for(int i=0;i<marks.length;i++){
int sum=0;
float aveg=0.0f;
String result="Pass";
String grade=" ";
System.out.println("\n The student "+(i+1)+" Details are \n");
System.out.println("Sub1\tSub2\tSub3\t Sub4 \t Total\t Average\tResult\tGrade");
for(int j=0;j<marks[i].length;j++){
System.out.print(" "+marks[i][j]+"\t");
if(marks[i][j]<35)
result="Fail";
sum=sum+marks[i][j];
}
aveg=sum/4;
if(result.equals("Pass")){
if(aveg>=70)
grade="Distinction";
else if(aveg>=60 && aveg<70)
grade="First Class";
else if(aveg<60)
grade="Second Class";
else
grade="Third Class";
}
else{
grade=" Sorry Study Well";
}
System.out.print(sum+" \t "+aveg+"\t \t"+result+"\t "+grade);
System.out.println("\n________________________________________");
}
}
}
/* Binary Search Examples */
package com.jsl.core.array;
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
int size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
size = sc.nextInt();
int a[] = new int[size];
for (int i = 0; i < a.length; i++) {
System.out.println("Enter the no " + (i + 1) + " Value");
int no = sc.nextInt();
a[i] = no;
}
int s[] = sort(a);
System.out.println("Enter the key to search ");
int key = sc.nextInt();
if (getElement(s, key) == -1) {
System.out.println("The element is not found");
} else {
System.out.println("The element is found");
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
return a;
}
public static int getElement(int a[], int key) {
int low = 0, high = a.length - 1, mid, pos = -1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
pos = mid;
return pos;
} else if (key > a[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
private int pid;
this.pid = pid;
System.out.println("The Product Details are :");
for (Product pro : product) {
System.out.print(pro.pid + "\t" + pro.pname + "\t" + pro.price);
public class ArraysWithReference {
public static void main(String[] args) {
Product p = new Product();
private int a[];
public ArrayContainer() {
a=new int[2];
public void addElement(int ele){
if(icount<a.length){
a[icount++]=ele;
}else{
public void display(){
if(a.length==0 ||icount==0){
System.out.println("There is no elements");
for(int i=0;i<icount;i++){
System.out.println(a[i]);
ArrayContainer obj=new ArrayContainer();
for(;;){
if(ch==1){
System.out.println("Enter the elment to add");
}else if(ch==2){
obj.display();
}else{
break;
/*Java Example with Arrays */
package com.jsl.core.array;
public class ArrayDemo {
public static void main(String[] args) {
int size;
System.out.print("[");
System.out.print(a[i] + " ");
int key = sc.nextInt();
if (getElement(a, key) == -1) {
int big = a[0];
if (big < a[i])
if (small > a[i])
/* Binary Search Examples */
package com.jsl.core.array;
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
int size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
size = sc.nextInt();
int a[] = new int[size];
for (int i = 0; i < a.length; i++) {
System.out.println("Enter the no " + (i + 1) + " Value");
int no = sc.nextInt();
a[i] = no;
}
int s[] = sort(a);
System.out.println("Enter the key to search ");
int key = sc.nextInt();
if (getElement(s, key) == -1) {
System.out.println("The element is not found");
} else {
System.out.println("The element is found");
}
}
private static int[] sort(int[] a) {for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
return a;
}
public static int getElement(int a[], int key) {
int low = 0, high = a.length - 1, mid, pos = -1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
pos = mid;
return pos;
} else if (key > a[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
/* Arrays with reference Type */
package com.jsl.core.array;
class Product {
private int pid;
private String pname;
private double price;
private Product product[];
private Product(int pid, String pname, double price) {
this.pid = pid;
this.pname = pname;
this.price = price;
}
public Product() {
product = new Product[] { new Product(1001, "Laptop", 45000),
new Product(1002, "DVDROM", 4000),
new Product(1003, "Mouse", 500),
new Product(1005, "PenDriver", 450)
};
};
}
public void productInfo() {
System.out.println("The Product Details are :");
System.out.println("-----------------------------------");
for (Product pro : product) {
System.out.print(pro.pid + "\t" + pro.pname + "\t" + pro.price);
System.out.println("\n-----------------------------------------\n");
}
}
}
public class ArraysWithReference {
public static void main(String[] args) {
Product p = new Product();
p.productInfo();
}
}
/* Dynamic growing array Example */
package com.jsl.core.array;
import java.util.Scanner;
class ArrayContainer{
private int a[];
private int icount=0;
private int count=0;
public ArrayContainer() {
a=new int[2];
}
public void addElement(int ele){
if(icount<a.length){
a[icount++]=ele;
}else{
int b[]=new int[a.length+a.length];
System.arraycopy(a, 0, b, 0, a.length);
b[icount++]=ele;
a=b;
}
}
public void display(){
if(a.length==0 ||icount==0){
System.out.println("There is no elements");
}
if(count<a.length){
for(int i=0;i<icount;i++){
System.out.println(a[i]);
}
}
}
}
public class ArraySwaping {
public static void main(String[] args) {
ArrayContainer obj=new ArrayContainer();
for(;;){
System.out.println("Enter the choice 1.add 2.display 3.exit");
Scanner sc=new Scanner(System.in);
int ch=sc.nextInt();
if(ch==1){
System.out.println("Enter the elment to add");
int ele=sc.nextInt();
obj.addElement(ele);
}else if(ch==2){
obj.display();
}else{
break;
}
}
}
}
package com.jsl.core.array;
import java.util.Scanner;
public class ArrayDemo {
public static void main(String[] args) {
int size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
size = sc.nextInt();
int a[] = new int[size];
for (int i = 0; i < a.length; i++) {
System.out.println("Enter the no " + (i + 1) + " Value");
int no = sc.nextInt();
a[i] = no;
}
System.out.println("The Array elements are :");
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.print("]");
System.out.println("The biggest element is :" + biggest(a));
System.out.println("The biggest element is :" + smallest(a));
System.out.println("The elements sum is :" + sumOfArrayElements(a));
System.out.println("Enter the key to search ");
int key = sc.nextInt();
if (getElement(a, key) == -1) {
System.out.println("The element is not found");
} else {
System.out.println("The element is found");
}
}
public static int biggest(int a[]) {
int big = a[0];
for (int i = 1; i < a.length; i++) {
if (big < a[i])
big = a[i];
}
return big;
}
public static int smallest(int a[]) {
int small = a[0];
for (int i = 1; i < a.length; i++) {
if (small > a[i])
small = a[i];
}
return small;
}
public static int getElement(int a[], int key) {
int pos = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == key) {
pos = i;
break;
}
}
return pos;
}
public static int sumOfArrayElements(int a[]) {
int sum = 0;
for (int ele : a)
sum = sum + ele;
return sum;
}
}
Task:
1. Write a program to accept N value and create the array size N. Find the sum of elements in the array.
2. Write a program to accept N value and create the array size N. Find the biggest and the smallest elements in the array
3. Write a program that allows you to create an integer array of 18 elements with the following values: int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,2,0,0,0,}. The program computes the sum of element 0 to 14 and stores it at element 15, computes the average and stores it at element 16 and identifies the smallest value from the array and stores it at element 17.
4. Write a program that accepts two numbers in the range from 1 to 50 from the user. It then compares these numbers against the single dimension array of 5 integer elements ranging in value from 1 to 50. The program displays the message success if the two inputted values are found in the array element. Otherwise print it as fail.
5. Write a program that accepts M x N matrix and
1. Find the sum of elements in the matrix
2. Biggest element in the matrix
3. Diagonal sum of the matrix
4. Transpose of the given matrix
final (keyword)
In Java, final keyword is applied in various contexts.
1. If class is marked as final that class cannot be inherited
2. If method is marked as final that method cannot be overridden
3. If the variable is declared as final then the value can’t be changed or reassigned
4. If the Arguments of a method declared as final those variables cannot be modified within the method.
final int i=10;
The variable i declared as final only once we can assign the value. If try to modify it leads to the compilation error.
final int var;
The final variables won’t be initialized with default values by JVM. It’s compulsory we should perform initialization before compilation of the constructor.
/* Program to demonstrate the blank final variables */
package com.jsl.core.book;
public class FinalKeywordExample {
final int var; // Blank final variables.
public FinalKeywordExample() {
var=100;
}
public void display( ){
System.out.print(“The value of final variable is :”+var);
}
}
/* Program to demonstrate the final local variables */
package com.jsl.core.book;
import java.util.Scanner;
public class FinalKeywordExample {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no : ");
int no=sc.nextInt();
double res=factorialOfNumber(no);
System.out.println("The factorial of : "+res);
}
private static double factorialOfNumber(final double no) {
double res=1;
for(int i=1;i<=no;i++)
res=res*i;
return res;
}
}
The static final variable must be initialized when it is declared or must be initialized inside the static block.
/* Program to demonstrate the static final variables */
package com.jsl.core.book;
public class FinalKeywordExample {
private final static int var1=5;
private final static int var2; // Blank static final variable.
static{
var2=10;
}
public static void main(String[] args) {
System.out.println("The product of "+var1+" and "+var2+" = "+(var1*var2));
}
}
If the final variable is declared inside the method that variable must be initialized before using, otherwise its leads to the compilation error.
public void showNumber( ){
final int no;
System.out.print(“The value of no is : “+no)
//Its leads to the compilation error. The local variable no must be initilzed before using.
}
/* Program to demonstrate final local variables */
package com.jsl.core.book;
public class FinalKeywordExample {
public static void showNumber(){
final int no=100;
System.out.println("The value of no is : "+no);
}
public static void main(String[] args) {
showNumber();
}
}
final methods:
The final keyword prevents a method from being overridden in a subclass, normally if methods, not necessary to change the functionality, then those methods can be marked as final.
public final void getSimpleInterest( ){
body
-----------------
}
/* program to demonstrate the final methods */
package com.jsl.core.book;
public class FinalKeywordExample {
public final static double calSimpleInterest(double p,double t,double r){
return (p*t*r)/100;
}
}
/* Main class to access the methods */
package com.jsl.core.book;
public class MainClass {
public static void main(String[] args) {
Double interest=FinalKeywordExample.calSimpleInterest(100000, 12, 1);
System.out.println("The interest is : "+interest);
}
}
final reference variable:
final reference variables cannot refer to a different object once the object has been assigned to the final variable. final reference variables must be initialized before the constructor completes.
There is no such thing as a final object. An object reference marked final does not mean the object itself is immutable. That object allows you to make the modification and behaves like a mutable object.
/* program to demonstrate the final reference variables */
package com.jsl.core.book;
public class MainClass {
public static void main(String[] args) {
final String fname=new String("Lakshman");
fname=new String("JSLTech");
// Leads compilation error. The final reference variable can be assigned only once.
}
}
final classes:
A final class cannot be sub classed i.e. that classes can’t be inherited. If classes is declared as final then all that class methods behave like final methods.
/* Program to demonstrate the final classes */
package com.jsl.core.book;
public final class FinalKeywordExample {
private FinalKeywordExample(){
}
public static double calSimpleInterest(double p,double t,double r){
return (p*t*r)/100;
}
public static double currencyConversion(final int amount,final int price){
return amount*price;
}
}
/* Main class to access the final class methods */
package com.jsl.core.book;
public class MainClass {
public static void main(String[] args) {
System.out.println(FinalKeywordExample.calSimpleInterest(100000,10, 1.50));
System.out.println(FinalKeywordExample.currencyConversion(5000,68));
}
}
Varargs:
Varargs is introduced from Java 1.5. by using varargs Programmers can create methods that receive an unspecified number of arguments.
In method varargs can be declare as
Data_type… variable_name
Example:
public void sum(int... a){
}
public void sum(int... a) indicates that the method receives a variable number of arguments of integer type.
Example:
package com.jsl.core;
public class VarArgsDemo {
public int sum(int... a){
int res=0;
for(int i=0;i<a.length;i++){
res=res+a[i];
}
return res;
}
public static void main(String[] args) {
VarArgsDemo obj=new VarArgsDemo();
System.out.println("The sum of two variable is :"+obj.sum(10,20));
System.out.println("The sum of three variable is :"+obj.sum(10,20,30));
System.out.println("The sum of four variable is :"+obj.sum(10,20,30,40));
}
}
Output:
The sum of two variable is :30
The sum of three variable is :60
The sum of four variable is :100
Example:
package com.jsl.core;
public class VarArgsDemo {
public static void main(String... args) {
for(String name:args){
System.out.println(name);
}
}
}
java VarArgsDemo Jsl Tech Java Training
output
Jsl
Tech
Java
Training
The varargs length must be only one variable in method parameter list.
public void sum(int... a, float... b) it leads to compilation error, Because in a method we can declare only one varargs length variable.
If the varargs length variable is combined with other variables, this varargs length variable should be last in the parameter list.
public void sum(int x,float y,int... a)
The method overloading with same type parameter in different length or passing array to a method can accomplished by using varargs.
Example:
package com.jsl.core;
public class VarArgsDemo {
public int sum(int[]...a){
int res=0;
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++){
res+=a[i][j];
}
}
return res;
}
public static void main(String... args) {
VarArgsDemo obj=new VarArgsDemo();
System.out.println("The sum is : "+obj.sum(new int[][]{{1,2,3},
{4,5,6},{7,8,9}}));
{4,5,6},{7,8,9}}));
}
}
output :
The sum is : 45
The data type enum, introduced in J2SE 5.0, is useful when you want a variable to hold only a predetermined set of values. You should use enums any time you need a fixed set of constants, including natural enumerated types such as days of the week. You define an enum variable in two steps:
1. Define the enum type with a set of named values.
2. Define a variable to hold one of those values.
enum ShirtSize { SMALL, MEDIUM, LARGE}
ShirtSize size = ShirtSize.MEDIUM;
Every constant inside enum is implicitly public static and final by default. And we can access enum
constants by using enum name.
ShirtSize.SMALL
An enum can be declared outside or inside a class, but not in a method. Because By Default enum constants are public static final. So in method we can’t declare any static Members. If An enum declared outside a class must not be marked static, final, abstract, protected, or private.
public static void main(String[] args) {
enum ShirtSize{ SMALL,MEDIUM,LARGE}
/*Leads to compilation error, because enum can’t be declared inside method */
}
All enum types are inherently subclasses of the Java class Enum and therefore inherit its methods, some of which are
Method Summary | |
protected Object |
clone()
Throws CloneNotSupportedException. |
Int | Compares this enum with the specified object for order. |
Boolean | equals(Object other) Returns true if the specified object is equal to this enum constant. |
Class<E> | getDeclaringClass() Returns the Class object corresponding to this enum constant's enum type. |
Int | hashCode() Returns a hash code for this enum constant. |
String | name() Returns the name of this enum constant, exactly as declared in its enum declaration. |
Int | ordinal() Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). |
String | toString() Returns the name of this enum constant, as contained in the declaration. |
Example :
public class EnumDemo {
enum ShirtSize{ SMALL,MEDIUM,LARGE}
public static void main(String[] args) {
for(ShirtSize s:ShirtSize.values()){
System.out.println(s);
}
}
}
The Output :
SMALL
MEDIUM
LARGE
Constructors,Methods, and Variables in an enum
Just like a class, an enum can have constructors, methods, and variables in addition to the constants.
Example
enum ShirtSize{
SMALL(30),MEDIUM(40),LARGE(50);
ShirtSize(int size){
this.size=size;
}
private int size;
public int getSize(){
return size;
}
}
public class EnumDemo {
public static void main(String[] args) {
for(ShirtSize size:ShirtSize.values()){
System.out.println(size.name() + " = " +size.getSize());
}
}
}
Nice and Informative Blog.
ReplyDeleteVisit us: Java Online Training
Visit us: Core java training