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

Wednesday, May 15, 2019

Can we Override Static Method in Java?

In this post you will learn one of the famous interview question for fresher and Experienced Java Developers that is Can we override Static methods in Java. No static methods cannot be overridden, if subclass tries to it will be called Method hiding and not overriding because there won't be any runtime polymorphism and decision as to which method to invoked is decided at compile time.(if any call is decided at compile time then there is no concept of overriding.)

Lets understand with example:

public class MainClass {

 public static void main(String[] args){

 Parent.print();

 Child.print();

 }

}

class Parent {

 public static void print() {

 System.out.println("I am Parent");

 }

}

class Child extends Parent {

}


Output:
I am Parent
I am Parent


Explanation:
Static methods including instance methods(public, protected and default) are inherited to subclass.

Only difference is, if subclass defines method with same name and signature that is present in super class then there is difference in the way static method and instance method will work.

STATIC METHODS:

If subclass defines method with same name & signature as one present in Superclass then for STATIC METHODS it is said to be method hiding and not method overriding.
It is said to be method hiding because there will be no polymorphic behavior achieved.

Lets understand with example

public class MainClass {

 public static void main(String[] args){

 Parent parent = new Child();

 parent.print();

 Child child = new Child();

 child.print();

 }

}

class Parent {

 public static void print() {

 System.out.println("I am Parent");

 }

}

class Child extends Parent {

 public static void print() {

 System.out.println("I am Child");

 }  

}


Output of above program is 
I am Parent, 
I am Child,

because no polymorphism is achieved and instance type that is,
for line parent.print(); instance type is Parent and print() method of Parent  class will be invoked.
for line child.print(); instance type is Child and print() method of Child class will be invoked.

Note: If it exhibits polymorphism then output will be "I am Child" for line parent.print().

METHOD HIDING

Child class also provides implementation of print method. so child.print(); method invokes print() method of Child class and not Parent class because Child class has hide the super class print() method by providing implementation of it and that is why it is called Method hiding.


INSTANCE METHODS:

If subclass defines method with same name & signature as one present in Superclass then for INSTANCE METHODS it is said to be method overriding and not method hiding.
It is said to be method overriding because there will be polymorphic effect.


If we run the same above program by removing static to print() method and making it instance method then output will be . 
I am Child.
I am Child.

output of line parent.print(); is "I am Child" because it checks whether Parent class has print() method and yes it has then it checks whether Subclass has provided his own implementation of print method, Yes, so print() method of Child class is invoked.

Friday, March 1, 2019

Where is java used?

In this post i am sharing where we used java and list of companies used java programming  across world. Java is the king of all the programming languages. We can see the application of Java everywhere, like in our mobile phones, desktops, websites. Java is majorly used for Application Development.

Let’s see some other Java applications:

Desktop application
Web application
Android application
Big Data
Cloud Computing
Robotics
Enterprise application
Scientific Application
Research and development
Retailing and e-commerce
Operating system
Cryptography
Banking
Computer games
Videogames
Web & Application servers
Smart Codes
Embedded system
Real-time software

List of Companies using Java Programming Languages

Today, Java is used almost in every company. According to research more than 64,000 companies using Java in the USA.

Big companies in the world

Airbnb
Uber
eBay
Pinterest
Groupon
Spotify
Pandora
Square



Big companies in India

Infosys
TCS
Wipro
HCL
Tech
Jaboong
Myntra
Flipkart
Trivago
Ibibo
Tripadvisor

Biggest Internet companies

Google
Accenture

Hardware companies

Intel
Symantec
Philips
Thomson
T-Mobile
Huge Product Companies
Thumbtack
Evernote
Klout
BetterCloud
Yelp
Okta
Stack
Any company, which has 1 million to 10 million revenue is using Java for the time being.

Wednesday, July 18, 2018

How can I be Strong in JAVA?

In this post you will know what things you must follow to become strong in Java Programming Language. Java is one of the highly demand programming language in the world.

Here are the 5 things you can do to become a sought-after Java Programmer:

