Wednesday, July 27, 2016

How to do split the String using more than one delimiter

How to do split the String using more than one delimiter

Split the String using more than one delimiter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
       package com.javasunderesan;

public class SplitStringDelimitters {

 public static void main(String[] args) {

  String str = "name Java Sunderesan field computer engineering grade 9.98";
  try {
   String[] splits = str.split("name |field |grade ");
   for (int i = 1; i < splits.length; i++) {
    System.out.println(splits[i]);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

}

Output::
Java Sunderesan
computer engineering
9.98


Java - String split() Method

Description:

This method has two variants and splits this string around matches of the given regular expression.


Syntax:
Here is the syntax of this method:

public String[] split(String regex, int limit)
or
public String[] split(String regex)


Parameter

regex : regular expression to be applied on string.

limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching regex.Parameter


Returns

array of strings



Throws

PatternSyntaxException if pattern for regular expression is invalid



Tuesday, July 26, 2016

How to do Convert the date from one format to another date object in another form Program

how do convert the date from one format to-another date object in another form in java

convert-the-date-from-one-format-to-another-date-object-in-another-form Program

   package com.javasunderesan;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ConvertDateObject {

 public static void main(String[] args) {
  SimpleDateFormat ddmmyyyy = new SimpleDateFormat("dd/mm/yyyy");
  SimpleDateFormat datetimeFormatyyyymmdd = new SimpleDateFormat("yyyy-mm-dd");
  try {
   ConvertDateObject cdo = new ConvertDateObject();
   String fromDate = "26/05/2016";
   System.out
     .println("Converted Date Time::" + cdo.convertDateType(fromDate, ddmmyyyy, datetimeFormatyyyymmdd));

  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 private String convertDateType(String date, SimpleDateFormat orgFormat, SimpleDateFormat targetFormat) {
  String formattedDate = null;
  try {
   Date calDate = orgFormat.parse(date);
   formattedDate = targetFormat.format(calDate); // 20120821
  } catch (Exception e) {
   e.printStackTrace();
  }
  return formattedDate;
 }

}

Output:: Converted Date Time::2016-05-26

parse() and format() method used to convert One date object to another date Object

public final String format(Date date)

Formats a Date into a date/time string.
Parameters:
date - the time value to be formatted into a time string.
Returns:
the formatted time string.

Parsing a Date

Parse()

Monday, July 25, 2016

How to calculate difference between two date String in Java

How to calculate difference between two date String in Java

Parsing Date

public Date parse(String source) throws ParseException

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
See the parse(String, ParsePosition) method for more information on date parsing.
Parameters:
source - A String whose beginning should be parsed.
Returns:
A Date parsed from the string.
Throws: ParseException - if the beginning of the specified string cannot be parsed.
   package com.javasunderesan;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CompareDateTime {

 public static void main(String[] args) {
  SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");  
  
  Date start = null, end = null;
  String fromDate = null;
  String toDate = null;
  try {
   CompareDateTime compareDate = new CompareDateTime();
   fromDate = "24/05/2016";
   toDate = "25/05/2016";
   start = sdf.parse(fromDate);
   end = sdf.parse(toDate);   
   System.out.println("Days Between " + start + " and " + end + ":::" +compareDate.daysBetween(start, end));
  } catch (ParseException e) {
    e.printStackTrace();
  }

 }

 private Long daysBetween(Date d1, Date d2) {
  return (Long) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
 }
}

output: Days Between Sun Jan 24 00:05:00 IST 2016 and Mon Jan 25 00:05:00 IST 2016:::1

Tuesday, July 19, 2016

public static void main(string args) in java

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

  • class keyword is used to declare a class in java.
  • public keyword is an access modifier which represents visibility, it means it is visible to all.
  • static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.
  • void is the return type of the method, it means it doesn't return any value.
    main represents startup of the program.
  • String[] args is used for command line argument. We will learn it later.
  • System.out.println() is used print statement. We will learn about the internal working of System.out.println statement later.
    package com.javasunderesan;

public class MainMethodExample {

 public static void main(String[] args) {
  System.out.println("Welcome to http://javasunderesan.blogspot.in/");
 }

}

public static void main(string args) interview Questions

  • Why main method is static?

    To execute main method without creating object then the main method oshould be static so that JVM will call main method by using class name itself.


  • Why main method return type is void?

    main method wont return anything to JVM so its return type is void.


  • Why the name main?

    This is the name which is configured in the JVM.


  • Why the arguments String[] args?

    Command line arguments. String array variable name args : by the naming conventions they named like that we can write any valid variable name.


  • Can we write static public void main(String [] args)??

    Yes we can define main method like static public void main(String[] args){}
    Order of modifiers we can change.


  • What are the possible public static void main(String [] args)method declaration with String[] args?

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

    Instead of args can place valid java identifier.


  • Overloading main method

    • We can declare multiple main methods with same name as per overloading concept.
    • So we can overload main method but every time JVM looks for main method with String[] args method.
    • Lets see an example program on main method overloading.
    • main(String[] args) method will be called automatically by JVM.
    • If we want to call other methods we need to call explicitly.
        package com.javasunderesan;
    
    public class OverloadingMainMethod {
    
     public static void main(String[] args) {
    
      System.out.println("Java Sunderesan - Main method String [] args");
     }
     public static void main(int[] args) {
      System.out.println("Java Sunderesan - Main method int[] args");
     }
    
    }
    

JRE,JVM and JDK

Java Tutorial

Java Virtual Machine

The Java Virtual Machine (JVM) is an execution environment for Java applications.
It interprets compiled Java binary code ( called bytecode) to enable a computer's processor to carry out a Java Program's instructions.Java was designed to allow application programs to be built that could be run on any platform without having to be rewritten or recompiled by the programmer for each separate platform. The Java Virtual Machine makes this possible.
  • The JVM is a main component of Java architecture, and is a part of the JRE(Java Runtime Environment).
  • The JVM is operating system-dependent. In other words, the JVM must translate the bytecode into machine language, and the machine language depends on which operating system is being used, which makes the JVM platform-dependent.
  • The JVM is responsible for allocating memory needed by the Java program.

Basically, the Java compiler reads Java language source (.java) files, translates the source into Java bytecodes, and places the bytecodes into class (.class) files.
The class files can then be executed on the Java Virtual Machine(JVM)

The JVM performs following main tasks:
  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

Every device that has a JVM installed is able to translate and run your .class files.
This makes it possible to run the same bytecode on different platforms.


JRE

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

Java Development Kit(JDK)

The Java Development Kit(JDK) is a software development environment for java applications and applets. It includes

  • The Java Compiler(javac)
  • The Java Archiving Tool(jar)
  • The Java Debugging Tool(jdb)
  • A complete Java Runtime Environment(JRE), for running Java programs.

After installing the JDK, you will be able to run javac,jar and jdb from the console(Command Prompt in Windows).

JDK is available for free at www.oracle.com under Java SDKs and Tools-> Java SE.

What is Keywords in Java?

Java Keywords

Java Keywords

* Keywords are predefined identifiers available directly throughout the JVM.

* They have a special meaning inside java source code and outside of comments and strings.

* For Example : public, static, void

Q1) What are different types of access modifiers in Java?

Ans) There are four different types of modifiers:

Modifier Accessible in the same package Accessible in different package
Private No Yes, only if the class extends the main class
Protected Yes Yes, only if the class extends the main class
Default Yes No
Public Yes Yes

Q2) What is the use of final keyword?

Ans) The final keyword can be assigned to

