Java Operator Precedence Guide
Java Operator Precedence Guide
evaluated when the expression has several operators. For example, multiplication and division
have a higher precedence than addition and subtraction. Precedence rules can be overridden by
explicit parentheses.
Precedence order.
When two operators share an operand the operator with the higher precedence
goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is
treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.
Associativity.
When an expression has two operators with the same precedence, the expression is
evaluated according to its associativity. For example x = y = z = 17 is treated as x
= (y = (z = 17)), leaving all three variables with the value 17, since the = operator
has right-to-left associativity (and an assignment statement evaluates to the value
on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3
since the / operator has left-to-right associativity.
Lev Associati
el
vity
Operator
Description
[]
.
()
++
--
access array
element
access object
member
invoke a method
post-increment
post-decrement
left to
right
++
-+
!
~
pre-increment
pre-decrement
unary plus
unary minus
logical NOT
bitwise NOT
right to
left
()
cast
object creation
right to
left
new
*
/
%
multiplicative
left to
right
+ +
additive
string
concatenation
left to
right
<< >>
>>>
shift
left to
right
< <=
> >=
instanceof
relational
type comparison
left to
right
==
!=
equality
left to
right
&
bitwise AND
left to
right
bitwise XOR
10
left to
right
bitwise OR
11
left to
right
&&
conditional AND
12
left to
right
||
conditional OR
13
left to
right
?:
conditional
14
right to
left
assignment
15
right to
left
=
*=
&=
<<=
+=
-=
/=
%=
^=
|=
>>= >>>=
B b= new B();
6.
7.
8.
9.
10.
11. public static void main(String[] args) {
12.
13.
B b= new B();
14.
[Link]();
15.
16.
17. }
Whenever we create the object of any class constructor will be called first and memory
allocated for all non static variables
Here B b= new B(); variable is object and assigned to new object of same class
B b= new B(); statement leads to recursive execution of constructor will create infinite
objects so at run time an exception will be raised
The common cause for a stack overflow exception is a bad recursive call. Typically this
is caused when your recursive functions doesn't have the correct termination condition
7.
static
8.
9.
a = a-- - --a;
10. }
11.
12. {
13.
a = a++ + ++a;
14. }
15.
16. public static void main(String[] args) {
17.
18.
[Link](a);
19.
20.
21.
22. }
Ans: 2
int GetValue()
7.
8.
9.
10.
11. public static void main(String[] args) {
12.
13. A obj= new A();
14.
15.
[Link]();
16.
17.
18.
19. }
1. Exception in thread "main" [Link]
5. What is the output of following program?
1. package [Link];
2.
3. public class A{
4.
5.
6.
7.
8.
Integer i1 = 128;
9.
10.
Integer i2 = 128;
11.
12.
[Link](i1 == i2);
13.
14.
Integer i3 = 127;
15.
Integer i4 = 127;
16.
17.
[Link](i3 == i4);
18.
19.
20.
21. }
1. false
2. true
6. What is the output of following program?
1. package [Link];
2. class A
3. {
4.
5. void method(int i)
6. {
7.
8.
9.
10.
11.
12. class B extends A
13. {
14.
15. @Override
16. void method(Integer i)
17. {
18.
19. }
20.
21.
22.
23. }
9.
10.
11. }
12.
13. }
1. 11
[Link](null);
9.
10. }
11.
12. }
1. Compilation Error
9.
10. for(int i=[Link]()-1;i>=0;--i){
11. revstring +=[Link](i);
12. }
13.
14. [Link](revstring);
15. }
16. }
Program:
output: dlrow olleH.
2)Sorting the String without using String API?
1. package [Link];
2.
3. public class SortString {
4.
5.
6.
7.
8.
int j=0;
9.
char temp=0;
10.
11.
12.
13.
14.
if(chars[j]>chars[i]){
15.
temp=chars[i];
16.
chars[i]=chars[j];
17.
chars[j]=temp;
18.
19.
20. }
21.
22.
for(int k=0;k<[Link];k++){
23.
[Link](chars[k]);
24.
25.
26. }
27. }
program:
output:abcde.
[Link] the String with using String API?
program:
1. package [Link];
2.
3.
4.
5.
6.
7.
8.
9.
[Link](chars);
10.
11.
12.
[Link](sorted);
13.
14. }
15. }
OutPut:abcde
[Link] String is palindrome or not?
program:
Solution #1:
1. package [Link];
2.
3. public class PalindromeDemo{
4.
5. public static void main(String[] args) {
6.
7. String str="MADAM";
8. String revstring="";
9.
10. for(int i=[Link]()-1;i>=0;--i){
11. revstring +=[Link](i);
12. }
13.
14. [Link](revstring);
15.
16. if([Link](str)){
17. [Link]("The string is Palindrome");
18. }
19. else{
20. [Link]("Not Palindrome");
21. }
22.
23. }
24.
25. }
Output:
The string is Palindrome
Solution #2:
1. package [Link];
2.
3.
import [Link];
4.
5.
6.
7. public static void main(String[] args)
8. {
9.
10. Scanner in = new Scanner([Link]);
11.
12. [Link]("Enter a string");
13. String str=[Link]();
14.
15. StringBuffer strone=new StringBuffer(str);
16. StringBuffer strtwo=new StringBuffer(strone);
17.
18. [Link]();
19.
20. [Link]("Orginal String ="+strtwo);
[Link]("Result:Palindrome");
25.
else
26.
[Link]("Result:Not Palindrome");
27.
28.
29.
30. }
Output:
Enter a string
MOOM
Orginal String =MOOM
After Reverse =MOOM
Result:Palindrome
[Link] to Check given number is palindrome or not?
Program:
1.
2.
package [Link];
3. import [Link];
4.
5. public class Palindrome {
6.
7. public static void main(String[] args)
8. {
9.
10. [Link]("Please Enter a number : ");
11.
12.
int number=givennumber;
13.
int reverse=0;
14.
while (number != 0) {
15.
16.
17.
18.
[Link]("Result:Palindrome");
21.
else
22.
[Link]("Result:Not Palindrome");
23.
24.
25. }
Output:
Please Enter a number :
535
Result:Palindrome.
1. package [Link];
2.
3. public class CountNumberofWords {
4.
5.
6.
7. String s="";
8. int count=0;
9.
[Link] in = new Scanner([Link]);
[Link]("Please enter a String");
12. s=[Link]();
13.
[Link] ch[]= new char[[Link]()];
15.
[Link](int i=0;i<[Link]();i++)
17.{
18.
19.
ch[i]= [Link](i);
20.
21.
22.
23.
24.}
[Link]("Number of words in given String: "+count);
26.
27.}
28.
29.}
Output:
1. Please enter a String
2. Java Tutorial
3. Number of words in given String: 2
8.
9.
10.
11. Scanner in= new Scanner([Link]);
12. [Link]("Please enter a String");
13.
14. str=[Link]();
15.
16. [Link]("Please enter a Character");
17. String chr=[Link]();
18.
19. int charCount = [Link]() - [Link]("a", "").length();
20.
21. [Link]("Number of occurances of given character:"+charCount);
22.
23.}
24.
25.}
Output:
Solution #2:
1. package [Link];
2.
3. import [Link];
4.
5. public class CountNumberofChars {
6.
7. public static int countOccurrences(String find, String string)
8. {
9. int count = 0;
[Link] indexOf = 0;
11.
[Link] (indexOf > -1)
13.{
14.
15.
16.
17.
count++;
}
[Link] count;
19. }
20.
21. public static void main(String[] args) {
22.
23. int charCount=countOccurrences("a", "Instance of Java");
24.
25. [Link]("Number of occurances of given character:"+charCount);
26.
27.}
28.
29.}
Output:
1. Number of occurances of given character: 3
6.
7. [Link]("Please enter a String");
8. Scanner in = new Scanner([Link]);
9.
10.
11.
12.
13. int count = 0;
14.
15. for (char ch : Chararray) {
16.
switch (ch) {
17.
case 'a':
18.
case 'e':
19.
case 'i':
20.
case 'o':
21.
case 'u':
22.
case 'A':
23.
case 'E':
24.
case 'I':
25.
case 'O':
26.
case 'U':
27.
count++;
28.
break;
29.
default:
30.
31.
32. }
33.
34.
35.}
36.
37.}
Output:
1. Please enter a String
2. Instance Of Java
3. Number of vowels in String 6
Solution #2:
1. package [Link];
2.
3. public class CountNumberofVowels {
4.
5.
6.
7.
8.
9. [Link]("Please enter a String");
[Link] in = new Scanner([Link]);
[Link] testString= [Link]();
12.
13.
[Link](int i = 0; i < [Link](); i ++)
15.{
16.
17. ch = [Link](i);
18.
19. if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
20.
21.
22.
23.
24.
25.
26. }
27.
28.
29.
30.
31.
32.
33.}
34.
35.}
Output:
1. Please enter a String
8.
int maxCount = 1;
9.
10.
11. for(int i = 0, j = 0; i < [Link]() - 1; i = j){
12.
13.
int count = 1;
while (++j < [Link]() && array[i] == array[j]) {
14.
15.
count++;
}
16.
17. if (count > maxCount) {
18.
maxCount = count;
19.
maxChar = array[i];
20. }
21.
22. }
23.
24.
25. }
26.
27. public static void main(String[] args) {
28.
29. String str1=MaxOccuredChar("instanceofjava");
30. [Link](str1);
31.
32. String str2=MaxOccuredChar("aaaabbbccc");
33. [Link](str2);
34.
35. String str3=MaxOccuredChar("ssssiiinnn");
36. [Link](str3);
37.
38. String str4=MaxOccuredChar("jaaaavvvvvvvvaaaaaaaaaa");
39. [Link](str4);
40.
41.}
42.
43.}
Output:
1. i = 1
2. a = 4
3. s = 4
4. a = 10
3. class RemoveCharString{
4.
5. public static void main(String [] args){
6.
7.
8.
9.
[Link](str);
10.}
11.}
Output:
1. Jv
#2: Java Program to Replace First occurance of Specific index char in a String
1. package [Link];
2.
3. class RemoveCharString{
4.
5. public static void main(String [] args){
6.
7.
8.
9. //String result = [Link](0, index) + [Link](index+1);
10.
11. String result = [Link](0, 1) + [Link](1+1);
12. [Link](result);
13.
14.}
15.}
Output:
1. Jva
8.
str = [Link]("[0-9]","")
9.
[Link](str);
10.
11.}
12.}
Output:
1. Instanceofjava
1. package [Link];
public class primenumbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=50;
int count=0;
for(int i=1;i<=num;i++){
count=0;
for(int j=2;j<=i/2;j++){
if(i%j==0){
count++;
break;
}
}
if(count==0){
[Link](i);
}
}
}
}
1. Output:
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
4.
5. public static void main(String[] args) {
6.
7. String str="Hello world";
8. String revstring="";
9.
[Link](int i=[Link]()-1;i>=0;--i){
[Link] +=[Link](i);
12.}
13.
[Link](revstring);
15.}
16.}
[Link](revstring);
15.
[Link]([Link](str)){
[Link]("The string is Palindrome");
18.}
[Link]{
[Link]("Not Palindrome");
21.}
22.
23.}
24.}
Output:
1. The string is Palindrome
89
8.
9.
10.
11. [Link](chars);
12.
13. String sorted = new String(chars);
14. [Link](sorted);
15.}
16.
17.}
1. package [Link];
2. public class SortString {
3.
4. public static void main(String[] args) {
5.
6. String original = "edcba";
7. int j=0;
8. char temp=0;
9.
10. char[] chars = [Link]();
11.
12. for (int i = 0; i <[Link]; i++) {
13.
14.
15.
16.
if(chars[j]>chars[i]){
17.
temp=chars[i];
18.
chars[i]=chars[j];
19.
chars[j]=temp;
20.
21.
22.
23.
24.}
25.
[Link](int k=0;k<[Link];k++){
[Link](chars[k]);
28.}
29.
30.}
31.
32.}
Output:
1. abcde
[Link](largest);
[Link](index);
[Link](smallest);
[Link](small);
32.
33.}
34.
35.}
Output:
1. 120
2. 1
3. 87
4. 4
int temp=0;
[Link](int i=0;i<n;i++){
14.
[Link](int j=1;j<(n-i);j++){
16.
[Link](a[j-1]>a[j]){
18.
temp=a[j];
19. a[j]=a[j-1];
20. a[j-1]=temp;
21.
22. }
23.
24.}
25.
26.}
27.
[Link](int k=0;k<n;k++){
[Link](a[k]);
30.}
31.
32.}
33.
34.}
5.
int a=0;
6.
String name="";
7.
8.
this.a=a;
9.
[Link]=name;
10.}
11.
[Link] Employee clone() throws CloneNotSupportedException{
13.
[Link] (Employee ) [Link]();
15.
16.}
17.
[Link] static void main(String[] args) {
19.
20.
21.
22.
[Link] {
24.
25. Employee b=[Link]();
26. [Link]([Link]);
27.
28.}
29. catch (CloneNotSupportedException e1) {
30.
[Link]();
32.}
33.}
34.
35.}
Output:
1. Indhu
2. Indhu
Output:
indhu
true
1. package [Link];
2.
3. public class Pyramidshape {
4.
5.
6.
7.
int num=10;
8.
9.
10.
11.
12.
13.
14.
[Link](" ");
}
15.
16. for (int k = 1; k <= i; k++) {
17.
[Link](""+k+" ");
18. }
19.
20. for (int l =i-1; l >0; l--) {
21.
[Link](""+l+" ");
22. }
23.
24.
[Link]();
25. }
26.
27.}
Output:
1.
2.
1
121
3.
12321
4.
1234321
1. package [Link];
2. import [Link];
3.
4. public class ArmstrongNumber{
5.
6. public static void main(String args[])
7.
8.
9.
10.
11.
12.
13.
14.
n = [Link]();
15.
16.
temp = n;
17.
while( temp != 0 )
18.
19.
20.
r = temp%10;
21.
22.
temp = temp/10;
23.
24.
25.
26.
if ( n == sum )
27.
28.
else
29.
30.
31.
32.}
Output:
1. Enter a number to check if it is an Armstrong number or not
2. 153
3. 153is an Armstrong number.
Common class
package [Link];
public class Common {
int x;
boolean flag=true;
//if flag is true producer thread has to produce
// if flag is false consumer thread has to produce
synchronized public void produce(int i){
if(flag){
x=i;
[Link]("producer thread has produced "+i);
flag=false;
notify();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
[Link]();
}
}
}
package [Link];
public class ProducerThread extends Thread {
Common c;
ProducerThread(Common c){
this.c=c;
}
public void run(){
int i=0;
while(true){
i++;
[Link](i);
try {
[Link](600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
[Link]();
}
}
}
}
ConsumerThread:
package [Link];
public class ConsumerThread extends Thread {
Common c;
ConsumerThread(Common c){
this.c=c;
}
public void run(){
while(true){
int x=[Link]();
[Link]("Consumer consumes"+x);
try {
[Link](600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
[Link]();
}
}
}
}
ProducerConsumerTest:
package [Link];
public class ProducerConsumerTest {
public static void main(String args[]){
Common c= new Common();
ProducerThread pt=new ProducerThread(c);
ConsumerThread ct= new ConsumerThread(c);
[Link]();
[Link]();
}
}
Output:
producer thread has produced
Consumer consumed 1
producer thread has produced
Consumer consumed 2
producer thread has produced
Consumer consumed 3
producer thread has produced
Consumer consumed 4
producer thread has produced
Consumer consumed 5
producer thread has produced
Consumer consumed 6
1
2
3
4
5
6
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class RemoveDupArray {
9.
10. public static void main(String[] args) {
11.
12. // A string array with duplicate values
13.
String[] data = { "E", "C", "B", "E", "A", "B", "E", "D", "B", "A" };
14.
[Link]("Original array
: " + [Link](data));
16.
17. List<String> list = [Link](data);
18. Set<String> set = new HashSet<String>(list);
19.
20. [Link]("After removing duplicates: ");
21. String[] resarray= new String[[Link]()];
22.
[Link](resarray);
23.
24. for (String ele: resarray) {
25.
26. [Link](ele + ", ");
27.
28. }
29.
30.}
31.
32.}
1. OutPut:
2. Original array
: [E, C, B, E, A, B, E, D, B, A]
1.
2.
package [Link];
3.
4. public class ByteArrayToString {
5.
/*
6.
7.
*/
8.
9.
10.
11.
12.
13.
[Link](value);
14.
15.
16.
17.
18.
19.
20.
[Link]();
}
21.}
Output:
1. NICE
package [Link];
/*
5.
6.
*/
7.
8.
9.
10.
11.
12.
13.
14.
[Link](byteData);
15.
16.
17.
18.}
Output:
1. [B@3b26456a
second one is by using recursive method call lets see these two programs
Solution #1:
1. package [Link];
2.
3. class Demo{
4.
5. public static void main(String args[]) {
6.
7.
[Link](1);
8.
[Link](2);
9.
[Link](3);
10.
[Link](4);
11.
[Link](5);
12.
[Link](6);
13.
[Link](7);
14.
[Link](8);
15.
[Link](9);
16.
[Link](10);
17.
18.}
19.
20.}
Output:
1. 1
2. 2
3.
4.
5. 5
6. 6
7. 7
8. 8
9. 9
10.10
Solution #2
1. package [Link];
2. class PrintDemo{
3.
4. public static void recursivefun(int n)
5. {
6.
7.
8.
9.
10.
[Link](n);
recursivefun(n+1); }
11.}
12.
[Link] static void main(String args[])
14.{
15.
[Link](1);
17.
18. }
19.
20.}
Output:
1. 1
2. 2
3.
4.
5. 5
6. 6
7. 7
8. 8
9. 9
10.10
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
rows = [Link]();
18.
cols = [Link]();
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
first[c][d] = [Link]();
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
[Link](sum[c][d]+"\t");
46.
[Link]();
47.
48.
}
}
49.
50. }
51.
Output:
1. Please Enter number of rows and columns
2.
3. 3
4. 3
5.
6. Please Enter elements of first matrix
7.
8. 1 1 1
9. 1 1 1
10.1 1 1
11.
[Link] Enter elements of second matrix
13.
14.2 2 2
15.2 2 2
16.2 2 2
17.
[Link] of entered matrices:19.
20.3
21.3
22.3
8.
9.
10.
int m, n, p, q, sum = 0, c, d, k;
11.
12.
13.
14.
15.
16.
m = [Link]();
17.
n = [Link]();
18.
19.
20.
21.
22.
23.
24.
25.
first[c][d] = [Link]();
26.
27.
28.
29.
p = [Link]();
30.
q = [Link]();
31.
32.
33.
if ( n != p )
[Link]("Matrices with entered orders can't be multiplied
with each other.");
34.
else
35.
36.
37.
38.
39.
40.
41.
42.
second[c][d] = [Link]();
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
multiply[c][d] = sum;
53.
sum = 0;
54.
55.
56.
57.
58.
59.
60.
61.
62.
[Link](multiply[c][d]+"\t");
63.
[Link]("\n");
64.
65.
66.
67.
68.
69.}
OutPut:
1. Enter the number of rows and columns of first matrix
2.
3. 2 2
4.
5. Enter the elements of first matrix
6.
7. 2 2
8. 2 3
9.
22.5
Checking the number even or odd program is very easy. Anybody can solve
this but there is a condition we need to see.
Before going to actual program lets see how to check a number is even or
odd by using modulus and division operators.
7.
8.
int number;
9.
10.
11.
12.
number=[Link]();
13.
14.
if((number % 2)==0){
15.
16.
17.
18.
19.
20.}
21.}
Output:
7.
8.
int number;
9.
10.
11.
12.
number=[Link]();
13.
14.
if((number / 2)*2==number){
15.
16.
17.
18.
19.
20.}
21.}
Output:
1. Enter a number to check even or odd
2. 46
3. 46 is Even Number
The above two programs will check number is even or odd and displays
result.
Now we need to write a program to check even or odd without using modulus
and division operators.
Yes using Bit Wise AND "&" operator we can check a number is even or odd.
Before starting our program lets see how this bit wise AND "&" operator will
work.
Bitwise Operators :
OR :
XOR: 0 | 1= 1 , 1 | 0=1
NOT : !0=1
010 : 2
011 : 3
-----010 : 2
------
010 :2
001 :1
----000 :0
-----
From above example we can say that on every even number & 1 gives 0.
0 | 1= 1 , 1 | 0=1 , 1| 1= 1
1. package instanceofjava;
2. import [Link];
3.
4. public class EvenorOdd {
5.
6. public static void main(String []args )
7.
8.
int number;
9.
10.
11.
12.
number=[Link]();
13.
14.
15.
16.
}else{
17.
18.
19.
20.}
21.}
Output:
1. Enter a number to check even or odd
2. 9
3. 9 is Odd Number
We can check even or odd by using shift operators also may be it is not a
better solution but trying to cover alternative.
Lets see how shift operators will work
010
----001
By this we can say if a (number >>1)<<1 gives same then that is even
number. result=input
7.
8.
int number;
9.
10.
11.
12.
number=[Link]();
13.
14.
15.
16.
}else{
17.
18.
19.
20.}
21.}
Output:
1. Enter a number to check even or odd
2. 64
3. 64 is Even Number
Here is the another solution for this.
1. package instanceofjava;
2. import [Link];
3.
4. class EvenOrOddDemo
5. {
6.
7. public static void main(String[] args)
8. {
9.
[Link] sc=new Scanner([Link]);
11.
[Link]("Enter a number to check whether it is even or odd
without using Modulus
[Link] Division: ");
14.
[Link] n=[Link]([Link]());
[Link] f=(float)n/(float)2;
[Link] d=(int)f*2;
18.
[Link](d==n)
[Link](n+" is a even number");
[Link]
[Link](n+" is a odd number");
23.}
24.
25.}
Output:
1. Enter a number to check whether it is even or odd without using Modulus and
Division
2. 4
3. 4 is Even Number
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class Mapiterator {
9.
[Link] static void main(String[] args) {
11.
[Link] map=new HashMap();
13.
[Link](1, "indhu");
[Link]("d", "sindhu");
[Link]("3", "swathi");
17.
[Link](![Link]()){
19.
[Link] it=[Link]().iterator();
21.
[Link]([Link]()){
23.
[Link] obj=(Entry) [Link]();
[Link]([Link]());
26.
27.}
28.
29.}
30.
31.}
32.
33.}
Output:
1. swathi
2. indhu
3. sindhu
Descending order:
1. package [Link];
2. import [Link];
3.
import [Link];
4. import [Link];
5.
9.
10.
11.
12.
13.
14.
[Link](1);
15.
[Link](2);
16.
[Link](3);
17.
[Link](4);
18.
[Link](5);
19.
[Link](6);
20.
21.
/*
22.
23.
24.
*/
25.
26.
27.
28.
29.
30.
31.
/*
32.
use
33.
34.
35.
*/
36.
[Link](arrayList,comparator);
37.
38.
39.
40.
41.
1. OutPut:
2. Before sorting : [1, 2, 3, 4, 5, 6]
3. After sorting : [6, 5, 4, 3, 2, 1]
int id;
7.
String name;
8.
9.
10.
11. [Link]=id;
12. [Link]=name;
13.
14. }
15.
[Link] int getId() {
17.
[Link] id;
19.
20.}
21.
22. public void setId(int id) {
23. [Link] = id;
24. }
25.
26. public String getName() {
27. return name;
28. }
29.
[Link] void setName(String name) {
31.
32. [Link] = name;
33.
34.}
35.
36.}
@Override
5.
6.
7.
8.
9.
return 1;
} else {
10.
11.
return -1;
}
12.
13.}
14.
15.}
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. import [Link].*;
8.
9. class Main{
10.
[Link] static void main(String args[]){
12.
[Link] al=new ArrayList();
14.
[Link](new Employee(101,"Indhu"));
[Link](new Employee(106,"Sindhu"));
[Link](new Employee(105,"Swathi"));
18.
[Link](al,MyEmpComp );
20.
[Link] itr=[Link]();
22.
[Link]([Link]()){
24.
[Link] st=(Employee)[Link]();
[Link]([Link] +" "+[Link] );
27.
28. }
29.
30.
31.}
32.
33.
34.}
Output:
1. Indhu
2. Swathi
3. Sindhu
Method overloading:
Defining multiple methods with same name and with different arguments is
known as method overloading.
Multiple methods with same name and different arguments so compile time
itself we can tell which method is going to get executed based on method
call.
By this we can define multiple main methods in our class with different
arguments but only default main method will be called by the JVM remaining
methods we need to call explicitly.
Lets see an example java program which explains static method overloading.
1. class StaticMethodOverloading{
2.
3. public static void staticMethod(){
4.
5. [Link]("staticMethod(): Zero arguments");
6.
7. }
8.
9. public static void staticMethod(int a){
10.
[Link]("staticMethod(int a): one argument");
12.
13.}
14.
[Link] static void staticMethod(String str, int x){
16.
[Link]("staticMethod(String str, int x): two arguments");
18.
19.}
20.
[Link] static void main(String []args){
22.
23. [Link]();
24. [Link](12);
25. [Link]("Static method overloading",10);
26.
27.}
28.}
Output:
1. staticMethod(): Zero arguments
2. staticMethod(int a): one argument
3. staticMethod(String str, int x): two arguments
Static means class level if we declare any data or method as static then
those data(variables) and methods belongs to that class at class level.
Static variables and static methods belongs to class level.
Static methods are not the part of objects state . Belongs to class
Defining the super class method in sub class with same signature.
Even though in inheritance all properties of supers class can access in sub
class we have an option of overriding super class methods in sub class known
as method overriding.
1. class SuperClassDemo{
2.
3. public void instanceMethod(){
4.
5. [Link]("SuperClassDemo instanceMethodcalled");
6.
7. }
8.
9. }
13. // here no need to create object to call a static method please note that.
14.
15. [Link]();
16. [Link]();
17. [Link]();
18.
19.}
20.}
Output
1. SuperClassDemo instanceMethodcalled
2. SubClassDemo instanceMethodcalled
3. SubClassDemo instanceMethodcalled
1. class SuperClassDemo{
2.
3. public static void staticMethod(){
4.
5. [Link]("SuperClassDemo staticMethod called");
6.
7. }
8.
9. }
Output
1. SuperClassDemo staticMethod called
2. SuperClassDemo staticMethod called
3. SubClassDemo staticMethod called
Based on the type of data to be returned will mention it as int , char , float
double etc as return type in method signature and return statement should
be the last statement of the method body.
1. package [Link];
2. class sample{
3.
4. public void add(){
5.
6. int a=40;
7. int b=50;
8. int c=a+b;
9. [Link](c);
10.
11.}
12.
[Link] static void main(String args[]) // ->method prototype.
14.
15.
[Link]();
18.
19.
20.
21.}
13.
[Link] obj= new sample();
15.
[Link](13,24);
16.
17.
18.
19.}
1. package [Link];
2. class sample{
3.
4. public int add(){
5. int a=40;
6. int b=50;
7. int c=a+b;
8. return c;
9. }
10.
[Link] static void main(String args[]) // ->method prototype.
12.
13.
[Link] obj= new sample();
15.
int x=[Link]();
16.
[Link](x);
17.
18.
19.}
1. package [Link];
2. class sample{
3.
4. public int add(int a, int b){
5.
6. int c=a+b;
7. return c;
8. }
9.
12.
[Link] obj= new sample();
14.
15.
int x=[Link](1,2);
16.
[Link](x);
17.
18.
19.}
Inheritance:
Getting the properties from one class object to another class object is known
as inheritance.
Two types of inheritance
Getting the properties from one class object to another with level wise and
with some priorities is known as multilevel inheritance.
Getting the properties from one class object to another class object with
same priority is known as multiple inheritance
Read this:
Why Java does not supports multiple inheritance
28. [Link]("a="obj.a);
29.
30.}
31.}
Output:
1. print method of super class A
2. 10
In above program super class and sub class is there and sub class extending
super class.
But we created object for super class so we can call only super class methods
on that object.
If we create sub class object we can call super class and sub class methods
on that object now we can able to access super class A methods only.
So by creating super class object we can call only super class methods
16.
17. [Link]("show method of sub class B");
18.
19.}
[Link] static void main(String[] args){
21.
22.B obj= new B();
[Link].a=10;
24.
[Link]();
[Link]();
27.
28. [Link]("a="obj.a);
29.
30.}
31.}
Output:
1. print method of super class A
2. show method of sub class B
3. 10
Above program shows sub class object using super class methods and
variables as we said in inheritance concept all super class members can
accessed by the sub class means all super class members are available to
sub class if sub class extending super class.
So whenever we create object of sub class it will call sub class constructor
and from sub class constructor super class constructor will be called so
memory will be allocated to all super class non static member and sub class
non static members.
[Link]();
So by creating sub class object we can call both super class methods and sub
class methods.
28. [Link]("a="obj.a);
29.
30.}
31.}
Output:
1. print method of super class A
2. 10
Yes its possible to call sub class methods using super class by type casting to
sub class object .
By type casting super class object to sub class object we can access all
corresponding sub class and all super class methods on that reference.
[Link] B extends A{
14.
[Link] void show(){
16.
17. [Link]("show method of sub class B");
18.
19.}
[Link] static void main(String[] args){
21.
22.A obj= new B();
[Link].a=10;
24.
[Link]();
26.//[Link](); compile time error
27.((B)obj).show(); // works fine
28.
29.
30. [Link]("a="obj.a);
31.
32.}
33.}
Output:
1. print method of super class A
2. show method of sub class B
3. 10
1. Class A{
2.
3.
4.
int a;
private int b;
5.
6. public void print(){
7.
8. [Link]("print method of super class A");
9.
10.}
11.
[Link] void add(){
13.
[Link]("add method of super class A");
15.
16.}
17.}
[Link] B extends A{
19.
[Link] void show(){
21.
22. [Link]("show method of sub class B");
23.
24.}
[Link] static void main(String[] args){
26.
Output:
1. print method of super class A
2. show method of sub class B
3. 30
From the above program we can say super class private members are not
accessible to sub class.
lets see what will happen if we try to override a method of super class?
Sorry if we are unable to access super class private methods then there
should not be a questions of overriding that method right?
Yes private methods of super class can not be overridden in sub class.
Even if we try to override same method of super class that will became a sub
class own method not overridden method.
1. Class A{
2.
3.
4.
5.
int a;
private int b;
Output:
1. add method of sub class B
2. 30
1. Class A{
2.
3.
4.
int a;
private int b;
5.
6. private void add(){
7.
8. [Link]("add method of super class A");
9.
10.}
11.}
[Link] B extends A{
13. //@override
[Link] void add(){// if we place @override annotation compile time error will
come here
15.
16. [Link]("add method of sub class B");
17.
18.}
[Link] static void main(String[] args){
20.
21.B obj= new B();
[Link].a=30;
23.
[Link]();
25.
26.
27. [Link]("a="obj.a);
28.
29.}
30.}
Output:
1. add method of sub class B
2. 30