Keep coding: To begin with, learn the basics. Go through a tutorial, do the exercises, and as you go through the lessons, try writing a code. While writing, make sure you understand each line. Write code on paper which has a good chance of compiling. Write/copy-paste same piece of code/configuration again and again. Keeping configuration snippets like log4.properties, jdbc configuration etc. and utilities like StringUtils, ReflectionUtils, DBUtils – these are always helpful.

Build a strong foundation in OOPS: For a Java Developer having strong understanding of Object Oriented Programming (OOP) is a must. Without having a strong foundation on OOPS, one can’t realize the beauty of an Object Oriented Programming language like Java.

Practice, practice, practice and follow technology trends: Look out for new framework and stay updated. Write a simple client server TCP service such as chat or read up on Design Patterns and try to use them. You can learn when they help and don’t help. Study the source code of various successful, popular frameworks where you can see the internal working mechanism of the framework and lot of best practices.



Keep solving problems: All software is designed to solve some user problem and a wide array of smaller problems that make it up. As a good Java developer you should understand the class loading process and how it works, have an understanding of garbage collection, when is it triggered and even know how to minimize it. Know when to use design patterns such as Singleton, Factory, Fly-weight, Builder, Object Pool, Iterator, Strategy, Visitor and Composite.

Master the core APIs: You may be strong in theoretical knowledge, but one should have very strong hands on experience on core APIs like java.lang.*, I/O, Exceptions, etc. And when it comes to Web application development, no matter which framework you are using, having strong knowledge on Servlets, JSPs is a must.

Friday, July 6, 2018

What are The Basic Things Java Programmer Should Know?

In this post you will know what are the some basic things every Java Programmer should know. Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere.

In any technology say Java or some other language, it is more important and valuable to know the language fundamentals thoroughly (OOP concepts, interfaces, class, objects, threading etc.) rather than specific frameworks or syntax. It's always easy to quickly learn new technologies when you master the fundamentals.

The first thing which I guess every programmer should know that Java is not going to be replaced by any technology ever. Java is still the biggest asset while developing a enterprise level application. 




Here are some of the java specific thing which you should know.

  • Always follow official java docs and java API docs. It will help you throughout your career, I'll advise you bookmark it on your browser.
  • Learn by doing. You just cannot remember each and everything conceptually without implementing it.
  • Being comfortable in Java you can easily get your hands dirty by building some cool apps for desktop, mobile and web.
  • Don't feel ashamed to use APIs and Libraries. It will save a lot of your time
  • Join IRCs and be active on online java forums, read blogs, follow articles on medium to stay updated.
  • How Java Virtual Machine works? e.g. (Platform Independence, Garbage Collection, class files etc)
  • What are the Object Oriented Programming Concepts Implemented in Java?
  • Multi-threading
  • Java Collection framework
  • Good understanding of data types and few java.lang classes like String, Math, System etc. java.io stream concepts.
  • Learn design pattern and implement them.
  • Follow java projects on github. Go through commits and check how other developers are doing.
  • Don't feel shy to ask someone to review your code. It's a good practice and even you should take out sometime to do code review of your peers.
  • Always write unit test cases for your code and try to provide 100% coverage.
  • Java is not going to die. Stop switching technology just because they are trending. Get comfortable in Java and you'll be able to do anything with it.
  • Improvements on language from major version changes (Generics, Annotations, Enums, ...).
  • Coding Conventions.
  • Build tool (Ant) or Project Management Tool (Maven).
  • Version control System like GIT/SVN/Perforce/Clearcase.
  • Unit testing - e.g. Junit and TestNG

Wednesday, June 20, 2018

Differences Between Java and JavaScript

In this post you will learn the main differences between Java and JavaScript.Programmers, developers and internet users have always been confused between Java and JavaScript. Many people still thinks that JavaScript is part of Java platform, which is not true. In truth, JavaScript has nothing to do with Java, only common thing between them is word "Java",

JavaScript is a client side scripting language for HTML, developed by Netscape, Inc, while Java is a programming language, developed by Sun Micro System.

Java is an OOP programming language,It is  used for creating desktop applications or others. To compile java based programs you need JDK+JRE set up in your computer. Since java is pure object oriented programming language everything you do is under a class.

