Skip to main content

Posts

Showing posts with the label Core JAVA

Primitive Obsession with Example

Primitive Obsession is the name of a code smell that occurs when we use primitive data types to represent domain ideas. For example, we use a string to represent a message or an integer to represent an amount of money. For Example: Code with Primitive Obsession // primitiveObsession.java public class primitiveObsession { public static void main ( String args []) { Integer [] cityPopulations = { 13000000 , // London 21903623 , // New York 12570000 , // Tokyo 1932763 , // Stockholm 1605602 , // Barcelona 4119190 // Sydney }; for ( Integer cityPopulation : cityPopulations ) { System . out . println ( cityPopulation ); } } } public class City { private final String name ; private final int population ; private final Continent continent ; public String getName () { return name ; } public int getPopulation () { return population ; } public Continent ge...

Basics of Encapsulation Inheritance & Polymorphism

Encapsulation: Hiding the data/methods inside the object is called the Encapsulation. In Structured programming when u want to have a variable having accessible by some part and not by other part u don't have a mechanism to achieve the same. Encapsulation provides the same mechanism, if a class or a function wants to access then it should access those variables and functions from the references of the class i.e. objects. Inheritance Inheritance enables you to create a class that is similar to a previously defined class, but one that still has some of its own properties. Polymorphism The last major feature of object-oriented programming is polymorphism. By using polymorphism, you can create new objects that perform the same functions as the base object but which perform one or more of these functions in a different way. For example, you may have a shape object that draws a circle on the screen. By using polymorphism, you can create a shape object that draws a rectangle instead...

Dependency Injection (DI)

The first reference to what would eventually become Dependency Injection appeared in 1994 in a paper by Robert C. Martin called "The Dependency Inversion Principle". In "The Dependency Inversion Principle" (or DIP ), the author states the three defining factors of "bad code": It is hard to change because every change affects too many other parts of the system (Rigidity) When you make a change, unexpected parts of the system break (Fragility) It is hard to reuse in another application because it cannot be disentangled from the current application (Immobility) According to Martin, interdependency causes these coding problems (we'll call them RFI for Rigidity, Fragility, and Immobility). To fix RFI issues in your OO code, DIP has two basic rules:   1. High level modules should not depend upon low level modules, both should depend upon abstractions. In other words, high level modules – which contain your business logic and all of the important meat of your...

Variable arguments

You can use a construct called  varargs  to pass an arbitrary number of values to a method. You will most commonly see varargs with the printing methods; for example, this printf method: public PrintStream printf(String format, Object... args)   allows you to print an arbitrary number of objects. It can be called like this: System.out.printf("%s: %d, %s%n", name, idnum, address);   or like this System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, mail); or with yet a different number of arguments.  

Overloading of Methods

The Java programming language supports  overloading  methods, and Java can distinguish between methods with different  method signatures . This means that methods within a class can have the same name if they have different parameter lists You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.   Note:   Overloaded methods should be used sparingly, as they can make code much less readable.  

Copying arrays using System class method

The  System  class has an  arraycopy  method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) The two  Object  arguments specify the array to copy  from  and the array to copy  to . The three  int  arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy. The following program,  ArrayCopyDemo , declares an array of  char  elements, spelling the word "decaffeinated". It uses  arraycopy  to copy a subsequence of array components into a second array:   class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',              'i',...

Java Variables

Types of Variables Instance Variable: Non-static fields are also known as  instance variables  because their values are unique to each  instance  of a class. Class Variables: A  class variable  is any field declared with the  static  modifier; this tells the compiler that there is exactly one copy of this variable in existence; regardless of how many times the class has been instantiated. Local Variables: Variables  between the opening and closing braces of a method. Parameters: The Arguments of a method or a constructor. Naming Conventions By convention it should start with the letter. Avoid $ and _ characters in the names. Whitespaces are not allowed. Keyword or any reserved word should not be used. For constants separate the words with the _.

Object initialization

As with class initialization, the simplest kind of object initialization is automatic initialization of object fields to default values. Example: class ObjectInitializationDemo1 { boolean b; byte by; char c; double d; float f; int i; long l; short s; String st; public static void main (String [] args) { ObjectInitializationDemo1 oid1 = new ObjectInitializationDemo1 (); System.out.println ("oid1.b = " + oid1.b); System.out.println ("oid1.by = " + oid1.by); System.out.println ("oid1.c = " + oid1.c); System.out.println ("oid1.d = " + oid1.d); System.out.println ("oid1.f = " + oid1.f); System.out.println ("oid1.i = " + oid1.i); System.out.println ("oid1.l = " + oid1.l); System.out.println ("oid1.s = " + oid1.s); System.out.println ("oid1.st = " + oid1.st); } } Output b = false by = 0 c = d = 0...

