Showing posts with label core java tutorial. Show all posts
Showing posts with label core java tutorial. Show all posts

Wednesday, June 26, 2019

What are the Concepts must know a 4 years Experienced Core Java DeveloperDev

In this post you will know what are the skills or concepts should know as a core java developer for 4 years of experienced. Core java is the language that means this is the base for all java related technologies and frameworks, and as you have 4 years of experience, you have a strong knowledge on internals with practical examples scenario based.

Lets start the main topics
1.OOPS:
  • Interface and Abstract class , which situation what to use with scenario
  • Abstraction and Encapsulation with real use cases
  • When to use inheritance, when to use Interface
  • Loose coupling and method overloading and overriding(Deep concept) with real time use cases
  • constructors with super()., different combinations with static block and non static block
  • Grip on static ,final key words
  • Static and non static member control flow
2.Exception Handling:
  • What is exception and error not theoretically definition like school going kids, you have to explain from your experience.
  • Basics of try,catch finally
  • throw,throws
  • Exception propagation.
  • Understanding the Exception hierarchy.
  • Understand the Exception based on method overriding.
3.MultiThreading:
  • Basics of Thread
  • Ways of creating thread, Extending from Thraed class, implementing from runnable interface.
  • sleep, join,yield methods with practical implementation knowledge,
  • Thread class methods and object class methods like wait, notify, notifyall
  • Concepts of parallelism , Synchronization
  • producer consumer problems
  • concurrent collection
4.Collections frame work with generics:
  • Hierarchy of Collections and Map
  • Grip on Collections provide classes and the interfaces, where to choose which collection having a strong knowledge.
  • Grip on Map provide interfaces and classes,
  • Having the sound knowledge of Internals of Map,Set,List
  • Implementations of hashCode() method and equals method.
  • sound knowledge of cursor objects.
  • Good knowledge of Comparable and Comparator interface, where to choose which interface
5.Inner classes:
  • Basics of inner classes
  • Anonymous inner classes , and where to use with real time use cases.
6.String,StringBuffer,StringBuilder:
  • immutable properties
  • String pooling.
  • 7.Wrapper classes:
  • where to use
  • How important
  • Auto boxing and unboxing
8.Grabage collection:
  • Basics of garbage collection.
  • How to manage JVM memory for better performance.
  • How to manage heap memory and permgen space.
  • How to handle out of memory error.
  • How to identify memory leak and how to handle.
9.Object class methods
  • Hashcode and equals method implementation.
10.Date and time Api,Calander classes

Some Important Interview Questions which are repeatedly asked in Interview:


  • write a program for singelton design pattern and how to avoid violation of its validity using java reflection.
  • How hashmaps works internally and when is resizing done.
  • Write a program to find one/two/three missing number in given series.
  • How java garbage collector works in detail.
  • Arraylist vs linklist.when to use stack/queue.
  • Given stack array write program to convert it to queue.
  • How ajax works.write equivalent jQuery.
  • When we use throwable in exception. Answer is in logging.
  • Factory design pattern.
  • Sql query to find 2/3/nth highest.
  • What are subquesries how is it diffrent from correlated query.
  • Given array write optimised code to find two number such that there sum is k.
  • Overloading overloading and method hiding.
  • Static methods when to use
  • Java enums
  • Overriding rules of user defined exception
  • How java classloader works.
  • Write a program to count number of character occurance in words
  • How hashset use hashmap internally
  • Find 10th prime number.
  • What are types of mapping possible in spring-MVC controller and annotation based.
  • Architecture of spring MVC.
  • multiple dispatcher servlet.
  • implement LRU in java.
  • implement producer-consumer problem.


Saturday, June 8, 2019

Object class methods with examples in Java

The most common general methods which are applicable on any object are defined in object class.This class provides methods to compare objects,to covert an object into a string, to notify threads regarding the availability of an object.

Object class defines the fallowing methods:

1) equals(): 

This method is used to compare two object for equality and if they are equal,it returns true otherwise false.Let us see how to compare two objects by using equals() method of Object class.

Generally Object class equals() methods compares the reference of two objects. If both object refer to same object then it gives true otherwise false. But based on our requirement it is recommended to override equals() method for content comparison. 

Example:

class EqualsDemo
{
public static void main(String args[])
{
String s1="HI";
String s2="HI";
String s3="welcome to java";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
}
}


Output:






In the above program Object class equals() methods has executed which is meant for reference comparison. But base on our requirement it is recommended to override equals() method for content comparison.

Example:


class Employee
{
String name;
int rollno;
Employee(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public boolean equals(Object obj)
{
try
{
String name1 = this.name;
int rollno1 = this.rollno;
Employee e2 = (Employee)obj;
String name2 = e2.name;
int rollno2 = e2.rollno;
if(name1.equals(name2) && rollno1 == rollno2)
{
return true;
}
else
{
return false;
}
}
catch (ClassCastException c)
{
return false;
}
catch (NullPointerException e)
{
return false;
}
}
public static void main(String arg[])
{
Employee e1 = new Employee ("pavan", 1);
Employee e2 = new Employee ("mahesh", 2);
Employee e3 = new Employee ("Eeswar", 3);
System.out.println(e1.equals(e2));
System.out.println(e2.equals(e3));
System.out.println(e1.equals(null));
}
}


Output:






2) toString():

This method returns a string representation of an object. 


Syntax:

public String toString()
{
return getClass.getName();
}

Example:


class Employee

{
String name;
int rollno;
Employee(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}

public static void main(String args[])
{
Employee e1=new Employee("nagaraju",1);
Employee e2=new Employee("prasad",2);
System.out.prinltn(e1);
System.out.prinltn(e2);
}
}
Output:






Whenever we are passing object reference as argument to System.out.println() internally JVM will call toString() on that object. If we are not providing toString() then Object class toString() will be executed which is implemented as fallows:

public String toString()

{
return getClass.getName()+'@'+Integer.toHexString(hashcode);
}
Based on our requirement to provide our own String representation we have to override toString(). Let us rewrite the above program by overriding toString() method


Example:


class Employee

{
String name;
int rollno;
Employee(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public String toString()
{
return name+"-------"+rollno;
}

public static void main(String args[])

{
Employee e1=new Employee("nagaraju",1);
Employee e2=new Employee("prasad",2);
System.out.println(e1);
System.out.println(e2);
}

}

Output:






3) getClass():

This method returns the runtime class of an object. 



4) hashCode():

This method returns a hash code value of the object. The hash code of an object just represents a random number which can be used by JVM while saving objects into hash tables,HashSet and HashMap.

hashCode() of an Object class implemented to return hashCode based on address of an object,but based on our requirement we can override hashCode() to generate our own numbers as hashCode.

Example:

class Demo

{
int a;
Demo(int a)
{
this.a = a;
}
public int hashCode()
{
return a;
}
public static void main(String arg[])
{
Demo d1 = new Demo(10);
Demo d2 = new Demo(20);
System.out.println(d1); 
System.out.println(d2);
}

}
Output:





Observe above program output JVM automated generated numbers displayed. So to get our own number we have to override hashCode(). Let us Rewrite the above program as fallows:

Example:

class Demo
{
int a;
Demo(int a)
{
this.a = a;
}
public int hashCode()
{
return a;
}
public String toString()
{
return a + "";
}
public static void main(String arg[])
{
Demo d1 = new Demo(10);
Demo d2 = new Demo(20);
System.out.println(d1); 
System.out.println(d2);
}
}

Output:





5) clone():

The process of creating exactly duplicate object is called cloning. 


Example:

class Demo implements Cloneable
{
int x = 10;
int y = 20;
public static void main(String arg[])throws CloneNotSupportedException
{
Demo d1 = new Demo();
Demo d2 = (Demo)d1.clone();
d1.x = 100;
d1.y = 200;
System.out.println(d2.x+"----"+d2.y); 
}
}

Output:





6) finalize():

This method is called by garbage collector on an object when garbage collection determine that there are no more reference to the object.

7) notify():

This method is used to wake up single thread that is waiting on the object's monitor.

8) notifyAll():

This method is used to wake up all the threads that are waiting on the object's monitor.

9) wait():

