Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Friday 30 June 2017

Java Main Method


Java Main Method - public static void main(String args[])

Java Main Method

Java main() is a important method in java programs and the main() method is look like public static void main(String args[]) in java.

Java main() method is the entry point of any java program i.e java main() method is a standard method which is used by JVM to start execution of any java program.

In other words, Java main() is a method and every java programs execution start from the public static void main(String args[]) i.e java main method and this java main method is called by the JVM when we execute our java program.

In java if any class contains main() method i.e public static void main(String args[]) know as main class.

Syntax of main() method :

public static void main(String args[])
{
----
----
}


Java Main Method Example

This is a simple example of java main method where we will define java main method as public static void main(String args[]). This is simple "hello world " program in java.

class JavaMainMethod
{
public static void main(String args[])//main method of java
{
System.out.println("hello world");
}
}

output : hello world

Now, let's understand each part of the main method like public , static, void and main(String args[]).

Description give below of public static void main(String args[])


Public

In java public is an access modifier and the scope of public access modifier is available everywhere in java environment. 

If we do not make any method as public, then we cannot call that method in any other program. This is the reason that we make main method public so that JVM can call main method from anywhere and execute our java program, So main method should be public.

Static

Static keyword in java which is basically used for memory management i.e to save memory or to make memory efficient. If we make any method as static then there is no need to create an object because we can call that method by using class name and this make our memory efficient because object take a memory.

To execute main method without creating object then the main method should be static so that JVM can call main method by using class name itself and when java runtime starts, there is no objects of class presents. That's why main method should be static so that JVM can call it by class name.


Void

In java void is a return type that doesn't return anything. Java main method is not returning any values and hence its return type must be void.

Main

Java main() is the name of the method where java program starts their execution, It is the entry point of any java programs.

String args[]

In java String args[] is a String array which accepts the command line arguments in the form of String values. String args[] also called command line arguments in java.


Different Ways To Writing Main Method In Java

Case 1 : Changes with public, static
  • public static void main(String args[])
  • static public void main(String args[])

Case 2 : Changes with main(String args[])
  • main(String args[])
  • main(String[] args)
  • main(String []args)
Case 3 : Changes with public static void main(String args[])

Using 3 dots(...) in main(String... s)
  • public static void main(String... s)

Q. Can We Overload Main Method In Java ?

Ans. Yes, We can overload main method in java.

Q. Can We Override Main Method In Java ?

Ans. No, We cannot override main method in java.

Q. Can We Apply Final Keyword With Main Method In Java ?

Ans. Yes, we can apply final keyword with main method e.g

final public static void main(String... s)



Share:

Wednesday 28 June 2017

Custom Exception In Java


Java Custom Exception


Custom Exception In Java

Java custom exception means to create your own exception. You can create your own exception in java which is called custom exception or user-defined exception.

You can create your own exception and massages by the help of custom exception.

Let's create simple example of custom exception

Java Custom Exception Example

This is a simple custom example where we will throw own exception.

There we will create 2 files.

//File 1 : InvalidAgeException.java

class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}

//File 2 : CustomExceptionExample.java

class CustomExceptionExample
{
static void validate(int age)throws InvalidAgeException
{
if(age < 18)
{
throw new InvalidAgeException("not valid age");
}
else
{
System.out.println("age is valid for vote");
}
}
public static void main(String args[])
{
try
{
validate(10);
}
catch(Exception e)
{
System.out.println("Exception is " +e);
}
}
}

save : InvalidAgeException.java, CustomExceptionExample.java
compile : CustomeExceptionExample.java
run : CustomeExceptionExample

output : Exception is InvalidAgeException : not valid age


In java Exception Handling, there are two types of exception :

  • checked exception : Checked exception are the exception which is checked at compile-time by the compiler is called checked exception e.g IOException, SQLException, FileNotFoundException .
  • unchecked exception : Unchecked exception are the exception which is not checked at compile-time , it is checked at run-time is called unchecked exception e.g ArithmeticException, NullPointerException, NumberFormatException, etc.

Custom Checked Exception

If the customer is able to recover from the exception, make it checked exception. When you create custom checked exception, extends java.lang.Exception.

//File 1 : NameNotFoundException.java

class NameNotFoundException extends Exception
{
NameNotFoundException(String s)
{
super(s);
}
}

//File 2 : CustomerService.java

class CustomerService
{
Customer findByName(String name)throws NameNotFoundException
{
if("".equals(name))
{
throw new NameNotFoundException("name is empty");
}
return new Customer(name);
}
public static void main(String args[])
{
CustomerService cs = new CustomerService();
{
try
{
Customer c = cs.findByName("");
}
catch(NameNotFoundException n)
{
e.printStackTrace();
}
}
}
}

Share:

Monday 26 June 2017

Collections Class In Java

Java Collections Class

Collections class in java

Collections is a class in java which is available in java.util package. Collections class inherit(extends) only Object class in java.

In java Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by specified collection and a few others odds and ends.

The methods of collections's class all throw a NullPointerException if the collections or class objects provided to them are null.

Collections class is a member of Java Collection Framework.


Declaration of Collections Class

public class Collections extends java.lang.Object


Fields

Following are fields for java.util.Collections class :

static List EMPTY_LIST : The empty list(immutable)

static Map EMPTY_MAP : The empty map(immutable)

static Set EMPTY_SET : The empty set(immutable)


Methods of Collections Class in Java

Take a look of some methods of Collections class.

1) static <T> boolean addAll(Collections<? super T> c, T... elements)

This method adds all of the specified elements to the specified collection.

2) static <T> Queue<T> asLifoQueue(Deque<T> deque)

This method returns a view of a Deque as a Last-in-first-out(Lifo) queue.

