Wednesday, November 30, 2016

How to Use methods in Java?

In this article,we will discuss about Java methods and what is the use of methods and how to call methods in java. A method  is a group of statements that perform a task. Here task means processing of data or calculation etc..

method syntax:

returndatatype  methodname(parameter-list)
{
//body of method;
}

In the above syntax method contains two parts: they are
  • method header
  • method body
method header:

It contains method name  that means name given to the method. After method name,we write some variables list in the braces. These variables are called parameters. These parameters are useful to receive data from outside into the method. Return data type is written before method name to represent what type of data the method is returning.

Let us Understand some methods with examples:

void add():

This method is not accepting any data from outside. Since after the method name we write empty braces(). This method does not return any value. So void is written before the method name. Here void means "no value".

we can call this method by using Objectname.methodname that means obj.add(),probably to calculate adding numbers and displaying result.



method body:

Whatever has below the method header is nothing but body of method. Method body consists of a group of statements which contains logic to perform the task.

Example:
{
statements;
}

In the above diagram we want to write a method that calculates adding of two numbers. Observe the method header,that method does not accept any values,we did not declare any parameters in the braces(). SO, this method does not return any values.







Recommended to Read: What is class and Object in Java?


How to call methods in Java:

Let us understand this concept with example:

class Test
{
private int a,b;
Test(int x,int y)
{
a=x;

b=y;
}
//method to calculate sum of a,b
void sum()
{
int res=a+b;
System.out.println("sum="+res);
}
}
class methods
{
public static void main(String[] args)
{
//create object and pass values 10 and 20 to constructor they will stored into a,b
Test t=new Test(10,20);
t.sum();
}
}

Output:

Java Program to find IP address of Website

In this page we will understand and learn How to get IP address of any website by using Java programming language. Java Networking API provides the method to know IP address of any website. It is possible to know the IP address of website on Internet with the help of getByName() method of InetAddress class of java.net package. The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. The InetAddress also includes the factory method getByaddress(),which takes an IP address and returns an InetAddress object. Either an IP4 or IP6 address can be used.




Let us understand and learn the concept with the fallowing example:

import java.io.*;
import java.net.*;
class InetAdressTest
{
public static void main(String[] args)throws UnknownHostException,IOException

{
BufferedReader br=new BufferedReader(new InputStreadReader(System.in));
System.out.println("enter a website name:");
String website=br.readLine();
try
{
InetAddress ip=InetAddress.getByName(website);
System.out.println(" The IP address is:"+ip);
}
catch(UnknownHostException ue)
{
System.out.println("Website not found");
}
}
}

Output:

I hope you enjoy this page and keep follow my blog for latest updates and share post to your friends through social websites like Facebook,google+,linkedin  etc... also comments about your answers on this concept.






Tuesday, November 29, 2016

How does System.out.println works in Java

In this post,we will understand and learn How does System.out.println works in Java. Earlier, i have shared what is main() method in java and how it works?. Today, we will learn what is the use of System.out.println and how it works. Some times Interviewer asks you when you are interview room What is System.out.println explain it individually. So you must be in a position to explain him about each part in it.


The above line is used to display message to the command window. Now, we will understand from the above line one by one

System:

System is a predefined class in  java.lang package that provides access to the system.This class contains final modifier that means it can not be inherited by other classes.

Out:  
It is a static variable in System class. out is called a field in System class,when we call this field, a PrintStream class object will be created internally. So, we can call the print() method as shown below.

Example:  System.out.print("hi java");

Thus, the expression System.out refers to Object an type PrintStream. 

println():

It is a public method in PrintStream class to display the data values.



Let us understand this concept with example then you can understand easily:

class Demo
{
public static void
main(String[] args)

{
System.out.println("Hello Java");
}
 

 The main aim of writing above program is simply display a string "Hello Java". In java, print() method is used to display something on the console. 

print("Hello Java");

But the above statement is not the correct way of calling a method in java. A method should be called by using Objectname.methodname(). So to call print()method,we should create an object to the class to which print() method belongs. Here print() method belongs to PrintStream class, so,we should call print() method by creating an object to PrintStream class like below:

PrintStream obj.print("Hello Java");

But it is not possible to create the object PrintStream class directly,an alternative is given to us. That is System.out.

System.out gives the PrintStream class object. This object,by default represents the standard output device that is monitor.So the string"Hello Java" sent to the monitor.

Note:  Every Java Statement in Program ends with semicolon(;)


I hope you enjoy this page and follow me for latest updates and share this post in social media like facebook,linkedin,twitter..



 




 


TOP 10 Java Pattern Programs

In this page, we will understand and learn different star and number java pattern programs. These pattern programs frequently asked in written Test and Technical interview to test your programming skills and way of your logic you applied to solve real time problems. Having knowledge on for loop,nested loop and while loop very useful to solve pattern programs in java. Let us understand with pattern programs how to use for loop and nested for loop in our pattern programs

1) How to print Star pyramid pattern in Java?

class StarPattern
{
public static void main(String[] args)
{
for(int i=0;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}//this is end of main() method
}//this is end of class

Output:











2)  How to print star pyramid pattern like below output:





class StarPattern1
{
public static void main(String[] args)
{

for(int i=0;i<=5;i++)
{
for(int j=5;j>=i;j--)
{
System.out.print("*");
}
System.out.println();
}
}
}//this is end of class

Output:











3) How to print Star pyramid pattern like below result?






class StarPattern2
{
public static void
main(String[] args)
{
int
n=7;
int
z=7;
for(int i=1;i<=n;i++)
{
for(int j=1;j<i;j++)
{
System
.out.print(" ");
}
for(int k=1;k<=z;k++)
{
System
.out.print("*");
}
z--;
System
.out.println();
}
}
}


Output:











5) How to print Star Pyramid pattern like below result?










class
StarPattern3
{
public static void
main(String[] args)
{
int size=5;
for
(int i=size;i>=-size;i--)
{
for
(int j=size;j>=Math.abs(i);j--)
{
System
.out.print("*");
}
System
.out.println();
}
}
}


Output:















6) How to print Number Pyramid in java like below result?







class NumberPattern
{
public static void main(String[] args)
{
int n=7;
int z=1;
for(int i=0;i<n;i++)
{
for(int j=n-1;j>i;j--)
{
System.out.print(" ");
}
for(int k=1;k<=z;k++)
{
System.out.print(k);
}
z=z+2;
System
.out.println();
}
}
}
 

Output:











7) How to print Number Pyramid in java like below result?










class NumberPattern1
{
public static void main(String[] args)
{
int size=5;
int i,j,k;
for(i=size;i>=-size;i--)
{
for(j=1;j<=Math.abs(i);j++)
{
System.out.print(" ");
}
for(k=Math.abs(i);k<=size;k++)
{
System.out.print(k);
}
System
.out.print("\n");
}
}
}


Output:












8) How to print Number Pyramid pattern in java like below result?







class NumberPattern2
{
public static void
main(String[] args)
{
for
(int i=1;i<=5;i++)
{
for
(int k=4;k>=i;k--)
{
System
.out.print(" ");
}
for
(int j=1;j<=i;j++)
{
System.
out.print(i+" ");
}
System
.out.println();
}
}
}


Output:







9) How to Print Number Pyramid pattern in java like below result?









class NumberPattern3 
{
public static void main(String[] args) 
{
int n=5;
int z=1;
for(int i=0;i<n;i++)
{
for(int j=n-1;j>i;j--)
{
System.out.println("");
}
for(int k=1;k<=z;k++)
{
System.out.print(z);
}
z=z+2;
System.out.println();
}
}

}
Output:














10) How to Print Number Pyramid pattern in Java like below result?










class NumberPattern4
{
public static void main(String[] args) 
{
int size=3;
int i,j;
for(i=size;i>=-size;i--)
{
for(j=size;j>=Math.abs(i);j--)
{
System.out.print(j);
}
System.out.println("\n");
}
}
}

Output:


Monday, November 28, 2016

main method in Java

In this page, we will discuss about Java main method and why main method has public static void. What does the main method in java? we will learn all these things in this page. Every Java Developer should have knowledge on this concept.

Whether the class contains main() method  or not and whether main() method properly declared or not . These checking are not responsibility of compiler. But at run time JVM is the responsible to perform these checking. In case JVM unable to find require main method then we will get runtime exception saying NoSuchMethodError:main 

Example:

class Test
{
}
Output:




JVM always searches for the main() with the fallowing signature only:



In the above code begins defining main() method. This is the line where program will start execution.

public:
 In the main() method signature the first one that is public keyword is an access specifier,which allows the programmer to control  visibility of the class members.That means it is called by JVM from any where. So, must be declare main() method as public,because it must be called by code outside of its class.




static:
Every java program's main() method has to be declared static , since the keyword static allows without existing object also JVM has to call this method. If you don't declare static keyword in method signature program will compile successfully but at run time it will report an error.

void:

The keyword void tells the compiler will not return anything to JVM.

main:

It is name of the method which is configured inside JVM. Java is a case-sensitive language that means Main() is different from main() method.So, you must declare main() method as specified in Java Programming language.

String[] args:

String [] args means in main() method signature is array of Strings. Here args contains the supplied command line arguments as an array of String objects.
Instead of args we can take any valid java identifier. We can replace String[] with var-arg parameter
Example:
public static void main(String...args)

Note: 
we can change the order of modifiers that is instead of public static,we can take static public

I hope you enjoy this page and follow me more updates and write your comments with your valuable answers.



Sunday, November 27, 2016

SCJP Java Interview Questions Part-II

Today, I am sharing Java SCJP/OCJP Written Test Interview Questions with answers,earlier i have shared SCJP/OCJP Interview Questions part-I. In this page we will discuss more SCJP interview Questions more. Those are preparing to appear SCJP/OCJP Written Test,they should brush up these questions and my earlier post as well. 

1) int[] myArray=new int[]{1,2,3,4,5}; What allows you to create a list from this array?

Ans:

A. List myList=myArray.asList();
B. List myList=Arrays.asList(myArray);
C. List myList=new ArrayList(myArray);
D. List myList=Collections.fromArray(myArray);

Answer: B

2)
 class A
{}
class B extends A{}
class C extends B{}
class D extends B{}
which three statements are true?(choose three)

A. The type List<A>is assignable to List
B. The type List<B>is assignable to List<A>
C. The type List<Object>is assignable to List<?>
D. The type List<D> is assignable to List<?extends B>
E. The type List<?extends A>is assignable to List<A>
F. The type List<Object>is assignable to any List reference
G. The type List<?extends B>is assignable to List<?extends A>

Answer: CDG

3) 

public static void search(List<String> list)
{
list.clear();
list.add("b");
list.add("a");
list.add("c");
System.out.println(Collections.binarySearch(list,"a"));
}

What is the result of calling search with a valid List implementation ?

A. 0
B. 1
C. 2
D. a
E. b
F. c
G. The result is undefined

Answer: G

4)

public class person
{
private name;
public Person(String name)
{
this.name=name;
}
public int hashCode()
{
return 420;
}
}
Which statement is true?

A. The time to find the value form HashMap with a Person Key depends on the size of the map.

B. Deleting a Person Key form a HashMap will delete all map entries for all keys of type person.

C. Inserting a second Person Object into a HashSet will cause the first Person object to be removed as a duplicate.

D. The time to determine whether a Person object is contained in a HashSet is constant and does NOT depend on the size of the map.

Answer: A

5)

23. HashMap props=new HashMap();
24. props.put("key45","some value");
25. porps.put("key12","some other value");
25. props.put("key39","yet another value");
26. Set s=props.keySet();
27.//insert code here

What,inserted at line 27,will sort the keys in the props HashMap?

A. Arrays.sort(s);
B. s=new TreeSet(s);
C. Collections.sort(s);
D. s=new Sortedset(s);

Answer: B

6) 

11.Object[] myObject={new Integer(12),new String("abc"),new Integer(15),new 12.Boolean(true)};
13.Arrays.sort(myObject);
14.for(int i=0;i<myObject.length;i++)
15.System.out.println(myObject[i].toString());
16.System.out.println(" ");
}
What is the result?

A. Compailation fails due to an error in line 11
B. Compilation fails due to an error at line 13
C. A ClassCastException occurs in line 13
D. A ClassCastException occurs in line 15
E. The value of all four objects prints in natural order

Answer: C

7)

import java.util.*;
public class Old{
public static Object get0(List list){
return list.get(0);
}
}
Which three will compile successfully?(choose three)


A. Object o=Old.get0(new LinkedList());
B. Object o=Old.get0(new LinkedList<?>());
C. Object o=Old.get0(new LinkedList<String>());
D. Object o=Old.get0(new LinkedList<Object>());
E. String s=(String)Old.get0(new LinkedList<String>());

Answer: A,D,E

8)
Which two statements are true about the hashCode method?(Choose two)?

A. The hashCode method for a given class can be used to test for object equality and object inequality for that class

B. The hashCode method is used by the java.util.SortedSet collection class to order the elements within that set.

C. The hashCode method for a given class can be used to test for object inequality,but Not object equality,for that class.

D. The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.

Answer: C,D

9)

A programmer has an algorithm that requires a java.util.List that provides an efficient implementation of add(0,object),but does NOT need to support quick random access.

What supports these requirements?

A. java.util.Queue
B. java.util.ArrayList
C. java.util.LinearList
D. java.util.LinkedList

Answer: D

10)

public static void before(){
Set set=new TreeSet();
set.add("2");
set.add("3");
set.add("1");
Iterator itr=set.iterator();
while(itr.hasNext())
System.out.println(itr.next()+" ");
}

Which of the following statements are true?

A. the before() method will print 1 2
B. the before() method will print 1 2 3
C. the before() method will print three numbers,but the order cannot be determined
D. the before() method will not compile
E. the before() method will throw an exception at runtime.

Answer: E

Explanation: E is correct,you can not put both String and int into the same TreeSet. Without generics,the compiler has no way of knowing what type is appropriate for this TreeSet,so it allows everything to compile. At runtime, the TreeSet will try to sort the elements as they are added,and when it tries to compare an Integer with a String it will throw a ClassCastException. Note that although the before() method does not use generics,it does use autoboxing.