This method causes to waits to be notified by another thread of a change in this object.

I hope you enjoy this post and Let me know your comments on this post and share this to your friends,keep follow me for latest updates.

Sunday, May 26, 2019

Difference Between For loop and for each loop in java with examples

In this post i am sharing what is for loop and for each loop and difference between them with examples.

In any programming language, loops are used to execute block of statements until the condition becomes false.For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5.


  1. It starts with the keyword for like a normal for-loop.
  2. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  3. In the loop body, you can use the loop variable you created rather than using an indexed array element.
  4. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

Example 1:

For each loop 

Syntax: for(data_type variable : array | collection){}

For each loop traversing the array elements:






Example 2:

For each loop traversing the Collection elements:




For loop:


The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.


for(initialization;condition;increment/decrement){
//statement or code to be executed
}

Example:



Difference Between for loop and for each:

The for loop is present from the start i.e. JDK 1, but enhanced for loop was added on Java 5, hence it's only available from JDK 5 onward.


The enhanced for loop executes in sequence. i.e  the counter is always increased by one, where as in for loop you can change the step as per your wish e.g doing something like i=i+2; to loop every second element in an array or collection.


The enhanced for loop can only iterate in incremental order. we cannot configure it to go in decrements. i.e in for loop we can write i-- in step counter to go backward.

If we have a requirement that array should be displayed sequence in the forward direction and we also don't want to change the real value in the array accidentally or intentionally by any user etc then we should use the enhanced for loop.


let me put short answer:

 If you only want to iterate over elements from an array or a collection e.g. a list or a set then use enhanced for loop, it's convenient and less error prone, but if you want more control over iteration process then use traditional for loop. 

Monday, March 26, 2018

Local variable in Java With Examples

In this post you will learn how to declare local variable and their behavior in the java program.In Java, there are many places to declare variables. You can declare them at the start of the program, within the main method, inside classes, and inside methods or functions. Depending on where they are defined, other parts of your code may or may not be able to access them.

 A local variable is a variable declared inside a method body, block or constructor. It means variable is only accessible inside the method, block or constructor that declared it.

Declaration of local variable:

Every local variable declaration statement is contained by a block ({ … }). We can also declare the local variables in the header of a “for” statement. In this case it is executed in the same manner as if it were part of a local variable declaration statement.

For example: for(int i=0;i<=5;i++){……}

In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.

Syntax:

methodname()
{
data type  localvarname;
-----------
-----------
}

Here method name is the name of method, Data Type refers to data type of variable like int, float etc and localvar Name is the name of local variable.

can we use local variables before they are initialized?Consider following program.

class LocalVariable
{
     public static void main(String[] args)
     {
          int a;
          System.out.println(a);
          a=10;
     }
}
If you try to compile above program, you will get a compile time error : i may not have been initialized. Because, any variable, global or local, should have some value before they are used. If you don’t initialize global variables explicitly, they take default values. But, If you don’t initialize local variables explicitly, they don’t take default values. They remain uninitialized until you initialize them explicitly. Therefore, local variables will not be having any value until they are initialized explicitly. Therefore, when you use local variables before they are initialized, you get compile time error. That’s why we can’t use local variables before they are initialized.

Note: To make the above program error free, put a=10 before System.out.println(a).

Important points to remember:

Access modifiers cannot be used for declaring local variables.
Default values are not assigned to a local variables in Java.
Local variables are declared in a blocks, methods or constructors.
Local variables are created when the block, method or constructor is started and the variable will be destroyed once it exits the block, method or constructor.

 

Friday, February 16, 2018

Java Break and Continue Statements with example

In this post you will learn about break and continue statements in java with some examples.
The break statement is used to "break" out of the innermost switch, for, while, or do-while statement body. When it is executed, a break statement causes the flow of control to jump to the next line after the loop or switch to the body containing the break.

The typical use of a break statement has the following simple syntax:
break;

The break statement can also be used in a labeled form to jump out of an outernested loop or switch statement. In this case, it has the syntax
break label;

where label is a Java identifier that is used to label a loop or switch statement. Such a label can only appear at the beginning of the declaration of a loop. There are no other kinds of "go to" statements in Java.

We illustrate the use of break statement in the following simple example:
public class Break
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;    // terminate loop if i is 5
}
System.out.print(i + " ");
}
System.out.println("stop the loop here");
}
}

Output:
1 2 3 4 stop the loop here

Continue Statement:
The other statement to explicitly change the flow of control in a Java program is the continue statement, which has the following syntax:
 
continue label;

where label is an optional Java identifier that is used to label a loop. As mentioned above, there are no explicit "go to" statements in Java. Likewise, the continue statement can only be used inside loops (for, while, and do-while). The continue statement causes the execution to skip over the remaining steps of the loop body in the current iteration (but then continue the loop if its condition is satisfied).

Example:

public class ContinueTest
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue;    // skip next statement if i is even
}
System.out.println(i + " ");
}
}
}
Output:
1 3 5 7 9

Wednesday, February 14, 2018

Java new operator with example

In this post you will learn how to use new operator in java with example.In Java, a new object is created from a defined class by using the new operator. The new operator creates a new object from a specified class and returns a reference to that object. In order to create a new object of a certain type, we must immediately follow our use of the new operator by a call to a constructor for that type of object.

Let us understand this topic with the following example:

public class Demo
{
public static void main(String args[])
{
Counter c;//declares the variable c to be of type Counter that means c can refer to any Counter object
Counter d=new Counter();//creates a new Counter object and returns a reference to it
c=new Counter();//creates a new Counter object and returns a reference to it
d=c;
}
}

Calling the new operator on a class type causes three events to occur:

  • A new object is dynamically allocated in memory, and all instance variables are initialized to standard default values. The default values are null for object variables and 0 for all base types except boolean variables (which are false by default).
  • The constructor for the new object is called with the parameters specified. The constructor fills in meaningful values for the instance variables and performs any additional computations that must be done to create this object.
  • After the constructor returns, the new operator returns a reference (that is, a memory address) to the newly created object. If the expression is in the form of an assignment statement, then this address is stored in the object variable, so the object variable refers to this newly created object.

Monday, February 12, 2018

How to declare class in Java

In this post you will learn how class is declared in java which is basic knowledge for beginners.an object is a specific combination of data and the methods that can process and communicate that data. Classes define the types for objects; hence, objects are sometimes referred to as instances of their defining class, because they take on the name of that class as their type.

Let's understand how to define a class with example. In this example a counter class for a simple counter,which can be accessed,incremented and decremented.

Example:

public class Counter{
protected int count;//a simple integer instance variable
Counter(){ //the default constructor for a counter object
count=0;
}
/** An accessor method to get the current count*/
public int getCount(){
return count;
}
/** A modifier method for incrementing the count */
public void incrementCount()
{
count++;
}
/**A modifier method for decrementing the count */
public void decrementCount()
{
return count--;
}

In the above example,notice that the class definition is delimited by braces, that is, it begins with a "{" and ends with a "} ". In Java, any set of statements between the braces "{" and "}" define a program block.

The Counter class is public, which means that any other class can create and use a Counter object. The Counter has one instance variable—an integer called count. This variable is initialized to 0 in the constructor method, Counter, which is called when we wish to create a new Counter object (this method always has the same name as the class it belongs to). This class also has one accessor method, getCount, which returns the current value of the counter. Finally, this class has two update methods—a method, incrementCount, which increments the counter, and a method, decrementCount, which decrements the counter.

Class modifiers are optional keywords that precede the class keyword. We have already seen examples that use the public keyword. 

In general,the different class modifiers and their meaning is as follows:

abstract: It is a class modifier describes a class that has abstract methods.Abstract methods are declared with the abstract keyword and are empty that means without defining a body of code for this method.

final: final class modifier describes a class that can have no subclasses.

public: public class modifier describes a class that can be instantiated or extended by anything in the same package or by anything that imports the class.

Public classes are declared in their own separate file called classname. java, where "classname" is the name of the class.

If the public class modifier is not used, the class is considered friendly. This means that it can be used and instantiated by all classes in the same package. This is the default class modifier

Wednesday, January 17, 2018

Java flatMap with example

In this post you will learn what is flatMap in Java8 and where we used flatMap. flatMap is a intermediate operation,which returns a new stream. Intermediate operations are classified as stateless and stateful operations based on need for sharing the information between elements while processing.

As per the Javadoc......

public <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) This is an intermediate operation.