3) static <T> int binarySearch(List<? extends Comparable<?  super T>> list, T key)

This method searches the specified list for the specified object using the binary search algorithm.

4) static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

This method searches the specified list for the specified object using the binary search algorithm.

5) static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type)

This method returns a dynamically typesafe view of the specified collection.

6) static <E> List<E> checkedList(List<E> list, Class<E> type)

This method returns a dynamically typesafe view of the specified list.



7) static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType)

This method returns a dynamically typesafe view of the specified map.

8) static <K, V> NavigableMap<K, V> checkedNavigableMap(NavigableMap<K, V> m, Class<K> keyType, Class<V> valueType)

This method returns a dynamically typesafe view of the specified navigable map.

9) static <E> Set<E> checkedSet(Set<E> s, Class<E> type)

This method returns a dynamically typesafe view of the specified set.

10) static <T> void copy(List<? super T> dest, List<? extends T> src)

This method copies all of the elements from one list into another.

11) static <T> Enumeration<T> emptyEnumeration()

This method returns an enumeration that has no elements.

12) static <T> Iterator<T> emptyIterator()

This method returns an iterator that has no elements.


Java Collections Class Example

This is simple example of collections class.

import java.util.*;
public class CollectionsExample
{
public static void main(String args[])
{
List<String> list = new ArrayList<String>();
list.add("hindi");
list.add("english");
list.add("math");
System.out.println("before adding collection values "+list);

//using collections's method
Collections.addAll(list, "science", "drawing");
System.out.println("after adding elements collection values"+list);
}


output : before adding collection values [hindi, english, math]
        after adding elements collection values [hindi, english, math, science, drawing]


Java Collections Class Example 1

In this example, we will use max() and min() methods of collections class.

import java.util.*;
public class CollectionsExample2
{
public static void main(String args[])
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(96);
al.add(150);
al.add(1);
al.add(2);
al.add(33);
al.add(50);
System.out.println("maximum value"+Collections.max(al));
System.out.println("minimum value"+Collections.min(al));
}
}

output : maximum value 150
              minimum value 1

Share:

Sunday 25 June 2017

StringTokenizer In Java

 Java StringTokenizer

StringTokenizer

The StringTokenizer class allows an application to break a string into tokens(parts). The StringTokenizer class are available into java.util package.

In other words, StringTokenizer class breaks a string on the basis of delimiters(spaces or any special symbols).

for example : suppose there is a word or String "Java is a simple programming language". We can break this string into tokens(part) with the help of delimiters like spaces or any special symbols.

java
is
a
simple
programming
language

The StringTokenizer is a legacy class in java.


Constructors of StringTokenizer Class

There are some constructors of StringTokenizer class, these are

1) StringTokenizer(String str)

This constructor creates a string tokenizer for the specified string.

2) StringTokenizer(String str, String delim)

This constructor creates a string tokenizer for the specified string and delimiter.

3) StringTokenizer(String str, String delim, boolean retrunDelims)

This constructor creates a string tokenizer for the specified string delimiter and return value. If return value is true, delimiter characters are considered to be tokens. If return values is false, delimiter characters serve to separate tokens.


Methods of StringTokenizer Class

There are some certain methods of StringTokenizer class in java which is given below.

1) boolean hasMoreTokens()

This method tests if there are more tokens available from this tokenizer's string.

2) boolean hasMoreElements()

This method returns the same value as the hasMoreTokens method.

3) String nextToken()

This method returns the next token from this string tokenizer.

4) Object nextElement()

This method returns the same value as the nextToken() method, excepts that is declared return value is Object rather than String.

5) String nextToken(String delim)

This method returns the next token in this string tokenizer's string.

6) int countTokens()

This method returns the total numbers of tokens.


Java StringTokenizer Example

This is a simple example of string tokenizer class where we will break or tokenize this string " java is a simple programming language" on the basis of white spaces. Space is the default delimiter.

import java.util.StringTokenizer;
class StringTokenizerExample
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("java is a simple programming language", " ");//using space delimiter
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

output : java
              is
              a
              simple
              programming
              language



Java StringTokenizer Example 1

This is another example of StringTokenizer, in this example we will break the string on the basis of 2 delimiters " space" and " comma". Space is the default delimiter.

import java.util.StringTokenizer;
public class StringTokenizerExample1
{
public static void main(String args[])
{
String s = "i am john, thank you";
StringTokenizer st = new StringTokenizer(s);//by using space
StringTokenizer st1 = new StringTokenizer(s, ",");//by using comma

System.out.println("tokenize by using space delimiter");

while(st.hasMoreTokens())

{

System.out.println(st.nextToken());

}

System.out.println("tokenize by using comma delimiter");


while(st1.hasMoreTokens())
{
System.out.println(st1.nextToken());
}
}
}

output : tokenize by using space delimiter
              i
              am
              john,
              thank
              you
              tokenize by using comma delimiter
              i am john
               thank you

Java StringTokenizer Example 2

This is the same example as above except that there we will use different method hasMoreElements() and nextElement() and in this example there is space between john and , e.g i am john , thank you.


import java.util.StringTokenizer;
public class StringTokenizerExample2
{
public static void main(String args[])

{

String s = "i am john , thank you";

StringTokenizer st = new StringTokenizer(s);//by using space

StringTokenizer st1 = new StringTokenizer(s, ",");//by using comma



System.out.println("tokenize by using space delimiter");


while(st.hasMoreElements())

{
System.out.println(st.nextElement());
}

System.out.println("tokenize by using comma delimiter");


while(st1.hasMoreElements())

{

System.out.println(st1.nextElement());
}
}
}

output : 
tokenize by using space delimiter
am
john
,
thank
you
tokenize by using comma delimiter
i am john
 thank you


Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate