Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, 18 June 2013

Date Difference Java

This example learns how to make the difference between two dates and how to convert milliseconds into seconds, seconds into minutes, minutes into hours, hours into days.

Here we are using Calendar, an abstract base class that extends Object class and makes a difference between a Date object and a set of integer fields. Calendar class provides a getInstance()  method for returning a Calendar object whose time fields have been initialized with the current date and time.

The methods used:
setTimeInMillis(long millis): This method is used to set current time in calendar object.
getInstance(): This method is used to get a calendar using the default time zone, locale and current time.

Generating Random Number In A Range With Java

One standard pattern for accomplishing this is:
Min + (int)(Math.random() * ((Max - Min) + 1))

The java Math library function Math.random() generates a double value in the range [0,1).
Notice this range does not include the 1.In order to get a specific range of values first you need to multiply by the magnitude of the range of values you want covered.
. 
Math.random() * ( Max - Min )
This returns a value in the range [0,Max-Min).
For example if you want [5,10] you need cover 5 integer values so you use
Math.random() * 5
This would return a value in the range [0,5)
Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.
Min + (Math.random() * (Max - Min))
You now will get a value in the range [Min,Max). Following our example, that means [5,10):
5 + (Math.random() * (10 - 5))
But, this is still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:
Min + (int)(Math.random() * ((Max - Min) + 1))
And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:
5 + (int)(Math.random() * ((10 - 5) + 1))

Is Java “pass-by-reference”?

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

It goes like this:

public void foo(Dog d) {
  d.name.equals("Max"); // true
  d = new Dog("Fifi");
  d.name.equals("Fifi"); // true
}

Dog aDog = new Dog("Max");
foo(aDog);
aDog.name.equals("Max"); // true

Java is always pass-by-value

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

It goes like this:

public void foo(Dog d) {
  d.name.equals("Max"); // true
  d = new Dog("Fifi");
  d.name.equals("Fifi"); // true
}

Dog aDog = new Dog("Max");
foo(aDog);
aDog.name.equals("Max"); // true

Java Interpreter/Lexical Analyzer

This project will be to write an interpreter for a small language with the grammar I have attached. This language has only 1 data type, integer, and the only identifiers are single letter (i.e. there are only 26 possible identifiers). 

This language has the following properties: not case sensitive must have white space (blank characters, tab characters, and end of line characters) between every lexeme The interpreter will parse a program in this language and build some intermediate data structures. 

These data structures will then be interpreted to execute the program. 
The parsing algorithm should detect any syntactical or semantic error. The first such error discovered should cause an appropriate error message to be printed, and then the interpreter should abort. Run-time errors should also be detected with appropriate error messages being printed.

How TO Compare Strings in Java


== tests for reference equality.
.equals() tests for value equality.

Consequently, if you actually want to test whether two strings have the same value you should use.equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).

== is for testing whether two strings are the same object.

HashMap Vs HashTable

HashMap and HashTable both implements Map interface but their are some difference between HashMap and HashTable.
1. HashMap is not synchronized whereas HashTable is synchronized.
2. HashMap allows one null key and any number of null values but HashTable does not allow null keys or values.
3. Iterator in HashMap is fail fast but Enumeration in HashTable is not fail fast.

String storage


String storage 

As mentioned, there are two ways to construct a string: implicit construction by assigning a string literal or explicitly creating a String object via the new operator and constructor. For example,

String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object


Java has provided a special mechanism for keeping the String literals - in a so-called string common pool. If two string literals have the same contents, they will share the same storage inside the common pool. This approach is adopted to conserve storage for frequently-used strings. On the other hand, String objects created via the new operator and constructor are kept in the heap. Each String object in the heap has its own storage just like any other object. There is no sharing of storage in heap even if two String objects have the same contents.

Sunday, 16 June 2013

Banker's Algorithm algorithm

Deadlock Definition
A set of processes is deadlocked if each process in the set is waiting for an event that only another process in the set can cause (including itself).

Waiting for an event could be:

  • waiting for access to a critical section
  • waiting for a resource Note that it is usually a non-preemptable (resource). pre-emptable resources can be yanked away and given to another.

It could also be a situation in which two computer programs sharing the same resource are effectively
preventing each other from accessing the resource, resulting in both programs ceasing to function.

Conditions for Deadlock
  • Mutual exclusion: resources cannot be shared.
  • Hold and wait: processes request resources incrementally, and hold on to what they've got.
  • No pre-emption: resources cannot be forcibly taken from processes.
  • Circular wait: circular chain of waiting, in which each process is waiting for a resource held by the next process in the chain.

Strategies for dealing with Deadlock

  • ignore the problem altogether ie. ostrich algorithm it may occur very infrequently, cost of detection/prevention etc may not be worth it.
  • detection and recovery
  • avoidance by careful resource allocation
  • prevention by structurally negating one of the four necessary conditions.

The RSA Algorithm Java code

The RSA algorithm is used for both public key encryption and digital signatures. It is the
most widely used public key encryption algorithm. The basis of the security of the RSA algorithm is that it is mathematically infeasible to factor sufficiently large integers. The RSA algorithm is believed to be secure if its keys have a length of at least 1024-bits.

History
The RSA algorithm was first published in the paper A Method for Obtaining Digital Signatures and Public-Key Cryptosystems in 1977 by Ron Rivest, Adi Shamir and Len Adleman. It is named after the initials of their surnames. The paper was published in the September 1977 issue of The Scientific American. The authors offered to send their full report to anyone who sent them a self-addressed stamped envelope. The NSA did not like the idea of distributing the crytography source code internationally and requested that it be stopped. However the distribution continued when the NSA failed to provide a legal basis for their request. The algorithm was published in The Communications of the ACM the following year.