JavaScript is a client side scripting programming language. You don't need anything except a browser for running a script. In JavaScript everything is objects/functions. There is no concept of classes.



One more difference which comes form this fact is that, Java is run inside JVM and needs JDK or JRE for running, on there other hand JavaScript runs inside browser and almost every modern browser supports JavaScript.

Java uses static type checking, where the type of a variable is checked at compile-time. The programmer must specify the type (integer, double, string, etc.) of any variable they create. JavaScript, like most scripting languages, uses dynamic typing, where type safety is verified at runtime.

JavaScript is much more forgiving than Java, you don't have NullPointerException in JavaScript, your variable can accept different kinds of data because of JavaScript is dynamically typed language.

Objects of Java are class based.

Objects of JavaScript are prototype based.

Java has block based scope.

JavaScript has function based scope and object based context.






Saturday, June 16, 2018

How do I master Coding?

In this post you will know how to become a master in coding. When you learn something new, try to question- How it works, what is fundamental logic behind it. You should have a good understanding of fundamental concepts. You should be good at logics. Even if you are not good at logic today, you can be tomorrow.

Also important is that you don’t focus on a single programming language! If you want to be good at programming then you need to understand several different languages, syntax's and especially programming techniques.

The following Tips might be helpful:

  1. Choose any programming language. Study its basic syntax and control structures.
  2. Be good in logic. This is your thinking ability and nobody can teach you this. It has to be within you
  3. you would need to learn about algorithms and data manipulation. For example, if someone mentions a linked list or a BTree, then you should know what they mean by that. You should also know what a Quick Sort is and why you would use it instead of e.g. a Bubble Sort. You don’t need to know how to implement it exactly, but you should understand the logic behind it!
  4. The Best websites to start practice easiest problems such as Codechef, hackerrank, topcoder
  5. Gradually increase the difficulty level of the problems.




In case of Web development and android development, it's more of framework. So I advice you to take up open source github projects and start working on it. You don't need to know all the syntax's in this case. You can also take up some online course of web dev/android dev on Coursera and other sites. This is comparatively easier task.

I advice you first learn C/C++ and Java and HTML,CSS, Javascript and SQL for web development.First you must become master in these programming languages then you can switch to other frameworks.

Saturday, November 25, 2017

what are the most trending jobs in the IT Industry in 2017

In this post we will know what are the best jobs in the IT industry right now. Currently most product based industries are in search for candidates who are able to write the correct logic for a program which is what the recruiters are looking for today.

The web development and Data Science are currently trending job roles which are hot in the market right now. To get best job roles one must start acquiring these skills to do so.

  • Web Development
  • Data Science
  • Artificial Intelligence and Machine Learning Developer
  • Blockchain Dev
  • Cloud Software Engineering
Web Development:

To get into web development one must know the skills of technologies such as Angular.js,Javascript,JSON,Node.js,MongoDB and Cloud etc.. The basic job roles that one gets offered after acquiring these skills are Front-end developer,Back-end developer, Full stack developer. An average pay a developer gets offered ranges from around 5 to 6 lpa in a product based company.

Data Science:

In spite of increased availability of highly refi ned data collection tools and analytics dashboards, there is still high demand for data scientists since they possess advanced skillsets in statistics and analytics, which is needed to clean and organise data before extracting valuable insights. 

The skills required mathmatics,statistics,R, Python Programming,Machine Learning,Data Modeling and Algorithms etc.. An average salary a Data Scientist gets offered ranges from 6 to 7 lpa as a fresher in product based company.

Who is hiring:

Social Networks, e commerce,Mobile Marketing, Search engines and engineering companies

Artificial Intelligence:


Being an artificial intelligence and machine-learning developer compels understanding of the entire ecosystem that you’re designing for. This necessitates working with AI and machine components that run autonomously with minimal human supervision. An average salary a AI developer gets offered ranges from 10 to 12 lpa  in product based company.

Who is hiring:

Technology Companies, health care and customer services

Blockchain Dev:

