You are on page 1of 47

JAVA NOTES

1. Basic things to understand before discussing about Architecture

 Program is a set of instruction to achieve a particular task, group of program related to a


particular domain is an application
 All these programs are generally written in High Level Language (normal English)
 All these programs must be given to CPU for execution purpose, but CPU understands
only Binary Level Language, hence programs must be translated

2.  Translators:

 Compilers

 Entire Program is compiled in “One shot”


 Compilation will be successful when all the instructions are according to syntax

 Interpreters

 Interpretation happens line by line


 In order to execute a statement, entire program need not to be interpreted
 This stops only when there is a syntax error
Let us understand the internal Process of Class loader Subsystem:
            it involves 3 stages : Loading, Linking and Initializing

1. Loading:

            This involves 3 type:



o Bootstrap loading: responsible for loading internal java class files which are
present in rt.jar all the primary files are present in rt.jar
o Extension Loader: responsible for importing extensible file/ extract files needed
for JVM for processing lib/ext will have all the content
o Application Class path: Specified by cp these are needed at compile/runtime   

2. Linking:

 Verifying:
o Java bytecode is taken care off here
o It checks whether it is compatible with Java specification or not
o Usually ClassNotFound Exceptions are thrown here
 Prepare:
o all the class data / variable are initialized to their default values here
o Ex: static int a = 5 is created in class but a is re initialized to default value i.e 0

 Resolving
o loads reference objects and Variables
o Ex: bike class is having another class called owner now checks whether owner
class is defined or not
o Throws ClassDefNotFound Exception

3. Initializing:
o static block initiates first
o Original values are reassigned back

                                    like a = 5
Execution Engine: Executes byte code info
1. JIT: whenever engine encounters same kind of instructions again and again
                        JIT compiles some part if code so perform is improved
                        JIT compiles converts the byte code into native code after compiling it
system used the native code directly

LANGUAGE BASICS :
Program 1
class Sample
{
 
    public static void main(String[] args)
    {
        System.out.println("Hi all welcome to JAVA training");
    }
 
}
 
/* 
    compilaction -> javac Sample.java -> .class file 
    execution -> java Sample 
*/
 
Program 2
class Convertion
{
 
    public static void main(String[] args)
    {
        System.out.println("Length of the String arrays is : "+args.length);
        if(args.length==0)
        {
            System.out.println("array is empty");
        }
        else
        {
            
        }
    }
 
}
 
/*
    int arrays -> 1,2,3 -> length is 3 index 0 1 2
    
    if an array length is 0 - means -> array is empty 
    
    length of an array -> arrayname.length
    
    during execution command when i pass data then only it will be stored in string array
    
    String to integer -> Integer.parseInt(name of string)
    
    args[0] - 10
    args[1]- 20
    
    int var1 = Integer.parseInt(args[0]);
    
    abc - args[0]
    
    "123bc" "abc"  "@#$" all these are strings 
  
*/
Exercises on language basics:
1. Write a Program that accepts two Strings as command line arguments and generate the output
in a specific way as given below.
 Example:
  If the command line arguments are ABC and Mumbai then the output generated should    be ABC
Technologies Mumbai
[Note: It is mandatory to pass two arguments in command line]
public class Command
{
public static void main(String args[])
{
System.out.println(args[0] + " Technologies " + args[1]);
}
}
//For output Wipro Technologies Banglore

//To Compile: Command.java

//To Execute:java Command Wipro Banglore

//For Output ABC Technologies Mumbai

//To Compile: Command.java

//To Execute:java Command ABC Mumbai

2.  Write a Program to accept a String as a Command line argument and the program should print a
Welcome message.
 Example:
    C:\> java Sample John
      O/P Expected: Welcome John

class Simple
{
public static void main(String args[])
{
System.out.println("Welcome"+ args[0]);
}
}