Bully election algorithm Java Program


We start with 6 processes,all directly connected to each other.Process 6 is the leader, as it has the highest number.

Process 6 fails.
Process 3 notices that Process 6 does not respond So it starts an election, notifying those processes         with ids greater than 3.


Both Process 4 and Process 5 respond, telling Process 3 that they'll take over from here.


Process 4 sends election messages to both Process 5 and Process 6.

SCJP or OCJP Dumps

Benefits of SCJP 1.6 (SCJP 6) | OCPJP 6 Certification
  • This certification is for programmers experienced using the Java programming language. Achieving this certification provides clear evidence that a programmer understands the basic syntax and structure of the Java programming language and can create Java technology applications that run on server and desktop systems using J2SE 5.0.
  • To achieve the Sun Certified Java Programmer certification, candidates must successfully complete one exam. It is not necessary to be a Certified Java Associate prior to taking this exam.
  • Demonstrate to your employer, peers & customers that you are proficient in Java Technologies and use industry-respected best practices.
  • Enhance your salary, job opportunities and credibility through this respected credential.
  • To get officially accredited as a Java professional.
You should enroll for SCJP 1.6 | OCPJP 6 Certification if:
  • You are into writing Java applications and want to be recognized for your skills
  • You want in-depth knowledge of various concepts of Java Programming Language
  • You do not have too much of an idea about Java Programming Language, preparing for this certification will get you a foothold in Java Programming Language
  • In case you are starting a new project for which you have to use Java SE 6, appearing SCJP 1.6 certification will definitely help you update your skills
SCJP 1.6 | OCPJP 6 Certification Details


  • Delivered at: Authorized Worldwide Pearsonvue Center
  • Prerequisites: None
  • Other exams/assignments required for this certification: None
  • Exam format: Multiple choice
  • Number of questions: 60
  • Pass score: 61%
  • Time limit: 150 minutes

Saturday, 15 June 2013

Features of Java

Features of Java 
  1. Simple
  2. Object-Oriented
  3. Platform Independent
  4. secured
  5. Robust
  6. Architecture Neutral
  7. Portable
  8. High Performance
  9. Distributed
  10. Multi-threaded
Simple
Java is simple in the sense that:
      syntax is based on C++ (so easier for programmers to learn it after C++).
      removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
      No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

Types of Java Applications

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows:
  1. Desktop Applications such as acrobat reader, media player, antivirus etc.
  2. Web Applications such as irctc.co.in, javatpoint.com etc.
  3. Enterprise Applications such as banking applications.
  4. Mobile
  5. Embedded System
  6. Smart Card
  7. Robotics
  8. Games etc.
There are mainly 4 type of applications that can be created using java:


1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.

Friday, 14 June 2013

Java Naming Conventions With Example


What Is a Naming Convention?
A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc..).

Why Use Naming Conventions?
Different Java programmers can have different styles and approaches to the way they program. By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it.

To illustrate the point it's worth mentioning that most software companies will have a document that outlines the naming conventions they want their programmers to follow. A new programmer who becomes familiar with those rules will be able to understand code written by a programmer who might have left the company many years before hand.

Picking a Name for Your Identifier
When choosing a name for an identifier make sure it's meaningful. For instance, if your program deals with customer accounts then choose names that make sense to dealing with customers and their accounts (e.g., customerName, accountDetails). Don't worry about the length of the name. A longer name that sums up the identifier perfectly is preferable to a shorter name that might be quick to type but ambiguous.

Sunday, 9 June 2013

Objects and Classes

Objects

In object-oriented programming we create software objects that model real world objects. Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function associated with an object.
Definition: An object is a software bundle of variables and related methods.

What is Java?

Java is an object-oriented programming language. It was released by “SUN MicroSystems” in June 1995. Java is popular for it's “Write Once,Run Everywhere” feature. This feature is enables a Java programmer written on a plateform to be executed on any plateform. It is the underlying technology that power “State-Of-The-Art” programs including utilities, games and business applications. Lots of applications, websites that run on java.

C++ vs Java

1. C++ supports procedural programming, functional programming, object-oriented programming, generic programming, and template metaprogramming. Favors a mix of paradigms. Java strongly support object-oriented programming paradigm.
2. Java does not support pointers. In C++, pointer is one of C++ most important language features. It is also one of the most dangerous if used improperly.
3. C++ has deterministic destruction; Java does not. Deterministic destruction is useful for managing resources. In C++, when objects are deleted, their destructors are executed immediately.

Saturday, 8 June 2013

Learn Java Introduction by Video

To learn Java Introduction by Video

The world's leading programming author offers comprehensive coverage of the new Java release The definitive guide to Java has been fully expanded to cover every aspect of Java SE 6, the latest version of the world's most popular Web programming language. This comprehensive resource contains everything you need to develop, compile, debug, and run Java applications and applets.

Java the Complete Reference

Java the Complete Reference, Sevent

McGraw Hill Professional, 2007 - Internet programming - 1024 pages

The world's leading programming author offers comprehensive coverage of the new Java release The definitive guide to Java has been fully expanded to cover every aspect of Java SE 6, the latest version of the world's most popular Web programming language. This comprehensive resource contains everything you need to develop, compile, debug, and run Java applications and applets.

Click Here To Download