Anda di halaman 1dari 89

Java has well-defined rules for specifying the order in which the operators in an expression are

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.

Precedence and associativity of Java operators.


The table below shows all Java operators from highest to lowest precedence, along
with their associativity. Most programmers do not memorize them all, and even
those that do still use parentheses for clarity.

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

=
*=
&=
<<=

+=
-=
/=
%=
^=
|=
>>= >>>=

1. What is the output of following program?


1. package com.instanceofjava;
2.
3. public class B{
4.
5.

B b= new B();

6.
7.

public int show(){

8.
9.

return (true ? null : 0);


}

10.
11. public static void main(String[] args) {
12.
13.

B b= new B();

14.

b.show();

15.

16.
17. }

1. Exception in thread "main" java.lang.StackOverflowError


2. at com.instanceofjava.B.<init>(B.java:3)
3. at com.instanceofjava.B.<init>(B.java:5)
4. at com.instanceofjava.B.<init>(B.java:5)
Exaplanation:

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

Exception in thread "main" java.lang.StackOverflowError

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

3. What is the output of following program?


1. package com.instanceofjava;
2.
3. public class A{
4.
5.
6.

static int a = 1111;

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.

System.out.println(a);

19.
20.
21.
22. }
Ans: 2

4. What is the output of following program?


1. package com.instanceofjava;
2.
3. public class A{
4.
5.
6.

int GetValue()

7.

8.
9.

return (true ? null : 0);


}

10.
11. public static void main(String[] args) {
12.
13. A obj= new A();
14.
15.

obj.GetValue();

16.
17.

18.
19. }
1. Exception in thread "main" java.lang.NullPointerException
5. What is the output of following program?
1. package com.instanceofjava;
2.
3. public class A{
4.
5.
6.

public static void main(String[] args) {

7.
8.

Integer i1 = 128;

9.
10.

Integer i2 = 128;

11.
12.

System.out.println(i1 == i2);

13.
14.

Integer i3 = 127;

15.

Integer i4 = 127;

16.
17.

System.out.println(i3 == i4);

18.
19.

20.
21. }

1. false
2. true
6. What is the output of following program?
1. package com.instanceofjava;
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. }

1. Compile time Error:The method method(Integer) of type B must override or implement a


supertype method

7. Which line will throw compile time error? 8 or 9?


1. package com.instanceofjava;
2. class A
3. {
4.
5. public static void main(String [] args)
6. {
7.
8.

Integer i = new Integer(null);

9.

String s = new String(null);

10.

11. }
12.
13. }

1. Compile time Error at line number 9:The constructor String(String) is ambiguous

9.What is the output of following program?


1. package com.instanceofjava;
2. class A
3. {
4.
5. static int method1(int i)
6. {
7. return method2(i *= 11);
8. }
9.
10. static int method2(int i)
11. {
12. return method3(i /= 11);
13. }
14.
15. static int method3(int i)
16. {
17. return method4(i -= 11);
18. }
19.
20. static int method4(int i)
21. {

22. return i += 11;


23. }
24. public static void main(String [] args)
25. {
26.
27. System.out.println(method1(11));
28.
29. }
30.
31. }

1. 11

10.What is the output of following program?


1. package com.instanceofjava;
2. class A
3. {
4.
5. public static void main(String [] args)
6. {
7.
8.

System.out.println(null);

9.
10. }
11.
12. }

1. Compilation Error

What happens When System.out.println(null)?


Compilation Error -This is because you can pass an Object or a String or char[]. Since null
can fit in both, the compiler doesn't know which method to use, leading to compile
error.
Method Overloading:
1.public void prinltln(String str) { }
2.public void prinltln(char[] ch){ }
3.public void prinltln(Object ch){
It seems the call System.out.print(null) is ambiguous to compiler because print(null) here
will find the two best specific matches i.e. print(String) and print(char[]) . So compiler is unable
to determine which method to call here .
Compilation Error:
System.out.println(null)
Compile Fine:
System.out.println((String)null);//null
System.out.println((char[])null);
System.out.println((Object)null);//null
It's the compiler type-checking the parameters of the method call.
But here we need to know one more thing System.out.println((char[])null); will compile fine
but at run time will throw runtime exception.

STRINGS CLASS EXAMPLES


1.Reverse a String Without using String API?
1. package com.instaceofjava;
2.
3. public class ReverseString {
4.
5. public static void main(String[] args) {
6.
7. String str="Hello world";
8. String revstring="";

9.
10. for(int i=str.length()-1;i>=0;--i){
11. revstring +=str.charAt(i);
12. }
13.
14. System.out.println(revstring);
15. }
16. }

Program:
output: dlrow olleH.
2)Sorting the String without using String API?
1. package com.Instanceofjava;
2.
3. public class SortString {
4.
5.

public static void main(String[] args) {

6.
7.

String original = "edcba";

8.

int j=0;

9.

char temp=0;

10.
11.

char[] chars = original.toCharArray();

12.

for (int i = 0; i <chars.length; i++) {

13.

for ( j = 0; j < chars.length; j++) {

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<chars.length;k++){

23.

System.out.println(chars[k]);

24.

25.
26. }
27. }
program:
output:abcde.
3.Sort the String with using String API?
program:
1. package com.instanceofjava;
2.
3.

public class SortString {

4.
5.

public static void main(String[] args) {

6.

String original = "edcba";

7.
8.

char[] chars = original.toCharArray();

9.

Arrays.sort(chars);

10.
11.

String sorted = new String(chars);

12.

System.out.println(sorted);

13.
14. }

15. }

OutPut:abcde
4.Check String is palindrome or not?
program:
Solution #1:
1. package com.instaceofjava;
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=str.length()-1;i>=0;--i){
11. revstring +=str.charAt(i);
12. }
13.
14. System.out.println(revstring);
15.
16. if(revstring.equalsIgnoreCase(str)){
17. System.out.println("The string is Palindrome");
18. }
19. else{
20. System.out.println("Not Palindrome");
21. }

22.
23. }
24.
25. }

Output:
The string is Palindrome
Solution #2:
1. package com.instaceofjava;
2.
3.

import java.util.Scanner;

4.
5.