3. Write a Program to accept two integers through the command line argument and print the sum
of the two numbers
 Example:
      C:\>java Sample 10 20
     O/P Expected: The sum of 10 and 20 is 30
public class SumCommand
{
public static void main(String args[])
{
int x = Integer.parseInt(args[0]); //first arguments
int y = Integer.parseInt(args[1]); //second arguments
int sum = x + y;
System.out.println("The sum of x and y is: " +sum);
}
}

FLOW CONTROL STATEMENTS


DEMO PROGRAMS GIVEN BY MAM:
public class SimpleIf 

    public static void main(String[] args)
    { 
        int x = 25;  //static data 
        if( x < 20 )
        { 
            System.out.print("This is if statement"); 
        } 
        System.out.println("  done program execution");
    }

 
************************************************
 
public class IfElse 
{
    public static void main(String[ ] args) 
    {
        int age;
        age = Integer.parseInt(args[0]);
        if(age>18) 
        {
            System.out.println("Eligible to vote");
        }
        else
        {
            System.out.println("Not eligible to vote");
        }
    }
}
 
************************************************
 
public class ElseIfDemo 
{
    public static void main(String[] args) 
    {
        //int month = args[0];
        int month = Integer.parseInt(args[0]);
        if(month == 12 || month == 1 || month == 2)
            System.out.println("Winter");
        else
        {
            if(month == 3 || month == 4 || month == 5)
            System.out.println("Spring");
        }
        else if(month == 6 || month == 7 || month == 8)
            System.out.println("Summer");
        else if(month == 9 || month == 10  || month == 11)
            System.out.println("Autumn");        
        else
            System.out.println("invalid number");
    }
}
 
*************************************************
 
public class Test
{
    public static void main(String[] args)
    {
    
        int x = 1;
        switch(x)
        {
            case 1 : System.out.println("one");
                        break;
            
            case 2 : System.out.println("two");
                        break;
            
            default : System.out.println("default");
        }
    }
 
}
 
**************************************************
 
public class SwitchDemo 
{
    public static void main(String[] args) 
    {
        int weekday = Integer.parseInt(args[0]);
        switch(weekday) 
        {
            case 1:   System.out.println("Sunday");       
                      break;
            case 2:   System.out.println("Monday");                                       
                      break;
            case 3:   System.out.println("Tuesday");                                       
                      break;
            case 4:   System.out.println("Wednesday");                                 
                      break;
            case 5:   System.out.println("Thursday");                               
                      break;
            case 6:   System.out.println("Friday");                                    
                      break;
            case 7:   System.out.println("Saturday");                                
                      break;
            default:  System.out.println("Invalid day");
            
        }  
    }   
}
 
*****************************************************
import java.util.Scanner;
 
public class SampleWhile
{
    public static void main(String[] args) 
    {
        int i = 0;
        int end;
        Scanner sc = new Scanner(System.in);
        
        System.out.println("enter an integer");
        
        end = sc.nextInt();
        
        while (i < end) 
        { 
            System.out.println("i: "+i);
            i = i + 1; 
        } 
    }
}
 
// 0 ... 4 
************************************************************************
public class SampleDoWhile
{
    public static void main(String[] args)
    {
        int i=5;
        do
        {
            System.out.println("i: "+i);
            i=i+1;
        }while(i<10);
    }    
}
// exit control loop     
// 5 6 7 8 9
 
*************************************************************************
import java.util.Scanner;
 
public class UserData
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter Integer");
        
        int var1 = sc.nextInt();
        
        System.out.println("Enter a String");
        
        String str = sc.next();
        
        System.out.println("Enter double value");
        
        double db = sc.nextDouble();
        
        System.out.println("Printing all the values of variables");
        
        System.out.println(var1);
        System.out.println(str);
        System.out.println(db);
    
    }
 
}
 
*************************************************************
public class SampleFor
{
    public static void main(String[] args)
    {
        
        for(int i=1;i<=10;i++)
        {
            System.out.println("i: "+i);
        }
    }
}
 
****************************************************************
public class SampleFor
{
    public static void main(String[] args)
    {
        int i,j;
        for( i=1,j=10;(i<=10 && j==10);i++,j++)
        {
            System.out.println("i: "+i +" j: "+j);
        }
        
        System.out.println(j);
    }
}
Exersise on flow control statements:
1.Write a program to check if a given number is Positive, Negative, or Zero.
import java.util.Scanner;
public class CheckPNZ
{
public static void main(String args[])
{
int num;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
num = s.nextInt();
if(num>0)
{
System.out.println("The number is positive.");
}
else if(num<0)
{
System.out.println("The number is negative.");
}

else
{
System.out.println("The number is zero.");
}
}
}
2. Write a program to check if a given number is odd or even.
import java.util.Scanner;
public class Odd_Even
{
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
n = s.nextInt();
if(n % 2 == 0)
{
System.out.println("The given number "+n+" is Even ");
}
else
{
System.out.println("The given number "+n+" is Odd ");
}
}
}
3. Write a program to check if the program has received command line arguments or not. If the
program has not received the values then print "No Values", else print all the values in a
single line separated by ,(comma).
 Eg1) java Example
 O/P: No values
 Eg2) java Example Mumbai Bangalore
 O/P: Mumbai, Bangalore
 [Note: You can use length property of an array to check its length.
class Example
{
public static void main(String[] args)
{
if(args.length== 0)
{
System.out.println("No values");
}
else
{
for(String i : args)
System.out.print(i+ " , ");
}
}
}
4. Initialize two character variables in a program and display the characters in alphabetical
order.
 Eg1) if first character is s and second is e
 O/P: e,s
 Eg2) if first character is a and second is e
 O/P:a,e
class Alphabet
{
public static void main (String[] args)
{
char item1='s';
char item2='e';
if (item1>item2)
{
System.out.println(item2+" , "+item1);
}

else
{
System.out.println(item1+" , "+item2);
}
}
}
5.  Initialize a character variable in a program and if the value is alphabet then print "Alphabet"
if it’s a    number then print "Digit" and for other characters print "Special Character"
class CheckValue
{
public static void main (String[] args)
{
char item1='1'; //here the initialization is carried out
if((item1>96&&item1<123)||(item1>64&&item1<91))
System.out.println("Alphabet");
else if(item1>47&&item1<58)
System.out.println("Digit");
else
System.out.println("Special Character");
}
}
6. Write a program to accept gender ("Male" or "Female") and age (1-120) from command line
arguments and print the percentage of interest based on the given conditions.
 Interest == 8.2%
  Gender ==> Female
  Age    ==>1 to 58
 Interest == 7.6%
  Gender ==> Female
  Age    ==>59 -120
 Interest == 9.2%
  Gender ==> Male
  Age    ==>1-60
 Interest == 8.3%
  Gender ==> Male
  Age    ==>61-120

public class Gender