Class initialization

Although we tend to think of initialization in terms of assigning values to variables, initialization is so much more.  For example, initialization might involve opening a file and reading its contents into a memory buffer, registering a database driver, preparing a memory buffer to hold an image's contents, acquiring the resources necessary for playing a video, and so on. Java supports initialization via language features collectively known as  initializers. Class initialization is different from Object initialization and it happens before Object initialization.   Class Initialization A program contains no of classes, before the execution of java program the class loader loads the public class having the PSVM. Then the byte code verifier verifies the class. Then class initializes. The class fields are set to default values. For Example:   static boolean b;//flase static byte by;//0 static char c;// static double d;//0.0 static float f;...

Class Loading while running JVM

The Order is Bootstrap classes  - Classes that comprise the Java platform, including the classes in  rt.jar  and several other important jar files. Extension classes  - Classes that use the Java Extension mechanism. These are bundled as  .jar  files located in the extensions directory. User classes  - Classes defined by developers and third parties that do not take advantage of the extension mechanism. You identify the location of these classes using the  -classpath  option on the command line (the preferred method) or by using the CLASSPATH environment variable. 

Wild Cards while specifying the class path

A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo , use either foo; foo/* or foo/*;foo . The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo , or vice versa. Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo , not in foo/bar , foo/baz , etc. If u want to load jars files or class file in a specific order that u have to specify the list itself in the class path but not using the wild cards. Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar , b.jar , and c.jar ,...

JDK and JRE File Structure

Assuming the JDK software is installed at c:\jdk1.7.0, here are some of the most important directories: c:\jdk1.7.0 Root directory of the JDK software installation. Contains copyright, license, and README files. Also contains src.zip, the archive of source code for the Java platform. c:\jdk1.7.0\bin Executable files for the development tools contained in the Java Development Kit. The PATH environment variable should contain an entry for this directory. For more information on the tools, see the JDK Tools . c:\jdk1.7.0\lib Files used by the development tools. These include tools.jar, which contains non-core classes for support of the tools and utilities in the JDK. Also includes dt.jar, the DesignTime archive of BeanInfo files that tell interactive development environments (IDE's) how to display the Java components and how to let the developer customize them for an application. c:\jdk1.7.0\jre Root directory of the Java runtime environment used by the JD...

Additional Files and Directories

This section describes additional files and directories. c:\jdk1.7.0\src.zip Archive containing source code for the Java platform. c:\jdk1.7.0\db Contains Java DB. c:\jdk1.7.0\demo Examples, with source code, that show you how to program for the Java platform. c:\jdk1.7.0\demo\applets Applets that can be used on a web page. c:\jdk1.7.0\demo\jfc Examples that use Java 2D™ and JFC\Swing functionality. c:\jdk1.7.0\demo\jpda Examples of using the Java Platform Debugging Architecture. Includes source code for the javadt and jdb utilities. c:\jdk1.7.0\demo\plugin Contains demos for use with the Java Plug-in product. c:\jdk1.7.0\include C-language header files that support native-code programming using the Java Native Interface and the Java Virtual Machine Debugger Interface.

JAVA TOOLS

Basic Tools These tools are the foundation of the JDK. They are the tools you use to create and build applications. Tool Name Brief Description Links to Reference Pages appletviewer Run and debug applets without a web browser. [ Solaris and Linux ] [ Windows ] apt Annotation processing tool. See Annotation Processing Tool for program annotation processing. [ Solaris, Linux, and Windows ] extcheck Utility to detect Jar conflicts. [ Solaris and Linux ] [ Windows ] jar Create and manage Java Archive (JAR) files. See Java Archive Files page for the JAR specification. [ Solaris and Linux ] [ Windows ] java The launcher for Java applications. In this release, a single launcher is used both for development and deployment. The old deployment launcher, jre , is no longer provided. [ Solaris and Linux ] [ Windows ] javac The compiler for the Java programming language. [ Solaris and Linux ] [ Windows ] javadoc API documentation generator. See Javadoc Tool page for doclet and taglet APIs. [ So...