How to call non static method from static method java

  • Class is a template and when we create object instance variables gets memory.
  • If we create two objects variables get memory in two objects. So instance variables gets memory whenever object is created.
  • When we create variables as static , memory will not be created in objects because static means class level and it belongs to class not object but we can access static variables and static methods from objects.
  • Calling static method from non static method in java 
  • In our scenario calling a non static method from static method in java.
  • If we are calling a non static method then we need to use object so that it will call corresponding object non static method.
  • Non static methods will be executed or called by using object so whenever we want to call a non static method from static method we need to create an instance and call that method.
  • If we are calling non static method directly from a static method without creating object then compiler throws an error. 



Program #1: Java example program to call non static method from static method. 


calling non static method from static method.png

  • In the above program we are trying to call non static method of class from a static method so compiler throwing error.
  • Can not make a static reference to the non- static method nonStaticMethod() from the type StaticMethodDemo
  • So without object we can not cal non static method of a class.
  • Check the below example program calling non static method from static method by creating object of that class and on that object calling non static method.

Program #2: Java example program to call non static method from static method.

  1. package com.instanceofjava.staticinterviewquestions;
  2. //www.instanceofjava.com
  3.  
  4. public class StaticMethodDemo {
  5.  
  6.     
  7.     void nonStaticMethod(){
  8.         System.out.println("non static method");
  9.     }
  10.     
  11.     public static void staticMethod(){
  12.         
  13.         new StaticMethodDemo().nonStaticMethod();
  14.     }
  15.     
  16.     
  17.     
  18.     public static void main(String[] args) {
  19.         
  20.         StaticMethodDemo.staticMethod();
  21. }
  22.  
  23. }
   
Output:

  1. non static method

Calling static method from non static method in java

  • Static means class level and non static means object level.
  • Non static variable gets memory in each in every object dynamically.
  • Static variables are not part of object and while class loading itself all static variables gets memory.
  • Like static variables we have static methods. Without creating object we can access static methods.
  • Static methods are class level. and We can still access static methods in side non static methods.
  • We can call static methods without using object also by using class name.
  • And the answer to the question of  "is it possible to call static methods from non static methods in java" is yes.
  • If we are calling a static method from non static methods means calling a single common method using unique object of class which is possible. 


Program #1: Java example program to call static method from non static method.


  1. package com.instanceofjava.staticinterviewquestions;
  2. public class StaticMethodDemo {
  3.  
  4. void nonStaticMethod(){
  5.         
  6.         System.out.println("Hi i am non static method");
  7.         staticMethod();
  8.  }
  9.     
  10.  public static void staticMethod(){
  11.         
  12.         System.out.println("Hi i am static method");
  13.   }
  14.     
  15.  public static void main(String[] args) {
  16.         StaticMethodDemo obj= new StaticMethodDemo();
  17.         
  18.         obj.nonStaticMethod();
  19.  
  20.     }
  21.  
  22. }
 Output:

  1. Hi i am non static method
  2. Hi i am static method

  • In the above program we have created object of the class and called a non static method on that object and in side non static method called a static method.
  • So it is always possible to access static variables and static methods in side non static methods

 Program #2: Java example program to call static method from non static method.


Top 60 Hadoop interview questions and answers for freshers and experienced - Part 1

hadoop interview questions and answers for frehsers and experienced


1.What is HDFS?

  • HDFS, the Hadoop Distributed File System, is a distributed file system designed to hold very large amounts of data (terabytes or even petabytes), and provide high-throughput access to this information.
  • Files are stored in a redundant fashion across multiple machines to ensure their durability to failure and high availability to very parallel applications


 
2.What are the Hadoop configuration files?

  1.     hdfs-site.xml
  2.     core-site.xml
  3.     mapred-site.xml


3.How NameNode Handles data node failures?

  • NameNode periodically receives a Heartbeat and a Blockreport from each of the DataNode in the cluster.Receipt of a Heartbeat implies that the DataNode is functioning properly.
  • When NameNode notices that it has not received a heartbeat message from a DataNode after a certain amount of time, the DataNode is identified as dead. Since blocks will be under replicated the system NameNode begins replicating the blocks that were stored on the dead DataNode.
  • The NameNode takes responsibility of the replication of the data blocks from one DataNode to another.The replication data transfer happens directly between DataNodes and the data never passes through the NameNode.


4.What is MapReduce in Hadoop?

  • Hadoop MapReduce is a specially designed framework for distributed processing of large data sets on clusters of commodity hardware. 
  • The framework itself can take care of scheduling tasks, monitoring them and reassigning of failed tasks.

5.What is the responsibility of NameNode in HDFS ?

  • NameNode is a master daemon for creating metadata for blocks, stored on DataNodes. Every DataNode sends heartbeat and block report to NameNode.
  • If NameNode not receives any heartbeat then it simply identifies that the DataNode is dead. This NameNode is the single Point of failover. If NameNode goes down HDFS cluster is inaccessible.

6.What it  the responsibility of SecondaryNameNode in HDFS?

  • SecondaryNameNode is the mater Daemon to create Housekeeping work for NameNode.
  • SecondaryNameNode is not the backup of NameNode but it is the backup for metadata of the NameNode.

7.What is the DataNode in HDFS?

  • DataNode is the slave daemon of NameNode for storing actual data blocks. Each DataNode stores number of 64MB blocks.

8.What is the JobTracker in HDFS?

  • JobTracker is a mater daemon for assigning tasks to TaskTrackers in different DataNodes where it can find data blocks for input file.

9.How can we list all job running in a cluster?

  •  ]$ hadoop job -list

10.How can we kill a job?

  • ]$ hadoop job –kill jobid

11.Whats the default port that jobtrackers listens to

  •  http://localhost:50030

12.Whats the default port where the dfs namenode web ui will listen on

  •     http://localhost:50070

13.What is Hadoop Streaming

  • Streaming is a generic API that allows programs written in virtually any language to be used as Hadoop Mapper and Reducer implementations


14.Whats is Distributed Cache in Hadoop

  • Distributed Cache is a facility provided by the Map/Reduce framework to cache files (text, archives, jars and so on) needed by applications during execution of the job.
  • The framework will copy the necessary files to the slave node before any tasks for the job are executed on that node.

15.What is the benifit of Distributed cache, why can we just have the file in HDFS and have the application read it

  • This is because distributed cache is much faster. It copies the file to all trackers at the start of the job.
  • Now if the task tracker runs 10 or 100 mappers or reducer, it will use the same copy of distributed cache. on the other hand, if you put code in file to read it from
  • HDFS in the MR job then every mapper will try to access it from HDFS hence if a task    tracker run 100 map jobs then it will try to read this file 100 times from HDFS. Also
  • HDFS is not very efficient when used like this.


16.Is it possible to provide multiple input to Hadoop? If yes then how can you give multiple directories as input to the Hadoop job

  • Yes, The input format class provides methods to add multiple directories as input to a Hadoop job

17.What will a hadoop job do if you try to run it with an output directory that is already present? Will it overwrite it - warn you and continue - throw an exception and exit

  • The hadoop job will throw an exception and exit.


18.How can you set an arbitary number of mappers to be created for a job in Hadoop

  • This is a trick question. You cannot set it

19.How can you set an arbitary number of reducers to be created for a job in Hadoop

  • You can either do it programmatically by using method setNumReduceTasksin the JobConfclass or set it up as a configuration setting

20.How will you write a custom partitioner for a Hadoop job

  • To have hadoop use a custom partitioner you will have to do minimum the following three
  1. Create a new class that extends Partitioner class
  2. Override method getPartition
  3. In the wrapper that runs the Map Reducer, either  add the custom partitioner to the job programtically using method setPartitionerClass or add the custom partitioner to the job as a config file (if your wrapper reads from config file or oozie)

21.How did you debug your Hadoop code?

  • There can be several ways of doing this but most common ways are
  1.     By using counters
  2.     The web interface provided by Hadoop framework

22.What does the term "Replication factor" mean

  • Replication factor is the number of times a file needs to be replicated in HDFS


23.What is the default replication factor in HDFS

  • The default replication factor is 3

24. What is the typical block size of an HDFS block

  • The default HDFS block size is 64Mb or 128Mb

25.What is the benefit of having such big block size (when compared to block size of linux file system like ext)

  • It allows HDFS to decrease the amount of metadata storage required per file (the list of blocks per file will be smaller as the size of individual blocks increases). Furthermore, it allows for fast streaming reads of data, by keeping large amounts of data sequentially laidout on the disk

26.Why is it recommended to have few very large files instead of a lot of small files in HDFS

  • This is because the Name node contains the meta data of each and every file in HDFS and more files means more metadata and since namenode loads all the metadata in memory for speed hence having a lot of files may make the metadata information big enough to exceed the size of the memory on the Name node

27.What alternate way does HDFS provides to recover data in case a Namenode, without backup, fails and cannot be recovered

  • There is no way. If Namenode dies and there is no backup then there is no way to recover data

