Saturday, December 17, 2016
Thursday, November 3, 2016
How Java Differs from C and C++
Pointers
Arrays
You must now add actual MyObject objects to that array:
for (int i; i< arrayofobjs.length. i++) {
arrayofobjs[i] = new MyObject();
}
Java does not support multidimensional arrays as in C and C++. In Java, you must create arrays
that contain other arrays.
Strings
Memory Management
Data Types
Control Flow
Arguments
Other Differences
- Java does not have a preprocessor, and as such, does not have #defines or macros.
- Constants can be created by using the final modifier when declaring class and instance variables.
- Java does not have template classes as in C++.
- Java does not include C’s const keyword or the ability to pass by const reference explicitly.
- Java classes are singly inherited, with some multiple-inheritance features provided through interfaces.
- All functions are implemented as methods. There are no functions that are not tied to classes.
- The goto keyword does not exist in Java (it’s a reserved word, but currently unimplemented). You can, however, use labeled breaks and continues to break out of and continue executing complex switch or loop constructs.
Friday, August 19, 2016
Java Object Oriented Programming Concept
Object Oriented Programming is a paradigm that provides many concepts
such as inheritance, data binding, polymorphism etc.
Simula
is considered as the first object-oriented programming language. The
programming paradigm where everything is represented as an object, is
known as truly object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming
language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc.
Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
- Object
- Class
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer differently, to draw something e.g. shape or rectangle etc. In java, we use method overloading and method overriding to achieve polymorphism. Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Static Polymorphism (compile time polymorphism/ Method overloading):
The ability to execute different method implementations by altering the argument used with the method name is known as method overloading. For Example We have three print methods each with different arguments. When you properly overload a method, you can call it providing different argument lists, and the appropriate version of the method executes.
Dynamic Polymorphism (run time polymorphism/ Method Overriding)
When you create a subclass by extending an existing class, the new subclass contains data and methods that were defined in the original superclass. In other words, any child class object has all the attributes of its parent. Sometimes, however, the superclass data fields and methods are not entirely appropriate for the subclass objects; in these cases, you want to override the parent class members.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. Encapsulation means putting together all the variables (instance variables) and the methods into a single unit called Class. It also means hiding data and methods within an Object. Encapsulation provides the security that keeps data and methods safe from inadvertent changes. Programmers sometimes refer to encapsulation as using a “black box,” or a device that you can use without regard to the internal mechanisms. A programmer can access and use the methods and data contained in the black box but cannot change them.
Advantage of OOPs over Procedure-oriented programming language
- OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows.
- OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can be accessed from anywhere.
- OOPs provides ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.
Wednesday, August 17, 2016
Java Comments
Comments
The purpose of including comments in your code is to explain what the code is doing. Java supports both single and multi-line comments. All characters that appear within a comment are ignored by the java compiler.
Single-line comment
A single-line comment starts with two forward
slashes and continues until it reaches the end of the line.
For example:
// this is a single-line comment X= 5; //Assign 5 to Variable X
Adding comments as you write code is a good practice,because they provide clarification and understanding when you need to refer back to it, as well as for others who might need to read it.
Multi-line comments
Java also supports comments that span multiple lines.
You
start this type of comment with a forward slash followed by an
asterisk, and end it with an asterisk followed by a forward slash.
For
example:
/* * This is also a Comment * Spanning multiple lines */
Note that Java does not support nested mutli-line comments.
However, you can nest Single-line comments within multi-line
comments.
/* * JavaSunderesan - MultiLine Comments // a Single Line Comment */
Documentation Comments
Documentation comments are special comments that
have the appearance of multi-line comments, with the difference being
that they generate external documentation of your source code. These
begin with a forward slash followed by two asterisks, and end with an
asterisk followed by an forward slash.
For Example:
/** Welcome To Java Sunderesan * Copyright (C)2016 King . All Rights Reserved */
Javadoc is a tool which comes with JDK and it is
used for generating Java Code documentation in HTML format from Java
source code which has required documentation in a predefined format.
When
a documentation comment begins with more than two asterisks, Javadoc
assumes that you want to create a "box" around the comment in the
source code. It simply ignores the extra asterisks.
For
Example:
/********** * Welcome To Java Sunderesan Copyright (C)2016 King . All Rights Reserved */
Monday, August 8, 2016
Write a program for a String must contain three digit using String.format()
Write a program for a String must contain three digit using String.format()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.javasunderesan; public class StringThreeDigit { public static void main(String[] args) { try { int no = 0; String formattingString = null; for (int i = 0; i < 10; i++) { formattingString = String.format("Dev - %03d", no); System.out.println(formattingString); no++; } } catch(Exception e) { e.printStackTrace(); } } } |
OutputDev - 000 Dev - 001 Dev - 002 Dev - 003 Dev - 004 Dev - 005 Dev - 006 Dev - 007 Dev - 008 Dev - 009
Write a Program to Add spaces before and After a String using String.format()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javasunderesan; public class AddSpaceBeforeAndAfterString { public static void main(String[] args) { try { String msg = "java"; System.out.println(String.format("%8s", msg)); // adding spaces // before // string ; System.out.println(String.format("%-8s", msg));// adding spaces // after // string // 8 is a number of characters String and spaces } catch (Exception e) { e.printStackTrace(); } } } |
Output::
java java
Java - String Format
String Format
Description:
String.format() method helps us to format the given string.
It replaces each format item in a specified string with the text
equivalent of a corresponding object's value.
Syntax:
Here is the syntax of this method:
public static String format(String format, Object... args)
Parameters:
args : arguments for the format string. It may be zero or more.
Return Value
String.format() Example Program
Write a Program to Add spaces before and After a String using String.format()
Write a program for a String must contain three digit using String.format()
Wednesday, July 27, 2016
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
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
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)
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
Parsing Date
public Date parse(String source) throws ParseException
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 Virtual Machine
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)
- 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
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
* 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
- Class level variable
- method
- class
- 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:Also static method can call only static methods and not non static methods. But non-static methods can call static mehtods.
Hello World
Friday, July 15, 2016
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
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{
}