  1. Class level variable
  2. method
  3. class
  4. Objects

If a final is assigned to a variable, the variable behaves as a constant. It means that the value of variable once set cannot be changed.

final int i=1;
i =5; // error

If a final is assigned to a method then it cannot be overridden in its child class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
      package com.javasunderesan;

class Parent {
 final void print() {
  System.out.println("Inside");
 }
}

class Child extends Parent {
 public final void print() {// error cannot override final method
  System.out.println("Inside");
 }
}

If a class is made as final, then no other class can extend it and make it as parent class. E.g. String Class.

Final objects are instantiated only once. i.e
final Map map = new HashMap();
map.put("key","value");
map = new HashMap();  // error

Q3) What is use of throws keyword?

Ans) The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
      package com.javasunderesan;

import java.io.IOException;

public class ThrowsKeyword {
 void callTestThrow_1() throws IOException {
  throw new IOException("device error");// checked exception
 }

 void callTestThrow() throws IOException {
  callTestThrow_1();
 }

 void test() {
  try {
   callTestThrow();
  } catch (Exception e) {
   System.out.println("exception handled");
  }
 }

 public static void main(String args[]) {
  ThrowsKeyword obj = new ThrowsKeyword();
  obj.test();
  System.out.println("normal flow...");
 }
}
Output
exception handled
normal flow...