28.Describe how a HDFS client will read a file in HDFS, like will it talk to data node or namenode ... how will data flow etc

  • To open a file, a client contacts the Name Node and retrieves a list of locations for the blocks that comprise the file.
  • These locations identify the Data Nodes which hold each block. Clients then read file data directly from the Data Node servers, possibly in parallel.
  • The Name Node is not directly involved in this bulk data transfer, keeping its overhead to a minimum.

29.Using linux command line. how will you List the the number of files in a HDFS directory

  •      hadoop fs -ls

30.Using linux command line. how will  Create a directory in HDFS

  •     hadoop fs -mkdir

Big data Hadoop interview questions answers freshers and experienced - Part 2  

How to read a file in java with example program

  • We can read java file using buffered reader class in java
  • We need to import java.io.BufferedReader in order to read java text file.
  • Create object of java.io.BufferedReader class by passing new FileReader("C:\\Sample.txt") object to the constructor.
  • In order to read line by line call readLine() method of BufferedReader class which returns current line. Initially first line of java text file



 Program #1: Write a java program to read a file line by line using BufferedReader class

  1. package com.instanceofjava.javareadfile;

  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;

  5. public class ReadFileBufferedReader {

  6. /**
  7. * @Website: www.instanceofjava.com
  8. * @category: How to read java read file line by line using buffered reader
  9. */

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

  11. BufferedReader breader = null;

  12.  try {

  13. String CurrentLine;

  14. breader = new BufferedReader(new FileReader("E://Sample.txt"));

  15. while ((CurrentLine = breader.readLine()) != null) {
  16. System.out.println(CurrentLine);
  17. }

  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. } finally {
  21.     try {
  22. if (breader != null)
  23. breader.close();
  24.      } catch (IOException ex) {
  25. ex.printStackTrace();
  26.      }
  27. }

  28. }

  29. }

 Output:
 
  1. Java open and read file
  2. Read file line by line in java
  3. Example java program to read a file line by line
  4. java read file line by line example
  
Program #2: Write a java program to read a file line by line using BufferedReader class using Eclipse

how to read a file in java

Can an abstract class have a constructor in Java

  • Yes we can define a constructor in abstract class in java.

  • Then next question will come like when we can not create object of abstract class then why to define constructor for abstract class.
  • It is not possible to create object of abstract class directly but we can create object of abstract class from sub class which is actually extending abstract class.
  • When we define a abstract class a class must extend that abstract class then only there will be use of that class
  • Then when we create object of class which extends abstract class constructor of sub class will be called from that abstract class constructor will be called and memory will be created for all non static members.
  • If we are not defining any constructor default constructor will be executed.
  • So we can define any number of constructor in abstract class.
  • And it is recommended to define constructor as protected. Because there is only one scenario which we can create object is from subclass so define abstract class constructor as protected always.

Order of  execution of  constructor in Abstract class and  its sub class.

  •  When we  create object of  class which is extending abstract class then it will call abstract class constructor through sub class constructor.
  • Lest see a java example program on abstract class constructor in java

Program #1: Does abstract class have constructor???

  1. package com.instanceofjava.abstractclassconstructor;
  2. public  abstract class AbstractDemo {
  3.  
  4. AbstractDemo(){
  5.         System.out.println("No argument constructor of abstract class");
  6.  }
  7.  
  8. }


  1. package com.instanceofjava.abstractclassconstructor;
  2. public class Test extends AbstractDemo{
  3.  
  4.     Test(){
  5.         System.out.println("Test class constructor");
  6.     }
  7.     
  8. public static void main(String[] args) {
  9.         Test obj = new Test();
  10.        
  11.  
  12. }
  13.  
  14. }


Output: 

  1. No argument constructor of abstract class
  2. Test class constructor

Can we define parameterized constructor in abstract class?

  • Yes we can define parameterized constructor in abstract class.
  • But we need to make sure that the class which is extending abstract class have a constructor and it should call super class parameterized constructor
  • We can call super class parameterized constructor in sub class by using super() call
  • For example: Super(2) ;
  • What will happen if we are not placing super call in sub class constructor?
  • Compiler time error will come.

Program #2: Can we define parameterized constructor in abstract class in java?

  1. package com.instanceofjava.abstractclassconstructor;
  2. public abstract class AbstractDemo {
  3.  
  4. AbstractDemo( int x){
  5.          System.out.println("No argument constructor of abstract class x="+x);
  6.  }
  7.  
  8. }


  1. package com.instanceofjava.abstractclassconstructor;
  2. public class Test extends AbstractDemo{
  3.  
  4.     Test(){
  5.         super(10);
  6.         System.out.println("Test class constructor");
  7.     }
  8.     
  9. public static void main(String[] args) {
  10.         Test obj = new Test();
  11.        
  12.  
  13. }
  14.  
  15. }


Output:
 
  1. No argument constructor of abstract class  x=10
  2. Test class constructor

Program #3: What will happen if we are not placing super call in sub class constructor?


does abstract class have constructor in java

How to generate unique random numbers in java

  • In java we can generate random number in two ways 
  • By using Random class
  • By using Math.random



Program #1:  Java Example program to generate random numbers using random class within  the range of 1 to 10

  • First we need to create object of java.util.Random class.
  • After creating object of java.util.Random class then we need call nextInt() method by passing range
  • int range = maximum - minimum + 1;
  • int randomNum =  rn.nextInt(range) + minimum;

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Enter minimum number");
  12. int minimum=in.nextInt();
  13. System.out.println("Enter maximum number");
  14. int maximum=in.nextInt();
  15. Random rn = new Random();
  16. int range = maximum - minimum + 1;
  17. int randomNum =  rn.nextInt(range) + minimum;
  18. System.out.println("Random Number= "+randomNum);

  19. }

  20. }

Output:

  1. Enter minimum number
  2. 1
  3. Enter maximum number
  4. 10
  5. Random Number= 4


Program #2:  Java Example program to generate random numbers using Math.random  within  the range of 1 to 10

  • By using Math.random() method also we can generate random number in java
  • int randomNum = minimum + (int)(Math.random() * maximum);

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Enter minimum number");
  12. int minimum=in.nextInt();
  13. System.out.println("Enter maximum number");
  14. int maximum=in.nextInt();
  15.   
  16.   int randomNum = minimum + (int)(Math.random() * maximum);
  17. System.out.println("Random Number= "+randomNum);

  18. }

  19. }

Output:

  1. Enter minimum number
  2. 1
  3. Enter maximum number
  4. 10
  5. Random Number=5


Program #3:  Java Example program to generate 10 random numbers using Random class  within  the range of 1 to 100 using for loop.

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Random randomNumGenerator = new Random();
  11.  
  12.            for (int idx = 1; idx <= 10; ++idx){
  13.               int randomInt = randomNumGenerator.nextInt(100);
  14.               System.out.println("Random Number= "+randomInt);
  15.  
  16. }       

  17. }

  18. }

Output:

  1. Random Number= 17
  2. Random Number= 3
  3. Random Number= 74
  4. Random Number= 59
  5. Random Number= 81
  6. Random Number= 90
  7. Random Number= 2
  8. Random Number= 32
  9. Random Number= 11
  10. Random Number= 75


random number generator java




How to generate random numbers in java without repetitions

  • lets see how to generate unique random numbers in java
  • By using Collections.shuffle();


Program #4:  Java Example program to generate 4 random numbers using Random class  within  the range of 1 to 100 without duplicate / java generate unique random number between 1 and 100


  1. package com.randomnumbergenerator;


  2. public class RandomNumber {

  3. /**
  4. * @Website: www.instanceofjava.com
  5. * @category: how to generate random numbers in java within range
  6. */
  7. public static void main(String[] args) {
  8.   ArrayList<Integer> list = new ArrayList<Integer>();
  9.             for (int i=1; i<10; i++) {
  10.                 list.add(new Integer(i));
  11.             }
  12.             Collections.shuffle(list);
  13.             for (int i=0; i<4; i++) {
  14.                 System.out.println("Random Number= "+(list.get(i)));
  15.             }
  16. }       

  17. }

  18. }

Output:

  1. Random Number= 7
  2. Random Number= 3
  3. Random Number= 2
  4. Random Number= 9

Program #5:  Java Example program to generate 10 random numbers. random number generator that doesn't repeat java

  1. package com.randomnumbergenerator;


  2. public class RandomNumber {

  3. /**
  4. * @Website: www.instanceofjava.com
  5. * @category: how to generate 10 random numbers in java within range
  6. */
  7.  
  8. public static final int SET_SIZE_REQUIRED = 10;
  9.  public static final int NUMBER_RANGE = 100;
  10.  
  11.  public static void main(String[] args) {
  12.  
  13.             Random random = new Random();
  14.  
  15.             Set set = new HashSet<Integer>(SET_SIZE_REQUIRED);
  16.  
  17.             while(set.size()< SET_SIZE_REQUIRED) {
  18.                 while (set.add(random.nextInt(NUMBER_RANGE)) != true)
  19.                     ;
  20.             }
  21.             assert set.size() == SET_SIZE_REQUIRED;
  22.             System.out.println(set);
  23.         }
  24. }


Output:

  1. [48, 99, 24, 58, 44, 77, 14, 95, 31, 79]
Select Menu