{
public static void main(String[] args)
{
String Gender = args[0];
int age = Integer.parseInt(args[1]);
if(args.length==0)
{
System.out.println("Empty Arguments");
}
else{
if(Gender.equals("Male") || Gender.equals("Female"))
{
if(age>1 && age<=100)
{
if (Gender.equals("Female") && (age >= 1 && age <= 58))
{
System.out.println("Interest == 8.2%");
}
else if (Gender.equals("Female") && (age >= 59 && age <= 100))
{
System.out.println("Interest == 9.2%");
}
else if (Gender.equals("Male") && (age >= 1 && age <= 58))
{
System.out.println("Interest == 8.4%");
}
else if (Gender.equals("Male") && (age >= 59 && age <= 100))
{
System.out.println("Interest == 10.5%");
}
}
}
}
}
}
7.  Write a program to convert from upper case to lower case and vice versa of an alphabet and
print the old character and new character as shown in example (Ex: a->A, M->m).
import java.util.Scanner;
public class LowerUpperCase
{

public static void main(String[] args)


{
Scanner s=new Scanner(System.in);
char c=s.next().charAt(0);
int i;

if(c>='a'&&c<='z')
{
System.out.println(c+"->");
i=(int)c;
c=(char)(i-32);
System.out.println(c);
}

else
{
System.out.println(c+"->");
i=(int)c;
c=(char)(i+32);
System.out.println(c);
}
}
}
8. Write a program to print the color name, based on color code. If color code in not valid then
print "Invalid Code". R->Red, B->Blue, G->Green, O->Orange, Y->Yellow, W->White.
import java.util.Scanner;
public class ColorCode
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter color code:");
char code = in.next().charAt(0);
switch(code)
{
case 'R':
System.out.println("Red");
break;
case 'B':
System.out.println("Blue");
break;
case 'G':
System.out.println("Green");
break;
case 'O':
System.out.println("Orange");
break;
case 'Y':
System.out.println("Yellow");
break;
case 'W':
System.out.println("White");
break;
default:
System.out.println("Invalid code");
break;
}
}
}
9.  Write a program to print month in words, based on input month in numbers
 Example1:
       C:\>java Sample 12
       O/P Expected: December
class MonthName
{
public static void main(String args[])
{
int number = Integer.parseInt(args[0]);
switch(number)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;

default:
System.out.println("Invalid");
break;
}
}
}
 Example2:
       C:\>java Sample
       O/P Expected: Please enter the month in numbers
import java.util.Scanner;
public class Month
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the months in numbers:");
int number= sc.nextInt();
switch(number)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;

default:
System.out.println("Invalid");
break;
}
}
}
 Example3:
       C:\>java Sample 15
       O/P Expected: Invalid month  