The following example understand you how to use flatMap in java8.The same example if you write before java 8 then you could write multiple loops. But in Java 8 it could be like this

Example:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FlatMapExample {
public static void main(String args[]) {
List<Zoo> zooList = new ArrayList<>();
Zoo nationalZoo = new Zoo("National");
nationalZoo.add("Lion");
 nationalZoo.add("Tiger");
 nationalZoo.add("Peacock");
      nationalZoo.add("Gorilla");

        Zoo aCountyZoo = new Zoo("Wills County");
        aCountyZoo.add("Peacock");
        aCountyZoo.add("Camelion");

        zooList.add(nationalZoo);
        zooList.add(aCountyZoo);

        // to get the aggregate
 List<String> animalList = zooList.stream()
                .flatMap(element -> element.getAnimals().stream())
                .collect(Collectors.toList());
System.out.println(animalList);

        // to get the unique set
Set<String> animalSet = zooList.stream()
                .flatMap(element -> element.getAnimals().stream())
                .collect(Collectors.toSet());
System.out.println(animalSet);
}
}
class Zoo {
private String zooName;
private Set<String> animals;
public Zoo(String zooName) {
this.zooName = zooName;
this.animals = new HashSet<>();
}
public void add(String animal) {
this.animals.add(animal);
}
public Set<String> getAnimals() {
return animals;
}
}

Output:
[Peacock, Lion, Tiger, Gorilla, Peacock, Camelion]
[Peacock, Lion, Tiger, Gorilla, Camelion]

Imagine that you want to create the following sequence: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 etc. (in other words: 1x1, 2x2, 3x3 etc.)

With flatMap it could look like:


IntStream sequence = IntStream.rangeClosed(1, 4)
                          .flatMap(i -> IntStream.iterate(i, identity()).limit(i));
sequence.forEach(System.out::println);

where:

IntStream.rangeClosed(1, 4) creates a stream of int from 1 to 4, inclusive
IntStream.iterate(i, identity()).limit(i) creates a stream of length i of int i - so applied to i = 4 it creates a stream: 4, 4, 4, 4
flatMap "flattens" the stream and "concatenates" it to the original stream

With Java < 8 you would need two nested loops:

List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
    for (int j = 0; j < i; j++) {
        list.add(i);
    }
}

Friday, January 8, 2016

What is STACK in Java with Algorithm and Example

STACK:

Stack is a linear Data Structure. It represents group of elements stored in LIFO(Last In First Out) Order.This means the element which is stored as  last element into the stack will be the first element to be removed from the stack. In this insertion & deletion of an element can be done at the same end (only one end).Stack is a static (or) dynamic Data Structure. It is very useful to solve the arithmetic expressions,memory management operation.

Also Read :  Introduction to Data Structure in java


  • In Stack recently entered  element is treated as a TOP element.
  • If you want to  insert an element into the Stack is called as PUSH Operation
  • If you want to Delete an element from the Stack is called as POP operation
  • Visit or Display the element in the Stack is called Traverse Operation.
  • If we push more elements than the Stack size then it is called as Stack is Overflow
  • If we want to delete the element from the empty Stack then it is called as Stack is Underflow

Stack can be represented in two ways: They are

a)Linear Stack
b)Linked Stack

a) Linear Stack:

The Stack that is implemented  by using Arrays is called "Linear Stack" The representation of Linear Stack is as follows.

















In the above representation Stack contains four elements like A,B,C,D. In that 'D' is a top element because it it a recently entered element.
The fallowing are the operation on the linear stack. They are

1)Push
2)Pop
3)Traverse

1.Push:

In Stack, 'Push' is nothing but Insertion. That means inserting an element in the Stack is called Push Operation.In this first we check the condition either Stack is full or not,if the Stack is full then it display the message as "Stack is Overflow". It the Stack is not full we can insert an element into the Stack by Increasing the TOP position and assigning that number at TOP Position. 

Algorithm:
Push(num)

Step 1: Start
Step 2: if(top=size-1) then Print "Stack is Overflow"
Step 3: else
             set top=top+1
             set Stack[top]=num
Step 4: End


2)Pop:

In Stack 'Pop'  is nothing but "Deletion". That means deletion of an element from the stack is called 'Pop' operation.In this first we check the condition either "Stack is empty or not".
It it is empty then display a message as "Stack is empty" or Stack is Under flow". If it is not empty then delete the element in the TOP position and decrease Top Position.

Algorithm: pop(num)

Step 1: Start
Step 2: if(top==-1)then print "Stack is empty"
Step 3:else
             delete stack[top]
              set top=top-1
Step 4: End

3.Traverse:

Display each and every element from the stack is called "traverse" Operation. In this we display the elements from the first element(top) to the last element.

Algorithm:

Step 1: Start
Step 2: set i=top
Step 3:Repeat the steps 4&5 until while(i>=0)
Step 4: print Stack[i]
Step 5:i=i-1
Step 6:End

b) Linked Stack:

The Stack that is implemented by using "Links or Pointers" is called "Linked Stack". The representation of Linked Stack is as fallows.























In the above stack contains four Nodes like 1,2,3,4. On that the fourth node is the top node,because it is recently entered element. 
The fallowing are the operations on the linear Stack. They are

1. Push
2. Pop
3. Traverse

1. Push:

In Stack, 'Push' is nothing but Insertion. That means inserting an element in the Stack is called Push Operation. In this first we check the condition either "Stack is empty or not". If stack is empty then insert a new node and assign the NULL pointer to the Link. Otherwise insert a new node and assign the next node address to the Link.

Algorithm:Push(num)

Step 1: Start
Step 2: if(top==NULL) then
             t=new Node
              t----->data=num
              t------>link=Null
             Set top=t

Step 3: else
             t=new node
             t----->data=num
             t----->link=top
             set top=t
Step 4:  End

2. Pop:

In Stack "POP" is nothing but 'Deletion'. That means deletion of an element from the Stack is called Pop Operation. In this first we check the condition either "Stack is empty or not". If Stack is empty then display the message as 'stack is empty or Stack is undrflow'. If it is not empty then delete the Top node and assign next node address to the Top.

Algorithm: pop(num)

Step 1: Start
Step 2:if(top==Null)then print "Stack is empty"
Step 3: else
              Set t=top
              top=top---->link
              delete t
Step 4: End


3. Traverse:

Display each and every element from the stack is called "Traverse" Operation. In this we display the elements from the first element(top)to the last element.

Algorithm: Traverse(num)

Step 1: Start
Step 2: set t=top
Step 3: repeat the steps 4&5 until while(t!=Null)
Step 4: print t---->data
Step 5: t=t----->link
Step 6: End

Example:
To perform different operations on a stack through a menu.

import java.io.*;
import java.util.*;
class StackDemo{
public static void main(String args[]) throws Exception
{
//create an empty stack to contain integer objects
Stack<Integer> st=new Stack<Integer>();
//take vars
int choice=0;
int position,element;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//display the meau as long as user choice<4
while(choice<4)
{
System.out.println("Stack Operations");
System.out.println("1.push");
System.out.println("2.pop");
System.out.println("3.search");
System.out.println("4.exit");

choice=Integer.parseInt(br.readLine());
//perform a task depending on user choice

switch(choice){
case 1: 
System.out.printlnk("enter element:");
element=Integer.parseInt(br.readLine());
//int type element converted into Integer object and then pushed into the stack
st.push(element);
break;
case 2: 
// the top-most Integer Object is popped
Integer obj=st.pop();
System.out.println("popped object:"+obj);
break;
case 3: 
System.out.println("which element?");
element=Integer.parseInt(br.readLine());

 //int type element converted into Integer object and then pushed into the stack
position=st.search(element);
if(position==-1)
System.out.println("element not found");
else
System.out.println("position"+position);
 break;
default:
//come out if user choice is other than 1,2,3
return;
}
System.out.println("stack contents"+st);
}
}
}
              

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...