Blockchain developers enable transparent, tamper-proof systems that facilitate transactions between machines without going through a neutral central authority. With a steady rise of interest in the technology, there is an increased demand for adoption at multiple stages of blockchain, which impacts the skill requirement.An average salary a Blockchain developer gets offered ranges from 4 to 5 lpa  in product based company.

Who is hiring:

Media, telecommunications, health care,technology companies and financial industry

 Cloud Computing Engineering:

The demand is expected to rise exponentially because more and more companies are implementing cloud technology and this is a crucial role in the loud computing ecosystem.An average salary a Cloud Computing developer gets offered ranges from 6 to 7 lpa  in product based company.

Who is hiring:

Tech Manufacturing, pharma,media,retail,software and telecom

In order to acquire these skills go to best websites such as Udemy, simplelearn and Edureka. They offer you different courses and certifications on the technologies so that you can acquire skills in the web development and data science etc..




















Friday, November 3, 2017

Java Interview Questions for above 5 years experience

In this post we will know about who having above 5 years experience as a Java Programmer what topics he must covered before facing interview and what types questions he or she should face questions. If you are a Java programmer with 4 to 8 years experience of working in Java and looking for job change then its better to know what is expected from a 4 to 8 years experienced Java programmer in a typical core Java or J2EE interview. 

Since 4 to 8 years is  a huge experience so you must have cover these topics such as Garbage collection tuning or designing complex Java applications or even creating concurrent Java design pattern. Due to J2EE and various framework it’s difficult to survive as Java Developer, you must have some understanding of these framework before going for an interview.For designing perspective learn Design Patterns,Polyglot Persistence.earn Spring MVC with Hibernate, first learn basics then design some CRUD (CREATE,Read,Update,Delete Web App).Mutexes, ReadWriteLock, ConcurrentHashMap, ArrayBlockingQueue, Thread pools, LinkedList vs ArrayList, Object Pooling, Read-Modify-Write, java.util.concurrent, java.util.concurrent.atomic, CAS, Collections, ADT, Java 5 Generics,Java Memory Model, Weak references,Jini, JMS, Javaspaces, JGroups, Hibernate trivia,,best practices in API design,Service Oriented Architecture / Web Services - SOAP / Rest.But if experience is 6+ then expectation is bit higher and my most preferred questions are -Questions from Executer framework like semaphore, barrier, latch, thread pool, callable, etc. Thread safety, Explicit locking, etc.Servlets thread safety, Servlets listeners. 
ORM, why use ORM, which ORM to use, ORM with cache, problems in using ORM like Concurrency and persistence exceptions. JAX-WS, web services, REST, where to use REST
One framework is a must. Cloud computing concept and architecture. Messaging advanced, guaranteed delivery and integration, and where to use messaging and where to use web services.

The following are some of the interview questions must Read:

1) why we use Generics?

Ans: Using Generics we have lots of benefits. They are
  • Stronger type checks at compile time. And thus avoid casting errors at run-time.
  • No need of casting. No extra code for casting like String s = (String) list.get(0).
  • Better, Intelligent, Generic, and good looking programming.  

2)How can you tell that instance is never garbage collected?

Ans: This is nothing but a singleton kind of pattern. There's a static reference to a singleton, so it won't be eligible for garbage collection until the classloader is eligible for garbage collection.

3) Can we write final method in interface? 

Ans: NO, because interface methods do not have body . It need to be implement in implemented class.

4)How to implement a polling mechanism in Java?  How if I want to poll something. How if client is sending some requests to server and if request doesn't arrives in within time limit or if no requests for like 2 minutes, stop expecting more requests and suspend operation/listening/waiting ?

Ans: Using Class ArrayBlockingQueue. Also, an useful method of ArrayBlockingQueue -

Example: 

public E poll(long timeout,TimeUnit unit)throws InterruptedException

5) When are class garbage collected, when are classes unloaded?
Ans: The only way that a Class can be unloaded is if the Classloader used is garbage collected. 

6)Why does Java not support operator overloading?

Ans: Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading.

7)Difference between synchronized  block and synchronized method ?

Ans : Synchronized Method defines a self contained block and  its easy to handle in multi-threaded environment. Both act as similar; there is no major advantage over each other. The difference is that a synchronized block can choose which object it synchronizes on. A synchronized method can only use 'this' (or the corresponding Class instance for a synchronized class method).

8)Difference between java.util.date and java.sql.date ?

Ans : As we know every database support most three form of entry i.e. date, time and  timestamp. In java JDBC having all those supports using java.sql.Date, java.sql.Time, java.sql.TimeStamp. Internally all these JDBC classes extends java.util.Date.

9)How to handle the runtime exception in jsp?

Ans : In jsp page directive you can use isErrorPage=true.

10) Difference between Cyclic Barrier and Countdown Latch ?
Ans: 
  • 1. Important thing in barrier is number(which is increment till it reaches its limit) and in latch is count(which is decremented till it reaches 0). 
  • 2. Any thread can lower the count of latch by calling countDown(), i.e. without waiting, this can't happen in barrier. 
  • 3. Latch can't be reused. 
  • 4. In barrier we can have a BarrierAction, nothing similar is in Latch. 
11) What are the protocols for web services?

Ans: 


JSON-RPC (RPC) : All transfer types are single objects, serialized using JSON. https://code.google.com/p/json-rpc/wiki/Usage
JSON-RPC is lightweight remote procedure call protocol similar to XML-RPC

SOAP (SOA, needs WSDL):
SOAP like XML-RPC, but lot more features, requires WSDL. 

REST:
SOAP uses interfaces and named operations to expose business logic. REST uses (generally) URI and methods like (GET, PUT, POST, DELETE) to expose resources.

12)I want to print "Hello" even before main() is executed. How will you achieve that?

Ans: Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.

13)Should a main() method be compulsorily declared in all java classes?
Ans: No not required. main() method should be defined only if the source class is a java application.

14)I have 1 to 100 elements in array unordered, one element missed find that one?

Ans : There is existing old formula. Calculate the sum of all numbers stored in the array of size 11 means it hold 12 data. Then, subtract the sum from (12 * 13)/2

Basic Formula: n * (n + 1) / 2. 

15)We can get the container object through Bean factory and Application context what is the difference in both?

Ans: A BeanFactory is used to just instantiates and configures beans. An ApplicationContextalso does that, andit provides the supporting infrastructure to enable lots of enterprise-specific features such as transactions and AOP.

16)We have equals() to compare two methods then why comparator again ?

Ans : Because , equals() method will only compare the content . It cannot compare two different objects. Comparator interface has compareTo()  method  which compare 2 different object.

17)What is the difference between web server and app server?

Answer: A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.

18) How does a 3 tier application differ from a 2 tier one?

Ans: Tiers are the physical units of separation or deployment, while layers are the logical units of separation.Imagine that you’re designing an e-commerce website. A 3 tier architecture would consist of web pages, a web server and a database, with the corresponding 3 layers being the “Presentation”, “Business Logic” and “Database” layers.
If you take the database tier and layer out then your have a 2 tier architecture.
Source.

19)How does the version control process works?

Ans: Initiate, pull, branch, merge, commit, push.
(Init) Make your own repository. (Pull) Download an existing repository from a url. (Branch / Merge )Make revisions. Commit then push your modifications.

20) Explain about Spring MVC?

Answer is huge...please check this  here Spring MVC tutorial

21)What are the ways to access Hibernate by using Spring?

Ans:  There are two ways to access Hibernate with Spring: They are
  • Inversion of Control with a Hibernate Template and Callback
  • Extending HibernateDAOSupport and Applying an AOP interceptor node.

22)What are the benefits of the Spring Framework's transaction management?


Ans: There are mainly 3 types of benefits. They are

  1. It integrates very will with spring's various data access abstractions.
  2. It provides consistent programming model across different transaction APIs such as JDBC,JPA,Hibernate and JDO.
  3. It supports declarative transaction management
23) Does Spring Security support password hashing? What is salting?

Ans: Yes, Spring Security provides support for password hashing. The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised.

24)How is Security mechanism implemented using Spring?

Ans:  Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. 

Spring makes use of the DelegatingFilterProxy for implementing security mechanisms. It is a Proxy for standard Servlet Filter, delegating to a Spring-managed bean that implements the Filter interface. Its the starting point in the springSecurityFilterChain which instantiates the Spring Security filters according to the Spring configuration