public class Month2
{
public static void main(String args[])
{
int number = Integer.parseInt(args[0]);
switch(number)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;

default:
System.out.println("Invalid month");
break;
}
}
}
10.   Write a program to print numbers from 1 to 10 in a single row with one tab space.  
public class Tabspace
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
System.out.print(i+" ");

}
}
11. Write a program to print even numbers between 23 and 57, each number should be printed in a
separate row.  
public class Even
{
public static void main(String[] args)
{
int i;
for(i=23;i<=57;i++)
{
if(i%2==0)
{
System.out.println(i);
}
}
}
}
12. Write a program to check if a given number is prime or not.
public class prime
{
public static void main(String args[])
{
int i,m=0,flag=0;
int n=3;
m=n/2;
if(n==0 || n==1)
{
System.out.println(n+ "is not prime number");
}
else
{
for(i=2;i<=m;i++)
{
if(n%i == 0)
{
System.out.println(n+ "is not prime number");
flag=1;
break;
}
}
if(flag ==0)
{
System.out.println(n+ "is prime number");
}
}
}
}
13.  Write a program to print prime numbers between 10 and 99.
public class Prime1
{
public static void main(String arg[])
{
int i,count;
System.out.println("Prime numbers between 1 to 100 are ");
for(int j=10;j<=99;j++)
{
count=0;
for(i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
System.out.print(j+" ");
}
}
}
15. Write a program to add all the values in a given number and print. Ex: 1234->10
import java.util.Scanner;
public class Sum
{
public static void main(String arg[])
{
long number = 1234;
long sum;
for(sum=0; number!=0; number=number/10)
{
sum = sum + number % 10;
}
System.out.println("Sum of digits: "+sum);
}
}
16.  Write a program to print * in Floyds format (using for and while loop)
 *
 *  *
 *  *   *
 Example1:
      C:\>java Sample
        O/P Expected : Please enter an integer number
import java.util.Scanner;
public class Firstpattern
{
public static void main(String args[])
{
int i, j, n;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter an integer number");
n=sc.nextInt();
for(i=0; i<n; i++)
{
for(j=0; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
 Example2:
        C:\>java Sample 3
         O/P Expected :
                   *
                   *  *
                   *  *  *
public class Firstpattern2
{
public static void main(String args[])
{
int i, j;
int n = Integer.parseInt(args[0]);
for(i=0; i<n; i++)
{
for(j=0; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
17. Write a program to reverse a given number and print
 Eg1)
    I/P: 1234
    O/P: 4321
public class Reverse
{
public static void main(String[] args)
{
int number = 1234, reverse = 0;
for( ;number != 0; number=number/10)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
}
System.out.println("The reverse of the given number is: " + reverse);
}
}
 Eg2)
   I/P: 1004
   O/P: 4001
Give number =1004 in above program.
18. Write a Java program to find if the given number is palindrome or not
 Example1:
       C:\>java Sample 110011
       O/P Expected : 110011 is a palindrome
 Example2:
       C:\>java Sample 1234
    O/P Expected : 1234 is not a palindrome.
class Palindrome
{
public static void main(String args[])
{
long r,sum=0;
long temp;
long n = Long.parseLong(args[0]);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println(n+" is a palindrome number ");
else
System.out.println("not palindrome");
}
}
19.  Write a program to print first 5 values which are divisible by 2, 3, and 5.
class Divisible
{
public static void main(String []args)
{
int N = 150;
for (int num = 0; num < N; num++)
{
if (num%2 ==0 && num % 3 == 0 && num % 5 == 0)
{
System.out.print(num + " ");
}
}
}
}
20.  Write a program that displays a menu with options 1. Add 2. Sub
Based on the options chosen, read 2 numbers and perform the relevant operation. After performing
the operation, the program should ask the user if he wants to continue. If the user presses y or Y,
then the program should continue displaying the menu else the program should terminate.
[ Note: Use Scanner class ]
import java.io.*;
import java.util.*;
public class DisplayMenu
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("1:ADD");
System.out.println("2:SUB");
String str = "";
int ans;
do
{
System.out.println("Enter your choice");
int choice = sc.nextInt();
System.out.println("Enter two numbers:");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
if(choice == 1)
{
ans = n1+n2;
System.out.println("Addition is " +ans);
}
else
{
ans = n1-n2;
System.out.println("Subtraction is" +ans);
}
System.out.println("Do you want to continue : Y/N");
str = sc.next();
}while(str.equalsIgnoreCase("y"));
}
}

ARRAYS:
 Normally, an array is a collection of similar type of elements which has contiguous
memory location.
 Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.
 In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.
 Advantages
 Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
 Random access: We can get any data located at an index position.

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.
Types of Array in java
There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Syntax to Declare an Array in Java(single dimensional):

1. dataType[] arr; (or)  
2. dataType []arr; (or)  
3. dataType arr[];  
Syntax to Declare an Array in Java(single dimensional):

1. dataType[][] arrayRefVar; (or)  
2. dataType [][]arrayRefVar; (or)  
3. dataType arrayRefVar[][]; (or)  
4. dataType []arrayRefVar[];   
Exercises on Array

1.Write a program to initialize an integer array and print the sum and average of the array

public class ArraySum


{
public static void main(String[] args)
{
Int [] arr = new int [] {1, 2, 3, 4, 5};
int sum = 0;
float Average;
for (int i = 0; i < arr.length; i++)
{
if(i<3 && i>5)
{
sum = sum + arr[i];
}
}
System.out.println("Sum of all the elements of an array: " + sum);
Average=sum/arr.length;
System.out.println("Average of all the array elements is:" +Average);
}
}
2. Write a program to initialize an integer array and find the maximum and minimum value of
an array.
public class ArrayMinMax
{
public static void main(String args[])
{
int [] arr = new int[] {25,50,75,60,10};
int max = arr[0];
int min = arr[0];
for(int i=0;i<arr.length;i++)
{
if(arr[i]>max)
max=arr[i];
if(arr[i]<min)
min=arr[i];
}
System.out.println("Maximum value present in given array:"+max);
System.out.println("Minimum value present in given array:"+min);
}
}
3. Write a program to initialize an integer array with values and check if a given number is
present in the array or not. If the number is not found, it will print -1 else it will print the
index value of the given number in the array.
Example 1)
If the array elements are {1,4,34,56,7} and the search element is 90,Then the output expected
is -1.
Example 2)
If the array elements are {1,4,34,56,7} and the search element is 56,Then the output expected
is 3.
import java.util.Scanner;
public class CheckArray
{
public static void main(String[] args)
{
int[] arr = {1,4,34,56,7};
int number;
int index = -1;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the number");
number=sc.nextInt();
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == number)
{
index = i;
break;
}
}
System.out.println("At position :" + index);
}

}
4. Initialize an integer array with ascii values and print the corresponding character values in a
single row.
public class AsciiValue
{
public static void main(String[] args)
{
int arr[] = {66,71,76,82,88,99};
for (int i=0; i<arr.length; i++)
{
System.out.print((char)arr[i]+" ");
}
System.out.println();
}
}
5. Write a program to find the largest 2 numbers and the smallest 2 numbers in the given array.
import java.util.Scanner;
public class TwoLargestSmallest
{
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.print("Enter no. of elements you want in array:");
Int n = sc.nextInt();
int array[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < array.length; i++)
{
array[i] = scn.nextInt();
}
int largest1, largest2, temp;
largest1 = array[0];
largest2 = array[1];
if (largest1 < largest2)
{
temp = largest1;
largest1 = largest2;
largest2 = temp;
}
for (int i = 2; i < array.length; i++)
{
if (array[i] > largest1)
{
largest2 = largest1;
largest1 = array[i];
}
else if (array[i] > largest2 && array[i] != largest1)
{
largest2 = array[i];
}
}
System.out.println ("The First largest is " + largest1);
System.out.println ("The Second largest is " + largest2);
int smallest1, smallest2;
smallest1 = array[0];
smallest2 = array[1];
if (smallest1 > smallest2)
{
temp = smallest1;
smallest1 = smallest2;
smallest2 = temp;
}
for (int i = 2; i < array.length; i++)
{
if (array[i] < smallest1)
{
smallest2 = smallest1;
smallest1 = array[i];
}
else if (array[i] < smallest2 && array[i] != smallest1)
{
smallest2 = array[i];
}
}
System.out.println ("The First smallest is " + smallest1);
System.out.println ("The Second smallest is " + smallest2);
}
}
6. Write a program to initialize an array and print them in a sorted fashion.
public class ArraySort
{
public static void main(String[] args)
{
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++)
{
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
7. Write a program to remove the duplicate elements in an array and print the same.
Example:
I/P : {12,34,12,45,67,89}
O/P : {12,34,45,67,89}
public class DuplicateElements
{
public static int removeDuplicateElements(int arr[], int n)
{
if (n==0 || n==1)
{
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++)
{
if (arr[i] != arr[i+1])
{
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
for (int i=0; i<j; i++)
{
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args)
{
int arr[] = {12,34,12,45,67,89};
int length = arr.length;
length = removeDuplicateElements(arr, length);
for (int i=0; i<length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
8. Write a program to print the element of an array that has occurred the highest number of times
Example:
Array -> 10,20,10,30,40,100,99
import java.util.*;
public class MaxCount
{
public static void main(String args[])
{
int arr[]={10,20,10,30,40,100,99};
int maxcounter=0;
int count = 1;
int element =0;
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
if(maxcounter<count)
{
maxcounter = count;
element = arr[i];
}

}
System.out.println("The element which occurs maximum times is:" +element);
}
}
9.Write a program to print the sum of the elements of the array with the given below condition if the
array has 6 and 7 in succedding orders, ignore 6 and 7 and the numbers between them for the
calculation of sum.
import java.util.*;
public class SumCondition67
{
public static void main(String args[])
{
int arr[] = {1,6,4,7,9};
int sum = 0;
int m=0;
int n=0;

for(int i=0;i<arr.length;i++)
{
if(arr[i] == 6)
{
m = i;
}
if(arr[i] == 7)
{
n = i;
}
}
for(int j=0;j<arr.length;j++)
{
if(!(n>=j&&j>=m) && j<arr.length)
{
sum = sum + arr[j];
}
}
System.out.println("The sum of array elements with condition is:" + sum);

}
}
PACKAGE IN JAVA
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

 Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

 Simple example of java package

The package keyword is used to create a package in java.


package mypack; 
public class Simple
{  
public static void main(String args[])
{  
System.out.println("Welcome to package");  
   }  
}  

 There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

 Example for packagename.*


package pack;  
public class A{  
 public void msg(){System.out.println("Hello");}  

package mypack;  
import pack.*;  
  class B{  
   public static void main(String args[]){  
    A obj = new A();  
    obj.msg();  
   }  
}
 Example for package.classname:
package pack;  
public class A{  
   public void msg(){System.out.println("Hello");}  
}  

package mypack;  

import pack.A;  
  class B{  
   public static void main(String args[]){  
    A obj = new A();  
    obj.msg();  
   }  
}  

 Example for fully qualified name:


package pack;  
public class A{  
   public void msg(){System.out.println("Hello");}  
}
package mypack;  
class B{  
   public static void main(String args[]){  
    pack.A obj = new pack.A();//using fully qualified name  
    obj.msg();  
   }  
}  
CONSTRUCTORS IN JAVA
 In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is
called. It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.
 There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

 Syntax and Example for default constructor


Syntax:<class_name>(){}
Example:
class Bike1{  
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[]){  
Bike1 b=new Bike1();  
}  
}  
 Example for parameterized constructor:
Definition: A constructor which has a specific number of parameters is called a
parameterized constructor.
Example:
class Student4{  
int id;  
String name;  
Student4(int i,String n){  
id = i;  
name = n;  
}  
void display(){System.out.println(id+" "+name);}  
public static void main(String args[]){  
Student4 s1 = new Student4(111,"Karan");  
Student4 s2 = new Student4(222,"Aryan");  
s1.display();
s2.display();  

}

ACCESS SPECIFIERS IN JAVA

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
 Understanding java access modifiers

Access within class within OutsidePackageBy outside


Modifier package SubclassOnly package
PRIVATE Y N N N
DEFAULT Y Y N N
PROTECTED Y Y Y N
PUBLIC Y Y Y Y

OOPS CONCEPTS

Object
 Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.
 An Object can be defined as an instance of a class. An object contains an address and
takes up some space in memory.

Class
 Collection of objects is called class. It is a logical entity.
 A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.

Inheritance
 Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
 Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
 The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
 Types of Inheritance:
1. Single Inheritance:
When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.
Example :

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class TestInheritance{  
public static void main(String args[]){  
Dog d=new Dog();  
d.bark();  
d.eat();  
}}
2. Multilevel Inheritance:
When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.
Example:
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  }  
class BabyDog extends Dog{  
void weep(){System.out.println("weeping...");}  
}  
class TestInheritance2{  
public static void main(String args[]){  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}}
3. Hierarchical Inheritance:
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
Example:
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class Cat extends Animal{  
void meow(){System.out.println("meowing...");}  
}  
class TestInheritance3{  
public static void main(String args[]){  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
}}
4. Multiple Inheritance:
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Example:
class A{  
void msg(){System.out.println("Hello");}  
}  
class B{  
void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
public static void main(String args[]){  
C obj=new C();  
obj.msg();//Now which msg() method would be invoked?  
}  

Polymorphism
 Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
 There are two types of polymorphism in Java: compile-time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.
 If you overload a static method in Java, it is the example of compile time polymorphism.
 Compile time polymorphism-Method Overloading
package pack3;
public class Program1 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            Calculator c = new Calculator();
            c.add(5, 6);
            c.add(2.4, 5.6);
            System.out.println(c.add(1, 3, 3.5));
            c.add(4, 6, 9);
  }
}
class Calculator
{
    void add(int a , int b)
  {
        System.out.println("sum 2 of integers : "+(a+b));
  }
   void add(int a , int b, int c)
  {
        System.out.println("sum 3 of integers : "+(a+b+c));
    } 
    void add(double a , double b)
  {
        System.out.println("sum of 2 double data type : "+(a+b));
  }
    int add(int a , int b ,double c)
  {
        return (int)(a+b+c);
  }
}
 Runtime Polyphormism – Over riding
package pack3;
public class Program2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Dog d = new Dog();
        d.eat();
  }
 
}
// static methods cannot be over rided because there are called with class names
class Animal
{
    void eat()
  {
        System.out.println("Animal is eating");
  }
    
    static void display()
  {
        
  }
}
class Dog extends Animal
{
    void eat()
  {
        super.eat();
        System.out.println("Dog is eating");
  }
    static void display()
  {
        
  }
}

Abstraction
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

 Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.

 There are two ways to achieve abstraction in java


1. Abstract class
A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the
body of the method.
 Syntax : abstract class A{} 
 A method which is declared as abstract and does not have implementation is
known as an abstract method.
 Examples of Abstract class :
Example 1:
abstract class Bike{  
abstract void run();  
}  
class Honda4 extends Bike{  
void run(){System.out.println("running safely");}  
public static void main(String args[]){  
 Bike obj = new Honda4(); 
 obj.run();  
}  

Example 2:
abstract class Shape{  
abstract void draw();  
}  
class Rectangle extends Shape{  
void draw(){System.out.println("drawing rectangle");}  
}  
class Circle1 extends Shape{  
void draw(){System.out.println("drawing circle");}  
}  
class TestAbstraction1{  
public static void main(String args[]){  
Shape s=new Circle1();  
s.draw(); 
}  
}
Example 3:
abstract class Bank{    
abstract int getRateOfInterest();    
}    
class SBI extends Bank{    
int getRateOfInterest(){return 7;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 8;}    
}    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
b=new PNB();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
}}
Encapsulation
 Encapsulation in Java is a process of wrapping code and data together into a
single unit, for example, a capsule which is mixed of several medicines.

 We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
 The Java Bean class is the example of a fully encapsulated class.
 Advantages of Encapsulation:
 It provides you the control over the data. 
 It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.

 The encapsulate class is easy to test. So, it is better for unit testing.

 Simple example of encapsulation:

//A Java class which is a fully encapsulated class.  
//It has a private data member and getter and setter methods.  
package com.javatpoint;  
public class Student{  
//private data member  
private String name;  
//getter method for name  
public String getName(){  
return name;  
}  
//setter method for name  
public void setName(String name){  
this.name=name  
}  
}

//FileName:Test.java

/A Java class to test the encapsulated class.  
package com.javatpoint;  
class Test{  
public static void main(String[] args){  
//creating instance of the encapsulated class  
Student s=new Student();  
//setting value in the name member  
s.setName("vijay");  
//getting value of the name member  
System.out.println(s.getName());  
}  
}
 GET AND SET:
 The private variables can only be accessed within the same class
(an outside class has no access to it). However, it is possible to
access them if we provide public get and set methods.
 The get method returns the variable value, and the set method
sets the value.
Example:

public class Person{

private String name; // private = restricted access

// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

this.name = newName;

public class Main {


public static void main(String[] args) {

Person myObj = new Person();

myObj.setName("John"); // Set the value of the name


variable to "John"

System.out.println(myObj.getName());

  

    
  

 
  

 
 

You might also like