Linux Interview Questions and Answers

In this article we will discuss Basic Linux Interview Questions for freshers. These Questions are frequently asked interview questions in Written Test and Technical Interview as well. Now a days in many competitive examination and entrance Test they are preferring from Linux Operating System Concept.

1) What is Linux?

Ans: Linux is Open Source Operating System based on UNIX. It was first introduced  by Linus Torvalds. It is based on the Linux Kernal,and can run on different hardware platforms manufactured by Intel,HP,IBM,SPARC and Motorola.

2) What is the difference between UNIX and Linux?

Ans: Unix originally began as a propriety operating system from Bell Laboratories developed by Dennis Ritche in 1969,which later on spawned into different commercial versions. On the other hand, Linux is free,open source and intended as a non-propriety operating system for the masses.

3) What is Linux Kernal?

ANS:  The Linux Kernal is a low-level systems software whose main role is to manage hardware resources for the user. It is also used to provide an interface for user-level interaction

4) What is the advantage of Open Source?

Ans: Open Source allows you to distribute your software,including source codes freely to anyone who is interested. People would then be able to add features and even debug and correct errors that are in the source code. They can even make it run better,and then redistribute these enhanced source code freely again.This eventually benefits everyone in the community.

5) What are the basic components of Linux?

Ans: Linux has all of these components: Kernal,shells and GUIs,System Utilities and application program. What makes Linux advantage over other OS is that every aspect comes with additional features and all codes for these are downloadable for free.

6) Does it help for a Linux system to have multiple desktop environment installed?

Ans: In general, one desktop environment like KDE or Gnome, is good enough to operate without issues. It is all a matter of preference for the user,although the system allows switching from one environment to another. Some programs will work on one environment and not work on the other,so it could also be considered a factor in selecting which environment to use.



7) What is BASH?

Ans: BASH means Bourne Again SHell. It was written by Steve Bourne as a replacement to the original Bourne Shell. It combines all the features from the original version of Bourne Shell,plus additional functions to make it easier and more convenient to use. It has since been adapted as a default shell for most systems running Linux.

8) How do you open a command prompt when issuing a command?

Ans: Top open the default shell(which is where the command prompt can be found). Press Ctrl-Alt-F1. This will provide a command line interface(CLI)from which you can run commands as needed

9)  How can you find out how much memory Linux is using?

Ans: From a command shell, use the "concatenate"command:cat/proc/meminfo for memory usage information. You should see a line starting something like Mem:5488989 etc..This is the total memory Linux thinks it has available to use

10) Does the Ctrl+Alt+Del key combination work on Linux?

Ans: YES, it does. Just Like Windows,you can use this key combination to perform a system restart. One difference is that you won't be getting any confirmation message and therefore,reboot is immediate.

11) How do you change permission under Linux?

ANS:  Assuming you are the system administrator or the owner of a file or directory,you can grant permission using the chmod command. Use + symbol to add permission or - symbol to deny permission,along with any of the fallowing letters:u(user),g(group),o(others),a(all),r(read),w(write)and x(execute).

12) How do you access partitions under Linux?

Ans: Linux assigns numbers at the end of the drive identifier. For example,if the first IDE hard drive had three primary partitions they would be named/numbered,/dev/hda1,/dev/hda1 and /dev/hda3

13) How do you share a program across different virtual desktops under Linux?

Ans:  To share a program across different virtual desktops, in the upper left-hand corner of a program window look for an icon that look like a pushpin. Pressing this button will "pin" that application in place,making it appear in all virtual Desktops in the same position onscreen.

14) What is grep command?

Ans:  grep command is a search command that makes use of pattern-based searching. It makes use of options and parameters that is specified along the command line and applies this pattern into  searching the required file output.

15) How do you terminate ongoing process?

Ans: Every process in the system is identified by a unique process Id or PID. Use the kill command followed by the pid in order to terminate that process.To terminate all process at once,use kill 0.

16)  How do you execute more than one command or program from a single command line entry?

Ans: You can combine several command by separating each command or program using semicolon symbol. For example, you can issue such a series of commands in a single entry:
ls l;wc file1;date

17) Write a shell command to find out the number of characters,words and lines in a ls -l output?

Ans: ls -l\=|WC

18) What are the contents in /usr/local?

Ans: It contains locally installed files. This directory actually matters in environment where files are stored on the network.

19) What are daemons?

Ans: Daemons are services that provide several functions that may not be available under the base OS. It's main task is to listen for service request and at the same time to act on these requests. After the service is done,it is then disconnected and waits for further requests.

20)What are hard Links?

Ans:  Hard Links point directly to the physical file on the disk,and not on the path name. This means that if you rename or move the original file,the link will not break,since the link is for the file itself,not the path where the file is located.

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...