Some of the features of Spring Security are: 
Comprehensive and extensible support for both Authentication and Authorization
Protection against attacks like session fixation, clickjacking, cross site request forgery, etc
Servlet API integration Optional integration with Spring Web MVC.

25)How to enable Spring Security in Web Application?

Ans: You can enable the Spring security by adding the Filter org.springframework.web.filter.DelegatingFilterProxy in your application’s web.xml.

Watch Video:  Java Interview Questions for experienced Developers

Thursday, November 2, 2017

What is the best Programming Language to learn

In this post we will discuss about some of best programming Language is used in today's IT industry. It is nearly impossible to say one language is the “best” because the criteria is dependent on so many factors.Languages serve different purposes at different times. Mobile, database, front end, back end, and so on.We have compiled a list of the best programming languages you can learn, potential salary and community support. 

According to our research, these are the top programming languages of 2017 will be -


  1.     Javascript
  2.     Java
  3.     Python
  4.     PHP
  5.     R
  6.     Matlab
  7.     Arduino
  8.     Swift

My top 5 languages in 2017, if I had to start from scratch with programming, would be this, and in this order:

Python:

Python is easy to learn and is probably the best “first programming language”, at least in my eyes. It's easy on the eyes, understandable, introduces basic programming concepts well and produces results quickly. Just don't get too complicated.

Java:

What is Java doing on this list, you ask? Well, to be honest, if you're not starting from scratch with programming, I'd recommend picking up Scala. But Java is still quite powerful: it runs on many devices, is object oriented and will allow you to dive into things like design patterns.

Combining the knowledge you picked up from gradually moving from Python to Swift and from Swift to Java, you've now learned nearly every programming concept that will allow you to learn every programming language. And that's the real trick: transcending the limits of just one or a set of languages and being able to apply your knowledge in nearly every language.

Swift:

Swift, Apples new programming language, is a step up from Python. It's easy on the eyes and understandable, and transitioning from Python will be easy thanks to Xcode's built-in playground feature, allowing you to play and get familiar with the language. Once you are, Swift will introduce you to important and more advanced programming concepts and related subjects like the linking of classes, optionals, UI development and testing. Besides, because Swift is Apples language, it'll be relatively easy to roll out anything you develop and actually make money with it. Other than that, I think it’s important to realize what is your current level in programming before thinking what to learn next. Think on a scale of 1 to 10 where you are in one particular domain/category, for example:

  1.     Low level programming
  2.     High level programming 
  3.     Working with data
  4.     Server side
  5.     Client side
  6.     App development
  7.     Game development

JavaScript:

The language that keeps coming back (in different forms and versions sometimes) is JavaScript (and I’m talking about the basic vanilla version, not frameworks). There is absolutely 0% chance to never encounter a project that has some .JS in it. If you didn’t learn JavaScript yet, start learning it now and you’ll thank me later.

Ruby:

Ruby on Rails is slowly sliding down the list of applicable languages to learn. This may be caused by Ruby losing some of its market share to increasingly popular alternatives like Node.js and Go. But that doesn’t mean there aren’t any jobs for it, or any reasons to learn Ruby on Rails in general. It’s still a popular language, just not as hot as it used to be.

If there’s one thing to take away from our analysis, it’s that no programming language can accomplish every task and the job market changes quickly from year to year. To be a successful developer, it’s important to master multiple languages and train yourself to pick up new languages quickly so you can adapt to changing job opportunities.

PHP:

PHP is the most popular server-side programming language in the world.
It’s generally used as the foundation of Content Management Systems for WordPress and other websites like Wikipedia and Facebook.


If you’re primarily a front-end developer, attempt back-end coding. Try PHP, Node.js, Ruby or whatever piques your interest, then add SQL to your skill set.If you’re primarily a back-end developer, learn HTML, CSS and JavaScript. Browser APIs and data formats such as JSON are also beneficial. 

PYPL Popularity:


The PYPL Popularity of Programming Languages Index uses data from Google Trends to determine how often language tutorials are searched online:
  •     Java — 23.1%
  •     Python — 14.4%
  •     PHP — 9.7%
  •     C# — 8.4%
  •     JavaScript — 7.7%
  •     C — 7.1%
  •     C++ — 7.0%
  •     Objective—C — 4.4%
  •     R — 3.4%
  •     Swift — 3.0






 

Monday, October 30, 2017

Java 9 features

In this post we will know some of the important features of JAVA 9. There are lots of new enhancements which are going to affect your programming style. The most important improvement is modularization  of java,which should make java platform more scalable while improving its deployments on smaller devices. 


Here are list of Java 9 features:



  1.     Modularity
  2.   interface Private Methods
  3.     Strings
  4.     Diagnostics
  5.     JVM options
  6.     Logging
  7.     HTTP2 Client
  8.     JavaScript/HTTP
  9.     Native Platform
  10.     Java Docs updates
  11.     Images
  12.     Unicode
Modularity:

This is core feature of Java 9. A module is new construct like we already have packages. An application, developed using new modular programming, can be seen as collection of interacting modules with a well-defined boundaries and dependencies between those modules.

Private Methods:

 Private methods will improve code re-usability inside interfaces. For example, if two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method to it’s implementing classes.

String:

Two interesting string-related features, Compact Strings and Indify String Concatenation will be part of JDK 9. JEP 254, the compact strings optimization for OpenJDK 9 will improve the footprint of Java String and related classes while preserving full compatibility for all related Java and native interfaces. JEP 280, Indify String Concatenation will enable invokedynamic to concatenate strings, to free runtime implementors for optimizing string concatenation without pushing users to recompile their programs.

Diagnostics:

It describes in detail the diagnostic tools in JDK 9 and troubleshooting tools specific to various operating systems. 


HTTP2/Client:

HTTP/1.1 client was released on 1997. A lot has changed since. So for Java 9 a new API been introduced that is cleaner and clearer to use and which also adds support for HTTP/2. New API uses 3 major classes i.e. HttpClient, HttpRequest and HttpResponse.The beta HTTP/2 client API has come to JDK 9, implementing in Java the upgrade to the web’s core HTTP protocol. WebSocket is supported by the API as well.

The HTTP/2 API can replace the HttpURLConnection API, which has had problems, including being designed with now-defunct protocols, predating HTTP/1, being too abstract, and being hard to use.

JVM Options:

The defining feature for Java 9 is an all-new module system. When codebases grow larger, the odds of creating complicated, tangled “spaghetti code” increase exponentially. There are two fundamental problems: It is hard to truly encapsulate code, and there is no notion of explicit dependencies between different parts (JAR files) of a system. Every public class can be accessed by any other public class on the classpath, leading to inadvertent usage of classes that weren't meant to be public API. Furthermore, the classpath itself is problematic: How do you know whether all the required JARs are there, or if there are duplicate entries? The module system addresses both issues.

Modular JAR files contain an additional module descriptor. In this module descriptor, dependencies on other modules are expressed through`requires` statements. Additionally, `exports` statements control which packages are accessible to other modules. All non-exported packages are encapsulated in the module by default. Here's an example of a module descriptor, which lives in module-info.java

Logging:

Java 9 will introduce a common logging system for all JVM components. This will overhaul how the JVM reports events in its subsystems and add common logging command-line options for loggers.

Unicode:

In JDK 9, the Javadoc documentation tool is enhanced to generate HTML5 markup. The Unicode 8.0 encoding standard—which adds 8,000 characters, 10 blocks, and six scripts—is supported as well.











Saturday, April 22, 2017

Java Vector Class with Examples

A Vector class also stores elements similar to ArrayList,but Vector is Synchronized.Vector class implements the List interface.The underlying Data Structure is re-sizable array or growable array. Every method present in the Vector class is synchronized and vector object is Thread-safe.

Creating Vector Class:

1) Vector v=new Vector();//creates an empty vector object with default initital capacity 10
                                                       (OR)
2) Vector v=new Vector(int initialCapacity);//creates a vector 'object' with the specified capacity.Whenever an element is added to the initial capacity,the capacity of the vector is doubled.
 Like this:  new capacity=currentcapcity*2
                                                        (OR)
3) Vector v=new Vector(int initialCapacity,int incrementCapacity)

Vector specific methods:

boolean add(E e)   -------->  Appends the element e to the end of the list

void add(int i,E element)--------> inserts the element e at the specified index 'i'in the list

void addElement(Object 0)------>inserts the element to the vector and increses the vector size by 1,This method is synchronized.

To REMOVE objects:

element remove(int index)  -----> This method removes the element at the specified position in the vector.This method also returns the element which was removed from the Vector.

boolean remove(Object o)  ------> This method removes the first occurrence of the specified element object from the vector,if it is present

void clear() -----> This method removes all the elements from the vector.

To Access Elements:

Object get(int index) -----> This method returns the element available at the specified position in the vector

int size() -----> This method returns the number of elements present in the Vector.

Example:
import java.util.*;
class VectorDemo
{
public static void main(String arg[])
{
Vector v = new Vector();
System.out.println(v.capacity());
for (int i = 0;i<10 ;i++ )
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("Aa");
System.out.println(v.capacity());
System.out.println(v);
}
}
Output:







Example 2:

This example shows creating a vector with Integer elements

import java.util.*;
class VectorTest
{
public static void main(String args[])
{
Vector<Integer>v=new Vector<Integer>();
//take an int type array
int x[]={12,23,34,45,55};
for(int i=0;i<x.length;i++)
{
v.add(x[i]);
}
//retrieve the elements using get()
System.out.println("vector elements");
for(int i=0;i<v.size();i++)
{
System.out.println(v.get(i));
}
//retrieve using ListIterator
System.out.println("Elements using ListIterator");
ListIterator li=v.listIterator();
System.out.println("In forward direction:");
while(li.hasNext())
System.out.println(li.next()+"\t");
System.out.println("Backward Direction:");
while(li.hasPrevious())
System.out.println(li.previous()+"\t");
}
}
Output:











ALSO READ:
How to prepare for campus interviews
Java for each loop with example
How Java PROGRAM WORKS
Java Object class methods with examples

                                                      

Friday, April 21, 2017

How to Solve Producer Consumer Problem in Java

Producer Consumer Problem is an important design concept involving multi-threading and inter thread communication. The main concept is that,Producer thread will produce the items to the Queue Consumer thread will Consume items from the Queue.If the Queue is empty Consumer thread has to call wait() method on the Queue object then it will enter into waiting state.After producing the items Producer thread has to give notification so that Consumer thread will get that notification and consume items.

Pseudo code to solve produce consumer problem:


Example:
This program shows how to solve producer consumer problem using wait() and notify()

class InterThread
{
public static void main(String args[])throws Exception
{
//producer produces some data which consumer consumes
Producer p1=new Producer();
//pass producer object to consumer so that it is then available to consumer
Consumer c=new Consumer(p1);
//create two threads and attach producer and consumer
Thread t1=new Thread(p1);
Thread t2=new Thread(c);
//Run the threads
t2.start();//consumer waits
t1.start();//producer starts production
}
}
class Producer extends Thread
{
//to add data,we use string buffer object
StringBuffer sb;
Producer()
{
sb=new StringBuffer();//allot memory
}
public void run()
{
synchronized(sb)
{
//go on appending data to string buffer
for(int i=1;i<=10;i++)
{
try{
sb.append(i+":");
Thread.sleep(2000);
System.out.println("adding");
}
catch(Exception e)
{}
}
//data production is over,so notify to consumer thread
sb.notify();
}
}
}
class Consumer extends Thread
{
//creates producer refercence to refer to producer object from consumer class
Producer prod;
Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
//wait till a notification is received from producer thread
try{
prod.sb.wait();
}
catch(Exception e)
{}
//when data production is over,display data of string buffer
System.out.println(prod.sb);
}
}
}

Output:
adding
adding
adding
adding
adding
adding
adding
adding
adding
adding
1:2:3:4:5:6:7:8:9:10:

Read Also:

InterThread Communication
Synchronization Interview Questions
How to find duplicate elements in array



High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...