Q4) Why static methods cannot access non static variables or methods?

Ans) A static method cannot access non static variables or methods because static methods doesn't need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be initialized since the object is not created and this could result in an error.


Q5) What is a static method?

Ans)A method defined as static is called static method. A static method can be accessed without creating the objects. Just by using the Class name the method can be accessed. Static method can only access static variables and not local or global non-static variables. For eg:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
      package com.javasunderesan;

public class StaticMethodExample {
 public static void main(String args[]) {
  MainClass.printMe();
 }
}

class MainClass {

 public static void printMe() {
  System.out.println("Welcome to JavaSunderesan.blogspot.in");
 }
}
OutPut:
Hello World
Also static method can call only static methods and not non static methods. But non-static methods can call static mehtods.

Friday, July 15, 2016

Is Possible to print message without using system.out.println?

Is Possible to print message without using system.out.println?

Is possible to print message without using system.out.println?

Yes. It is possible to print message without using system.out.println.

package com.javasunderesan;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintMessage {
  public static void main(String[] args) {
    // https://javasunderesan.blogspot.in/
    // Display message without System.out.println
    try {
      String message = "javasunderesan - Learn Java\n";
      System.out.write(message.getBytes());
      System.out.format("%s", message);
      PrintStream myout = new PrintStream(new FileOutputStream(FileDescriptor.out));
      myout.print(message);
      System.err.print(message);
      System.console().writer().println(message);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Wednesday, July 13, 2016

Coding Standards and Naming conventions

Coding Standards and Naming Conversion

Why Coding Standards?

  • A program is written once , but read many times

    • During debugging
    • When adding to the program
    • When updating the program
    • When trying to understand the program
  • Anything that makes a program readable and understandable saves lots of time , even in the shot run.

Naming Conventions

  • Naming a class

    • Class name should be in title case , means Every word first letter should be capital letter.
    • This is also known as UpperCamelCase.
    • Choose descriptive and simple names.
    • Try to avoid acronyms and abbreviations.
    • Naming Class Example

      package com.javasunderesan
      public JavaNamingVariableDemo{
      }
  • Naming a Variable

    • Variable name should be start with small letter.
    • Use lowerCamelCase.
    • Example: name, mobileNumber, age.
    • For final variable all its letters should be capital and words must be connected with "_".
    • Example: MAX_COUNT, MIN_COUNT.
    • Naming Variable Example

      package com.javasunderesan
      public JavaNamingVariableDemo{
      String firstName;
      String lastName;
      int mobileNumber;
      final static int MIN_WORDS=300;
      }
  • Naming a Method

    • Method name should be verb because it represents action.
    • Use lowerCamelCase for naming methods
    • Example: setFirstName(), getFirstName(), getLastName().
    • Naming Variable Example

      package com.javasunderesan
      public JavaNamingMethodDemo{
      String firstName;
      String lastName;
      int mobileNumber;
      final static int MIN_WORDS=300;
      public void getFirstName()
      {
      return firstName;
      }
      public void setFirstName(String firstName)
      {
      this.firstName = firstName;
      }
      }
  • Naming a Package

    • All letters should be small.
    • like in java io, util, applet
    • Example: com.javasunderesan
    • Naming Variable Example

      package com.javasunderesan
      public JavaNamingMethodDemo{
      }

Monday, July 11, 2016

Features of Java

Features of Java

  • Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

  • Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

  • Simple:Java is designed to be easy to learn. If you understand the basic concept of OOP,Java would be easy to master.

  • Secure: With Java's secure feature, it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

  • Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler inJava is written in ANSI C with a clean portability boundary which is a POSIX subset.

  • Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.

  • Multithreaded: With Java's multithreaded feature, it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.

  • Interpreted:Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and lightweight process.

  • High Performance: With the use of Just-In-Time compilers, Java enables high performance. Distributed:Java is designed for the distributed environment of the internet.

  • Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Saturday, July 9, 2016

Java Overview

Java Overview

Java

What is Java?

Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end Unix workstations. Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level (more about this later).

History of Java

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak” but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype. Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent (that is, architectureneutral)