public class Palindrome {

6.
7. public static void main(String[] args)
8. {
9.
10. Scanner in = new Scanner(System.in);
11.
12. System.out.println("Enter a string");
13. String str=in.nextLine();
14.
15. StringBuffer strone=new StringBuffer(str);
16. StringBuffer strtwo=new StringBuffer(strone);
17.
18. strone.reverse();
19.
20. System.out.println("Orginal String ="+strtwo);

21. System.out.println("After Reverse ="+strone);


22.
23. if(String.valueOf(strone).compareTo(String.valueOf(strtwo))==0)
24.

System.out.println("Result:Palindrome");

25.

else

26.

System.out.println("Result:Not Palindrome");

27.
28.

29.
30. }

Output:
Enter a string
MOOM
Orginal String =MOOM
After Reverse =MOOM
Result:Palindrome
5.Program to Check given number is palindrome or not?
Program:
1.
2.

package com.instaceofjava;

3. import java.util.Scanner;
4.
5. public class Palindrome {
6.
7. public static void main(String[] args)
8. {
9.
10. System.out.println("Please Enter a number : ");

11.

int givennumber = new Scanner(System.in).nextInt();

12.

int number=givennumber;

13.

int reverse=0;

14.

while (number != 0) {

15.

int remainder = number % 10;

16.

reverse = reverse * 10 + remainder;

17.

number = number / 10;

18.

19. if(givennumber == reverse)


20.

System.out.println("Result:Palindrome");

21.

else

22.

System.out.println("Result:Not Palindrome");

23.

24.
25. }
Output:
Please Enter a number :
535
Result:Palindrome.

Java program To Count the number of words in a


String

1. package com.javatutorial;
2.
3. public class CountNumberofWords {
4.
5.

public static void main(String[] args) {

6.
7. String s="";
8. int count=0;
9.
10.Scanner in = new Scanner(System.in);
11.System.out.println("Please enter a String");
12. s=in.nextLine();
13.
14.char ch[]= new char[s.length()];
15.
16.for(int i=0;i<s.length();i++)
17.{
18.
19.

ch[i]= s.charAt(i);

20.
21.
22.

if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )


count++;

23.
24.}
25.System.out.println("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

Java Program to Count the number of occurrences


of a char in a String?
Solution #1:
1. package com.javatutorial;
2.
3. import java.util.Scanner;
4.
5. public class CountNumberofChars {
6.
7.

public static void main(String[] args) {

8.
9.

String str = "";

10.
11. Scanner in= new Scanner(System.in);
12. System.out.println("Please enter a String");
13.
14. str=in.nextLine();
15.
16. System.out.println("Please enter a Character");
17. String chr=in.next();
18.
19. int charCount = str.length() - str.replaceAll("a", "").length();
20.
21. System.out.println("Number of occurances of given character:"+charCount);
22.
23.}
24.
25.}

Output:

1. Please enter a String


2. Java
3. Please enter a Character
4. a
5. Number of occurances of given character:2

Solution #2:
1. package com.javatutorial;
2.
3. import java.util.Scanner;
4.
5. public class CountNumberofChars {
6.
7. public static int countOccurrences(String find, String string)
8. {
9. int count = 0;
10.int indexOf = 0;
11.
12.while (indexOf > -1)
13.{
14.

indexOf = string.indexOf(find, indexOf + 1);

15.

if (indexOf > -1)

16.
17.

count++;
}

18.return count;
19. }
20.
21. public static void main(String[] args) {
22.
23. int charCount=countOccurrences("a", "Instance of Java");

24.
25. System.out.println("Number of occurances of given character:"+charCount);
26.
27.}
28.
29.}

Output:
1. Number of occurances of given character: 3

Java Program to count number of vowels in a string


Solution #1:
1. package com.javatutorial;
2.
3. public class CountNumberofVowels {
4.
5.

public static void main(String[] args) {

6.
7. System.out.println("Please enter a String");
8. Scanner in = new Scanner(System.in);
9.

String input = in.nextLine();

10.
11.

char[] Chararray = input.toCharArray();

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.

System.out.println("Number of vowels in String "+count);

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 com.javatutorial;
2.
3. public class CountNumberofVowels {
4.
5.
6.

public static void main(String[] args) {

7.

int vowels = 0, digits = 0, blanks = 0; char ch;

8.
9. System.out.println("Please enter a String");
10.Scanner in = new Scanner(System.in);
11.String testString= in.nextLine();
12.
13.
14.for(int i = 0; i < testString.length(); i ++)
15.{
16.
17. ch = testString.charAt(i);
18.
19. if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
20.
21.
22.
23.
24.
25.

ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')


vowels ++;
else if(Character.isDigit(ch))
digits ++;
else if(Character.isWhitespace(ch))
blanks ++;

26. }
27.
28.

System.out.println("Vowels : " + vowels);

29.

System.out.println("Digits : " + digits);

30.

System.out.println("Blanks : " + blanks);

31.
32.
33.}
34.
35.}
Output:
1. Please enter a String

2. vowels and consonants


3. Vowels : 6
4. Digits : 0
5. Blanks : 2

Java Program to find Max occurred character in a


string
1. package com.javatutorial;
2.
3. public class MaxOccuranceOfChar{
4.
5. public static String MaxOccuredChar(String str) {
6.
7.

char[] array = str.toCharArray();

8.

int maxCount = 1;

9.

char maxChar = array[0];

10.
11. for(int i = 0, j = 0; i < str.length() - 1; i = j){
12.
13.

int count = 1;
while (++j < str.length() && array[i] == array[j]) {

14.
15.

count++;
}

16.
17. if (count > maxCount) {
18.

maxCount = count;

19.

maxChar = array[i];

20. }
21.
22. }
23.

24.

return (maxChar + " = " + maxCount);

25. }
26.
27. public static void main(String[] args) {
28.
29. String str1=MaxOccuredChar("instanceofjava");
30. System.out.println(str1);
31.
32. String str2=MaxOccuredChar("aaaabbbccc");
33. System.out.println(str2);
34.
35. String str3=MaxOccuredChar("ssssiiinnn");
36. System.out.println(str3);
37.
38. String str4=MaxOccuredChar("jaaaavvvvvvvvaaaaaaaaaa");
39. System.out.println(str4);
40.
41.}
42.
43.}
Output:
1. i = 1
2. a = 4
3. s = 4
4. a = 10

Remove Character from string in java


#1: Java Program to Remove all occurrences of a string
1. package com.instanceofjava;
2.

3. class RemoveCharString{
4.
5. public static void main(String [] args){
6.
7.

String str = "Java";

8.

str = str.replace("a", "");

9.

System.out.println(str);

10.}
11.}
Output:
1. Jv

#2: Java Program to Replace First occurance of Specific index char in a String
1. package com.instanceofjava;
2.
3. class RemoveCharString{
4.
5. public static void main(String [] args){
6.
7.

String str = "Java";

8.
9. //String result = str.substring(0, index) + str.substring(index+1);
10.
11. String result = str.substring(0, 1) + str.substring(1+1);
12. System.out.println(result);
13.
14.}
15.}
Output:
1. Jva

#3: Java Program to Remove all Numbers from a string.


1. package com.instanceofjava;
2.
3. class RemoveNumberString{
4.
5. public static void main(String [] args){
6.
7.

String str = "Instance12ofjava143";

8.

str = str.replaceAll("[0-9]","")

9.

System.out.println(str);

10.
11.}
12.}
Output:
1. Instanceofjava

Program to print prime numbers in java

1. package com.instaceofjava;
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){
System.out.println(i);
}
}
}
}

1. Output:
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Reverse a string without using string function in


java
1. package com.instaceofjava;
2.
3. public class ReverseString {

4.
5. public static void main(String[] args) {
6.
7. String str="Hello world";
8. String revstring="";
9.
10.for(int i=str.length()-1;i>=0;--i){
11.revstring +=str.charAt(i);
12.}
13.
14.System.out.println(revstring);
15.}
16.}

Check whether string is palindrome or not


Solution #1:
1. package com.instaceofjava;
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=str.length()-1;i>=0;--i){
11.revstring +=str.charAt(i);
12.}
13.

14.System.out.println(revstring);
15.
16.if(revstring.equalsIgnoreCase(str)){
17.System.out.println("The string is Palindrome");
18.}
19.else{
20.System.out.println("Not Palindrome");
21.}
22.
23.}
24.}

Output:
1. The string is Palindrome

Reverse number program in java


1. package com.instaceofjavaforus;
public class Reversenum {
public static void main(String[] args) {
int rev=0;
int num=1234;
while(num>0){
int rem=num%10;
rev=rem+(rev*10);
num=num/10;
}
}
}

Fibonacci series using recursion in java


Posted by: instance of java Posted date: 18:40 / comment : 0
1. package com.instaceofjavaforus;
public class FibanacciRecursive {

public void fibanci(int n1,int n2){


int sum=0;
if(n1==0){
System.out.println(n1+"\n"+n2);
}
sum=n1+n2;
if(sum<=100){
System.out.println(sum);
n1=n2;
n2=sum;
fibanci(n1,n2);
}
}
public static void main(String[] args) {
FibanacciRecursive fb=new FibanacciRecursive();
fb.fibanci(0,1);
}
}
Output:
0
1
1
2
3
5
8
13
21
34
55

89

Fibonacci series without using recursion in java


Posted by: instance of java Posted date: 18:34 / comment : 0
1. package com.instaceofjava;
public class Fibanaciwithoutrecursive {
public static void main(String[] args) {
int n1=0;
int n2=1;
System.out.println(n1);
System.out.println(n2);
for(int i=0;i<=100;i++){
int sum=n1+n2;
if(sum<=100){
n1=n2;
n2=sum;
System.out.println(sum);
}
}
}

Sort the string using String Methods?


Posted by: instance of java Posted date: 18:44 / comment : 0
1. package com.instanceofjava;
2.

3. public class SortString {


4.
5. public static void main(String[] args) {
6.
7.

String original = "edcba";

8.
9.

char[] chars = original.toCharArray();

10.
11. Arrays.sort(chars);
12.
13. String sorted = new String(chars);
14. System.out.println(sorted);
15.}
16.
17.}

Sorting string without using string Methods?


Posted by: instance of java Posted date: 18:46 / comment : 0

1. package com.Instanceofjava;
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 = original.toCharArray();

11.
12. for (int i = 0; i <chars.length; i++) {
13.
14.

for ( j = 0; j < chars.length; j++) {

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.
26.for(int k=0;k<chars.length;k++){
27.System.out.println(chars[k]);
28.}
29.
30.}
31.
32.}

Output:
1. abcde

How to find largest element in an array with index


and value using array?
Posted by: instance of java Posted date: 18:58 / comment : 0
1. package com.instanceofjava;
2. public class Array {
3.
4. public static void main(String[] args) {
5.
6. int arr[]={1,120,56,78,87};
7. int largest=arr[0];
8. int smallest=arr[0];
9. int small=0;
10.int index=0;
11.
12.for(int i=1;i<arr.length;i++){
13.
14.if(arr[i]>largest){
15.
16.largest=arr[i];
17.index=i;
18.
19.}
20.else if(largest>arr[i]){
21.
22.smallest=arr[i];
23.small=i;
24.
25.}
26.}
27.

28.System.out.println(largest);
29.System.out.println(index);
30.System.out.println(smallest);
31.System.out.println(small);
32.
33.}
34.
35.}

Output:
1. 120
2. 1
3. 87
4. 4

Sort integer array using Bubble Sort in java


Posted by: instance of java Posted date: 19:02 / comment : 0
1. package com.instaceofjava;
2.
3. public class Bubblesort {
4.
5. public static void main(String[] args) {
6.
7. int a[]={23,5,6,66,1};
8.
9. int n=a.length;
10.
11.
12.

int temp=0;

13.for(int i=0;i<n;i++){
14.
15.for(int j=1;j<(n-i);j++){
16.
17.if(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.
28.for(int k=0;k<n;k++){
29.System.out.println(a[k]);
30.}
31.
32.}
33.
34.}

Object cloning in java example


Posted by: instance of java Posted date: 19:07 / comment : 0
1. package com.instanceofjava;
2.
3. public class Employee implements Cloneable {
4.

5.

int a=0;

6.

String name="";

7.

Employee (int a,String name){

8.

this.a=a;

9.

this.name=name;

10.}
11.
12.public Employee clone() throws CloneNotSupportedException{
13.
14.return (Employee ) super.clone();
15.
16.}
17.
18.public static void main(String[] args) {
19.
20.
21.

Employee e=new Employee (2,"Indhu");


System.out.println(e.name);

22.
23.try {
24.
25. Employee b=e.clone();
26. System.out.println(b.name);
27.
28.}
29. catch (CloneNotSupportedException e1) {
30.
31.e1.printStackTrace();
32.}
33.}
34.
35.}

Output:
1. Indhu
2. Indhu

write a program to create singleton class?


Posted by: instance of java Posted date: 15:50 / comment : 0
package com.instanceofjava;
public class Singleton {
static Singleton obj;
private Singleton(){
}
public static Singleton getInstance(){
if(obj!=null){
return obj;
}
else{
obj=new Singleton();
return obj;
}
}
public static void main(String[] args) {
Singleton obj=Singleton.getInstance();
Singleton obj1=Singleton.getInstance();
if(obj==obj1){
System.out.println("indhu");
}
else{
System.out.println("Sindhu");
}
System.out.println(obj==obj1);
}
}

Output:
indhu
true

Print numbers in pyramid shape


Posted by: instance of java Posted date: 14:12 / comment : 0

1. package com.instanceofjava;
2.
3. public class Pyramidshape {
4.
5.

public static void main(String[] args) {

6.
7.

int num=10;

8.
9.

for (int i = 1; i < num; i++) {

10.
11.

for (int j = 1; j<=num-i;j++) {

12.
13.
14.

System.out.print(" ");
}

15.
16. for (int k = 1; k <= i; k++) {
17.

System.out.print(""+k+" ");

18. }
19.
20. for (int l =i-1; l >0; l--) {
21.

System.out.print(""+l+" ");

22. }
23.
24.

System.out.println();

25. }
26.
27.}

Output:
1.
2.

1
121

3.

12321

4.

1234321

Check armstrong number or not


Posted by: instance of java Posted date: 20:09 / comment : 0

1. package com.instanceofjavaTutorial;
2. import java.util.Scanner;
3.
4. public class ArmstrongNumber{
5.
6. public static void main(String args[])
7.

8.
9.

int n, sum = 0, temp, r;

10.
11.

Scanner in = new Scanner(System.in);

12.
13.

System.out.println("Enter a number to check if it is an Armstrong


number or not");

14.

n = in.nextInt();

15.
16.

temp = n;

17.

while( temp != 0 )

18.

19.
20.

r = temp%10;

21.

sum = sum + r*r*r;

22.

temp = temp/10;

23.
24.

25.
26.

if ( n == sum )

27.

System.out.println(n+"is an Armstrong number.");

28.

else

29.

System.out.println(n+" is not an Armstrong number.");

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.

Producer consumer problem


Posted by: instance of java Posted date: 12:02 / comment : 0

Common class
package com.instanceofjavaforus;
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;
System.out.println("producer thread has produced "+i);
flag=false;
notify();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

synchronized public int consume(){


if(flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
flag=true;
notify();
return x;
}
}

package com.instanceofjavaforus;
public class ProducerThread extends Thread {
Common c;
ProducerThread(Common c){
this.c=c;
}
public void run(){
int i=0;
while(true){
i++;
c.produce(i);

try {
Thread.sleep(600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

ConsumerThread:
package com.instanceofjavaforus;
public class ConsumerThread extends Thread {
Common c;
ConsumerThread(Common c){
this.c=c;
}
public void run(){
while(true){
int x=c.consume();
System.out.println("Consumer consumes"+x);
try {
Thread.sleep(600);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

ProducerConsumerTest:
package com.instanceofjavaforus;
public class ProducerConsumerTest {
public static void main(String args[]){
Common c= new Common();
ProducerThread pt=new ProducerThread(c);
ConsumerThread ct= new ConsumerThread(c);
pt.start();
ct.start();
}
}
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

Remove duplicates from an array java


Posted by: instance of java Posted date: 11:09 / comment : 0

Removing duplicate elements form an array using collections:


1. package com.instanceofjavaTutorial;
2.

3. import java.util.Arrays;
4. import java.util.HashSet;
5. import java.util.List;
6. import java.util.Set;
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.
15.System.out.println("Original array

: " + Arrays.toString(data));

16.
17. List<String> list = Arrays.asList(data);
18. Set<String> set = new HashSet<String>(list);
19.
20. System.out.print("After removing duplicates: ");
21. String[] resarray= new String[set.size()];
22.

set.toArray(resarray);

23.
24. for (String ele: resarray) {
25.
26. System.out.print(ele + ", ");
27.
28. }
29.
30.}
31.
32.}

1. OutPut:
2. Original array

: [E, C, B, E, A, B, E, D, B, A]

After removing duplicates: D, E, A, B, C

Convert Byte Array to String


Posted by: instance of java Posted date: 09:01 / comment : 2

1.
2.

To convert byte array to string we have a constructor in String class which is


taking byte array as an argument.
So just we need to pass byte array object to string as argument while
creating String class object.

package com.instanceofjavaforus;

3.
4. public class ByteArrayToString {
5.

/*

6.

* This method converts a byte array to a String object.

7.

*/

8.
9.

public static void convertByteArrayToString() {

10.
11.

byte[] byteArray = new byte[] {78,73, 67,69};

12.

String value = new String(byteArray);

13.

System.out.println(value);

14.
15.

16.
17.

public static void main(String[] args) {

18.
19.
20.

ByteArrayToString.convertByteArrayToString();
}

21.}

Output:

1. NICE

Convert String to Byte Array:


1.
2.

package com.instanceofjava;

3. public class StringTOByteArray{


4.

/*

5.

* This example shows how to convert a String object to byte array.

6.

*/

7.
8.

public static void main(String[] args) {

9.
10.

String data = "Instance of java";

11.
12.

byte[] byteData = data.getBytes();

13.
14.

System.out.println(byteData);

15.
16.
17.
18.}

Output:

1. [B@3b26456a

Print 1 to 10 without using loop in java?


Posted by: instance of java Posted date: 15:01 / comment : 0

Basically to display numbers from 1 to 10 or a series we will use for , while or


do while loop
So here is the programs to do same thing without using loop.

This is possible in two ways

First one is to display by printing all those things using system.out.println.

second one is by using recursive method call lets see these two programs

Solution #1:

1. package com.instanceofjavaTutorial;
2.
3. class Demo{
4.
5. public static void main(String args[]) {
6.
7.

System.out.println(1);

8.

System.out.println(2);

9.

System.out.println(3);

10.

System.out.println(4);

11.

System.out.println(5);

12.

System.out.println(6);

13.

System.out.println(7);

14.

System.out.println(8);

15.

System.out.println(9);

16.

System.out.println(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 com.instanceofjavaTutorial;
2. class PrintDemo{
3.
4. public static void recursivefun(int n)
5. {
6.
7.

if(n <= 10) {

8.
9.
10.

System.out.println(n);
recursivefun(n+1); }

11.}
12.
13.public static void main(String args[])

14.{
15.
16.recursivefun(1);
17.
18. }
19.
20.}

Output:
1. 1
2. 2
3.

4.

5. 5
6. 6
7. 7
8. 8
9. 9
10.10

add two matrices


Posted by: instance of java Posted date: 20:48 / comment : 0
1. package com.instanceofjava;
2.
3. import java.util.Scanner;
4.
5. class Add2Matrix
6. {
7.

8.

public static void main(String args[])

9.

10.
11.

int rows, cols, c, d;

12.
13.

Scanner in = new Scanner(System.in);

14.
15.

System.out.println("Please Enter number of rows and columns");

16.
17.

rows = in.nextInt();

18.

cols = in.nextInt();

19.
20.

int first[][] = new int[rows][cols];

21.

int second[][] = new int[rows][cols];

22.

int sum[][] = new int[rows][cols];

23.
24.

System.out.println("Please Enter elements of first matrix");

25.
26.

for ( c = 0 ; c < rows ; c++ )

27.

for ( d = 0 ; d < cols ; d++ )

28.

first[c][d] = in.nextInt();

29.
30.

System.out.println("Please Enter elements of second matrix");

31.
32.
33.
34.

for ( c = 0 ; c < rows ; c++ )


for ( d = 0 ; d < cols ; d++ )
second[c][d] = in.nextInt();

35.
36.
37.

for ( c = 0 ; c < rows ; c++ )


for ( d = 0 ; d < cols ; d++ )

38.

sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to


subtract matrices

39.
40.

System.out.println("Sum of entered matrices:-");

41.
42.

for ( c = 0 ; c < rows ; c++ )

43.

44.

for ( d = 0 ; d < cols ; d++ )

45.

System.out.print(sum[c][d]+"\t");

46.

System.out.println();

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.
12.Please Enter elements of second matrix
13.
14.2 2 2

15.2 2 2
16.2 2 2
17.
18.Sum of entered matrices:19.
20.3

21.3

22.3

Multiply two matrices


Posted by: instance of java Posted date: 21:21 / comment : 0
1. package com.instanceofjava;
2.
3. import java.util.Scanner;
4.
5. class Multiply2Matrices{
6.
7.

public static void main(String args[])

8.

9.
10.

int m, n, p, q, sum = 0, c, d, k;

11.
12.

Scanner in = new Scanner(System.in);

13.
14.

System.out.println("Enter the number of rows and columns of first


matrix");

15.
16.

m = in.nextInt();

17.

n = in.nextInt();

18.
19.
20.

int first[][] = new int[m][n];

21.

System.out.println("Enter the elements of first matrix");

22.
23.

for ( c = 0 ; c < m ; c++ )

24.

for ( d = 0 ; d < n ; d++ )

25.

first[c][d] = in.nextInt();

26.
27.

System.out.println("Enter the number of rows and columns of second


matrix");

28.
29.

p = in.nextInt();

30.

q = in.nextInt();

31.
32.
33.

if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied
with each other.");

34.

else

35.

36.

int second[][] = new int[p][q];

37.

int multiply[][] = new int[m][q];

38.

System.out.println("Enter the elements of second matrix");

39.
40.

for ( c = 0 ; c < p ; c++ )

41.

for ( d = 0 ; d < q ; d++ )

42.

second[c][d] = in.nextInt();

43.
44.

for ( c = 0 ; c < m ; c++ )

45.

46.

for ( d = 0 ; d < q ; d++ )

47.

48.

for ( k = 0 ; k < p ; k++ )

49.

50.

sum = sum + first[c][k]*second[k][d];

51.

52.

multiply[c][d] = sum;

53.

sum = 0;

54.

55.

56.
57.

System.out.println("Multiplication of entered matrices:-");

58.
59.

for ( c = 0 ; c < m ; c++ )

60.

61.

for ( d = 0 ; d < q ; d++ )

62.

System.out.print(multiply[c][d]+"\t");

63.

System.out.print("\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.

10.Enter the number of rows and columns of second matrix


11.
12.2 2
13.
14.Enter the elements of second matrix
15.
16.1 1
17.1 1
18.
19.Multiplication of entered matrices:20.
21.4

22.5

Program Check even or odd without using modulus


and division operators
Posted by: instance of java Posted date: 14:49 / comment : 3

Checking the number even or odd program is very easy. Anybody can solve
this but there is a condition we need to see.

When we get this question in interview "write a program to check given


number is even or odd" always continues with "without using modulus and
division operators".

Before going to actual program lets see how to check a number is even or
odd by using modulus and division operators.

Program to check number is even or odd by using modulus "%" operator


1. package instanceofjava;
2. import java.util.Scanner;
3.
4. public class EvenorOdd {
5.
6. public static void main(String []args )

7.
8.

int number;

9.

Scanner in= new Scanner(System.in);

10.
11.

System.out.println("Enter a number to check even or odd");

12.

number=in.nextInt();

13.
14.

if((number % 2)==0){

15.
16.

System.out.println(+number+" is Even number");


}else{

17.
18.
19.
20.}
21.}

Output:

System.out.println(+number+" is Odd Number");


}

1. Enter a number to check even or odd


2. 37
3. 37 is Odd Number

Program to check number is even or odd by using division "/" operator


1. package instanceofjava;
2. import java.util.Scanner;
3.
4. public class EvenorOdd {
5.
6. public static void main(String []args )

7.
8.

int number;

9.

Scanner in= new Scanner(System.in);

10.
11.

System.out.println("Enter a number to check even or odd");

12.

number=in.nextInt();

13.
14.

if((number / 2)*2==number){

15.
16.

System.out.println(+number+" is Even number");


}else{

17.
18.

System.out.println(+number+" is Odd Number");


}

19.
20.}
21.}

Output:
1. Enter a number to check even or odd
2. 46
3. 46 is Even Number

Without using modulus and division operators:

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.

It is very simple if you know about operators including "BIT WISE".

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 :

Bit wise operators will work on bits at a time.


AND : 1 & 1=1

OR :

XOR: 0 | 1= 1 , 1 | 0=1

NOT : !0=1

Take two number 2 and 3

010 : 2
011 : 3
-----010 : 2

------

Take two numbers 2 and 1

010 :2
001 :1
----000 :0
-----

From above example we can say that on every even number & 1 gives 0.

So this is our logic to be implemented in our program if "Number & 1==0"


then its even number.

0 | 1= 1 , 1 | 0=1 , 1| 1= 1

Program to check number is even or odd by using "&" operator

1. package instanceofjava;
2. import java.util.Scanner;
3.
4. public class EvenorOdd {
5.
6. public static void main(String []args )

7.
8.

int number;

9.

Scanner in= new Scanner(System.in);

10.
11.

System.out.println("Enter a number to check even or odd");

12.

number=in.nextInt();

13.
14.

if((number & 1)==0){

15.

System.out.println(+number+" is Even number");

16.

}else{

17.

System.out.println(+number+" is Odd Number");

18.

19.
20.}
21.}

Output:
1. Enter a number to check even or odd
2. 9
3. 9 is Odd Number

Using Shift Operators:

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

Lets do this 2 >> 1

2 means 010 so now we need to shift right side by 1 place

010
----001

Here we added one "0" to the left side to shift right

So the value became 1

Now will try left shift 001 >> 1


001
---010

010<<1=001(1) and 001 >> 001=010(2)

By this we can say if a (number >>1)<<1 gives same then that is even
number. result=input

Lets check for odd number 3

011>>1=001 which is 1 and 001<<1=010 which is 2 so (3>>1)>>1=2 so


result!=input

Program to check number is even or odd by using Shift operator


1. package instanceofjava;
2. import java.util.Scanner;
3.
4. public class EvenorOdd {
5.
6. public static void main(String []args )

7.
8.

int number;

9.

Scanner in= new Scanner(System.in);

10.
11.

System.out.println("Enter a number to check even or odd");

12.

number=in.nextInt();

13.
14.
15.

if( ( number >> 1) <<1==number){


System.out.println(+number+" is Even number");

16.

}else{

17.
18.

System.out.println(+number+" is Odd Number");


}

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 java.util.Scanner;
3.
4. class EvenOrOddDemo
5. {
6.
7. public static void main(String[] args)
8. {
9.
10.Scanner sc=new Scanner(System.in);
11.
12.System.out.println("Enter a number to check whether it is even or odd
without using Modulus
13.and Division: ");
14.
15.int n=Integer.parseInt(sc.next());
16.float f=(float)n/(float)2;
17.int d=(int)f*2;
18.
19.if(d==n)
20.System.out.println(n+" is a even number");

21.else
22.System.out.println(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

How to Add elements to hash map and Display?


Posted by: instance of java Posted date: 18:54 / comment : 0

1. package com.instaceofjava;
2.
3. import java.util.HashMap;
4. import java.util.Iterator;
5. import java.util.Map;
6. import java.util.Map.Entry;
7.
8. public class Mapiterator {
9.
10.public static void main(String[] args) {
11.
12.HashMap map=new HashMap();
13.
14.map.put(1, "indhu");
15.map.put("d", "sindhu");
16.map.put("3", "swathi");
17.

18.if(!map.isEmpty()){
19.
20.Iterator it=map.entrySet().iterator();
21.
22.while(it.hasNext()){
23.
24.Map.Entry obj=(Entry) it.next();
25.System.out.println(obj.getValue());
26.
27.}
28.
29.}
30.
31.}
32.
33.}

Output:
1. swathi
2. indhu
3. sindhu

Sort ArrayList in descending order


Posted by: instance of java Posted date: 10:49 / comment : 0

Descending order:
1. package com.instanceofjavaforus;
2. import java.util.ArrayList;
3.

import java.util.Collections;

4. import java.util.Comparator;
5.

6. public class SortArrayListDesc {


7.
8.

public static void main(String[] args) {

9.
10.

//create an ArrayList object

11.

ArrayList arrayList = new ArrayList();

12.
13.

//Add elements to Arraylist

14.

arrayList.add(1);

15.

arrayList.add(2);

16.

arrayList.add(3);

17.

arrayList.add(4);

18.

arrayList.add(5);

19.

arrayList.add(6);

20.
21.

/*

22.
23.

Use static Comparator reverseOrder() method of Collections


utility class to get comparator object

24.

*/

25.
26.

Comparator comparator = Collections.reverseOrder();

27.
28.

System.out.println("Before sorting : " + arrayList);

29.
30.
31.

/*

32.

use

33.

static void sort(List list, Comparator com) method of Collections


class.

34.
35.

*/

36.

Collections.sort(arrayList,comparator);

37.

System.out.println("After sorting : + arrayList);

38.
39.
40.

41.

1. OutPut:
2. Before sorting : [1, 2, 3, 4, 5, 6]
3. After sorting : [6, 5, 4, 3, 2, 1]

Sort object using comparator


Posted by: instance of java Posted date: 19:18 / comment : 0
1. package com.instanceofjava;
2.
3. public class Employee
4. {
5.
6.

int id;

7.

String name;

8.
9.

public Employee(int id, String name) {

10.
11. this.id=id;
12. this.name=name;
13.
14. }
15.
16.public int getId() {
17.

18.return id;
19.
20.}
21.
22. public void setId(int id) {
23. this.id = id;
24. }
25.
26. public String getName() {
27. return name;
28. }
29.
30.public void setName(String name) {
31.
32. this.name = name;
33.
34.}
35.
36.}

1. class MyEmpComp implements Comparator<Employee >


2. {
3.
4.

@Override

5.

public int compare(Employee e1, Employee e2) {

6.
7.

if(e1.getName() < e2.getName()){

8.
9.

return 1;
} else {

10.
11.

return -1;
}

12.
13.}
14.
15.}

1. package com.oops;
2.
3. import java.util.ArrayList;
4. import java.util.Collections;
5. import java.util.Iterator;
6.
7. import java.io.*;
8.
9. class Main{
10.
11.public static void main(String args[]){
12.
13.ArrayList al=new ArrayList();
14.
15.al.add(new Employee(101,"Indhu"));
16.al.add(new Employee(106,"Sindhu"));
17.al.add(new Employee(105,"Swathi"));
18.
19.Collections.sort(al,MyEmpComp );
20.
21.Iterator itr=al.iterator();
22.
23.while(itr.hasNext()){
24.
25.Employee st=(Employee)itr.next();
26.System.out.println(st.id +" "+st.name );

27.
28. }
29.
30.
31.}
32.
33.
34.}

Output:
1. Indhu
2. Swathi
3. Sindhu

Can we overload static methods in java


Posted by: instance of java Posted date: 19:20 / comment : 0

Yes. We can overload static methods in java.


Method overriding is not possible but method overloading is possible for
static methods.

Before that lets see about method overloading in java.

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.

Method overloading also known as compile time polymorphism.

Static methods - method overloading

Its always possibles static method overloading.


Defining multiple static methods with same name and different arguments
will possible.

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. System.out.println("staticMethod(): Zero arguments");
6.
7. }
8.
9. public static void staticMethod(int a){
10.
11.System.out.println("staticMethod(int a): one argument");
12.
13.}
14.
15.public static void staticMethod(String str, int x){
16.
17.System.out.println("staticMethod(String str, int x): two arguments");
18.
19.}
20.
21.public static void main(String []args){
22.
23. StaticMethodOverloading.staticMethod();
24. StaticMethodOverloading.staticMethod(12);
25. StaticMethodOverloading.staticMethod("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

Can we override static methods in java


Posted by: instance of java Posted date: 16:58 / comment : 0

Exact answer is NO. We can not override static methods.


Before discussing this topic lets see what is static in java.

Static methods in java:

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

Without using object we can call these static methods.

here the detailed explanation on static methods

Instance methods in java:

Instance methods will be called at run time.


Instance variables and instance methods are object level. variables values
may change from one object to another where as static variable values are
class level so if we access by using any object and changes that values will
effect to all objects means its class level variable.
Lets see about overriding in java.

Method overriding in java:

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.

So by this every-time sub-most object method will be called.

Instance methods - Method Overriding

1. class SuperClassDemo{
2.
3. public void instanceMethod(){
4.
5. System.out.println("SuperClassDemo instanceMethodcalled");
6.
7. }
8.
9. }

1. class SubClassDemo extends SuperClassDemo{


2.
3. public void instanceMethod(){
4.
5. System.out.println("SubClassDemo instanceMethod called");
6.
7. }
8. public static void main(String []args){
9.
10. SuperClassDemo superObj= new SuperClassDemo();
11. SuperClassDemo superobj1= new SubClassDem();
12. SubClassDemo subObj= new SubClassDem();

13. // here no need to create object to call a static method please note that.
14.
15. superObj.instanceMethod();
16. superObj1.instanceMethod();
17. subObj.instanceMethod();
18.
19.}
20.}

Output
1. SuperClassDemo instanceMethodcalled
2. SubClassDemo instanceMethodcalled
3. SubClassDemo instanceMethodcalled

Static methods - method overriding:

Lest an example program on static methods in method overriding concept


and then discus about this clearly.

1. class SuperClassDemo{
2.
3. public static void staticMethod(){
4.
5. System.out.println("SuperClassDemo staticMethod called");
6.
7. }
8.
9. }

1. class SubClassDemo extends SuperClassDemo{


2.
3. public static void staticMethod(){
4.

5. System.out.println("SubClassDemo staticMethod called");


6.
7. }
8. public static void main(String []args){
9.
10. SuperClassDemo superObj= new SuperClassDemo();
11. SuperClassDemo superobj1= new SubClassDem();
12. SubClassDemo subObj= new SubClassDem();
13. // here no need to create object to call a static method please note that.
14.
15. superObj.staticMethod();
16. superObj1.staticMethod();
17. subObj.staticMethod();
18.
19.}
20.}

Output
1. SuperClassDemo staticMethod called
2. SuperClassDemo staticMethod called
3. SubClassDemo staticMethod called

Method Overriding - Method Hiding:

Method overriding : in method overriding we will define super class method in


sub class with same signature and these methods will be called at run time
based on the object.
Method Hiding: In method hiding even though super class methods are
accesible in sub class they are not the part of sub class so the methods and
these methods will be called based on the class.
In method Hiding if we define same static method in super class and sub
class they are not same they are unique and distinct from the other.

return type in java example


Posted by: instance of java Posted date: 18:02 / comment : 0
Return type in java:

Basically return type is used in java methods.


Method signature includes this return type.

public int show(){ // }

we will use methods to do a particular task after completion of task if we


want to return something to the calling place these return types will be used.

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.

Type of declaration of methods based on return type and arguments:


1.Method with out return type and without arguments.

1. package com.instanceofjava;
2. class sample{
3.
4. public void add(){
5.
6. int a=40;
7. int b=50;
8. int c=a+b;
9. System.out.println(c);
10.
11.}
12.
13.public static void main(String args[]) // ->method prototype.
14.
15.

16.sample obj= new sample();


17.

obj.add();

18.
19.
20.

21.}

2.Method with out return type and with arguments.


1. package com.instanceofjava;
2. class sample{
3.
4. public void add(int a, int b){
5.
6. int c=a+b;
7. System.out.println(c);
8.
9. }
10.
11.public static void main(String args[]) // ->method prototype.
12.

13.
14.sample obj= new sample();
15.

obj.add(13,24);

16.
17.
18.

19.}

3.Method with return type and without arguments.

1. package com.instanceofjava;

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.
11.public static void main(String args[]) // ->method prototype.
12.

13.
14.sample obj= new sample();
15.

int x=obj.add();

16.

System.out.println(x);

17.
18.

19.}

4.Method with return type and with arguments.

1. package com.instanceofjava;
2. class sample{
3.
4. public int add(int a, int b){
5.
6. int c=a+b;
7. return c;
8. }
9.

10.public static void main(String args[]) // ->method prototype.


11.

12.
13.sample obj= new sample();
14.
15.

int x=obj.add(1,2);

16.

System.out.println(x);

17.
18.

19.}

Can we call sub class methods using super class


object
Posted by: instance of java Posted date: 16:23 / comment : 0

Common coding interview question everybody facing in interviews is can we


call sub class method using super class object? or can we call child class
method using parent class? or can a super class call a subclass' method.
The answer is No. but still we can say yes. so we need to what are all those
scenarios of calling sub class method from super class and lets discuss about
which is the actual possible case to call sub class method using super class
object.
Before that let me explain what is inheritance and how the super and sub
classes related each other.

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

Java does not supports multiple inheritance

Read this:
Why Java does not supports multiple inheritance

Creating super class object and calling methods


1. //Multilevel inheritance program
2. Class A{
3.
4. int a;
5.
6. public void print(){
7.
8. System.out.println("print method of super class A");
9.
10.}
11.
12.}
13.Class B extends A{
14.
15.public void show(){
16.
17. System.out.println("show method of sub class B");
18.
19.}
20.public static void main(String[] args){
21.
22.A obj= new A();
23.obj.a=10;
24.
25.obj.print();
26. //obj.show(); // compile time error
27.

28. System.out.println("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

Creating super class object and calling methods


1. //Multilevel inheritance program
2. Class A{
3.
4. int a;
5.
6. public void print(){
7.
8. System.out.println("print method of super class A");
9.
10.}
11.
12.}
13.Class B extends A{
14.
15.public void show(){

16.
17. System.out.println("show method of sub class B");
18.
19.}
20.public static void main(String[] args){
21.
22.B obj= new B();
23.obj.a=10;
24.
25.obj.print();
26.obj.show();
27.
28. System.out.println("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.

So we can call super class methods using sub class.

B obj= new B();

obj.print();

So by creating sub class object we can call both super class methods and sub
class methods.

Assigning sub class reference to super class object.


1. //Multilevel inheritance program
2. Class A{
3.
4. int a;
5.
6. public void print(){
7.
8. System.out.println("print method of super class A");
9.
10.}
11.
12.}
13.Class B extends A{
14.
15.public void show(){
16.
17. System.out.println("show method of sub class B");
18.
19.}
20.public static void main(String[] args){
21.
22.A obj= new B();
23.obj.a=10;
24.
25.obj.print();
26.//obj.show(); // compile time error
27.

28. System.out.println("a="obj.a);
29.
30.}
31.}

Output:
1. print method of super class A
2. 10

Yes we can assign sub class object to super class reference.


So here Sub class object is created so memory allocated to all super class
members

so can we call all methods ? No eventhough sub class object is created we


can not call sub class methods because we assigned sub class object to super
class reference.

Then how its possible to call sub class methods?

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.

Assigning sub class reference to super class object.


1. //Multilevel inheritance program
2. Class A{
3.
4. int a;
5.
6. public void print(){
7.
8. System.out.println("print method of super class A");
9.
10.}
11.
12.}

13.Class B extends A{
14.
15.public void show(){
16.
17. System.out.println("show method of sub class B");
18.
19.}
20.public static void main(String[] args){
21.
22.A obj= new B();
23.obj.a=10;
24.
25.obj.print();
26.//obj.show(); compile time error
27.((B)obj).show(); // works fine
28.
29.
30. System.out.println("a="obj.a);
31.
32.}
33.}

Output:
1. print method of super class A
2. show method of sub class B
3. 10

Can we override private method in java


Posted by: instance of java Posted date: 17:20 / comment : 0

We can not override private methods in java.

The basic inheritance principle is when we are extending a class we can


access all non private members of a class so private members are private to
that class only we can not access anywhere outside the class if we declare
anything as private.

Know more information about access specifiers here

1. Class A{
2.
3.
4.

int a;
private int b;

5.
6. public void print(){
7.
8. System.out.println("print method of super class A");
9.
10.}
11.
12.private void add(){
13.
14.System.out.println("add method of super class A");
15.
16.}
17.}
18.Class B extends A{
19.
20.public void show(){
21.
22. System.out.println("show method of sub class B");
23.
24.}
25.public static void main(String[] args){
26.

27.B obj= new B();


28.obj.a=30;
29.
30.obj.print();
31.obj.show();
32.
33. System.out.println("a="obj.a);
34.//obj.b=20; compile time error. The field Super.a is not visible
35.//obj.add(); compile time error : The method show() from the type Super is
not visible
36.
37.}
38.}

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;

6. private void add(){


7.
8. System.out.println("add method of super class A");
9.
10.}
11.}
12.Class B extends A{
13.
14.private void add(){
15.
16. System.out.println("add method of sub class B");
17.
18.}
19.public static void main(String[] args){
20.
21.B obj= new B();
22.obj.a=30;
23.
24.obj.add();
25.
26.
27. System.out.println("a="obj.a);
28.
29.}
30.}

Output:
1. add method of sub class B
2. 30

We can prove this by providing @override annotation in sub class method

1. Class A{
2.
3.
4.

int a;
private int b;

5.
6. private void add(){
7.
8. System.out.println("add method of super class A");
9.
10.}
11.}
12.Class B extends A{
13. //@override
14.private void add(){// if we place @override annotation compile time error will
come here
15.
16. System.out.println("add method of sub class B");
17.
18.}
19.public static void main(String[] args){
20.
21.B obj= new B();
22.obj.a=30;
23.
24.obj.add();
25.
26.
27. System.out.println("a="obj.a);
28.
29.}
30.}

Output:
1. add method of sub class B
2. 30

Anda mungkin juga menyukai