-
Java JDK, JRE and JVM:
Pic Courtesy: https://www.naukri.com
What is Java Virtual Machine (JVM)?
Java Virtual Machine (JVM) is an abstract machine responsible for compiling and executing Java code. It is a part of the Java Runtime Environment (JRE) which calls the main function of a program.
- JVM facilitates a platform-independent way of executing Java source code. Its basis on WORA (Write Once Run Anywhere).
- It has a class loader, runtime data area, execution engine, and libraries.
- JVM comes with JIT(Just-in-Time) compiler that converts Java source code into machine code.
First, the java compiler compiles a Java file into a Java .class file. Then the .class file works as an input into the JVM, which loads and executes the class file.
What is Java Runtime Environment (JRE)?
JRE is software that includes JVM and class libraries to run java programs independently. Although it can execute the code. Yet, JRE comes bundled with Java development Kit (JDK) to provide a complete application development experience.
- The JRE includes class libraries along with JVM and its supporting files. Note: It does not include separate tools such as a debugger for Java development.
- JRE comprises significant package classes such as util, math, AWT, lang, and various runtime libraries.
JRE = JVM + Class Libraries (For Running the Java Applications).
What is the Java Development Kit (JDK)?
Java Development Kit (JDK) is a complete software environment for building applications and applets using the Java programming language. It is platform-dependent. Therefore, it has different OS platform versions for Windows, Linux, Mac, etc. It allows to read, write, and execute the java program.
- It includes various tools required for writing Java programs.
- It includes an Appletviewer, Java application launcher, debugger, compiler, etc.
- JDK also consists of JRE for executing Java programs.
- The Java application launcher helps in opening a JRE. Then, it loads the necessary details and executes the main method of the program.
JDK = Development Tools + JRE (Java Runtime Environment)
Difference between JVM, JRE, and JDK:
JDK JRE JVM JDK stands for Java Development Kit. JRE stands for Java Runtime Environment. JVM stands for Java
Virtual Machine.It is a software development kit that helps in the development of applications in Java. Along with JRE, the JDK includes other various development tools. It is a kind of software package that provides class libraries of Java with JVM. Moreover, it includes other components for running the Java applications. It is a platform-independent abstract machine that includes a loader, runtime data, and execution engine. It is also known as a Java interpreter. JDK is platform-dependent. For each OS platform (Linux, Windows, Mac, etc.) users are required to install a different JDK. JRE is also platform-dependent like JDK. Unlike JDK and JRE, JVM is platform-independent, which means users won’t require different JVM for each OS platform. It consists of various tools for debugging, monitoring, and developing java applications. It contains various supporting files for JVM and the class libraries that help JVM in running the program. JVM particularly does not consist of any tools for software development. JDK is the superset of JRE. JRE is the subset of JDK. JVM is a subset of JRE. JDK comes with the installer for OS. JRE only contains an environment to execute source code. JVM is bundled in both software JDK and JRE. Table Conclusion:
Java is one of the most popularly used programming languages worldwide. Java Development Kit (JDK) plays a vital role in Gaming, GUI, Web, and Mobile Application Development.
Reference: https://www.naukri.com
-
Software Development Life Cycle (SDLC):
The Software Development Life Cycle (SDLC) refers to a methodology with clearly defined processes for creating high-quality software. in detail, the SDLC methodology focuses on the following phases of software development:
- Requirement analysis
- Planning
- Software design such as architectural design
- Software development
- Testing
- Deployment
What is the software development life cycle?
SDLC or the Software Development Life Cycle is a process that produces software with the highest quality and lowest cost in the shortest time possible. SDLC provides a well-structured flow of phases that help an organization to quickly produce high-quality software which is well-tested and ready for production use.
The SDLC involves six phases as explained in the introduction. Popular SDLC models include the waterfall model, spiral model, and Agile model.
How the SDLC Works:
SDLC works by lowering the cost of software development while simultaneously improving quality and shortening production time. SDLC achieves these apparently divergent goals by following a plan that removes the typical pitfalls of software development projects. That plan starts by evaluating existing systems for deficiencies.
Next, it defines the requirements of the new system. It then creates the software through the stages of analysis, planning, design, development, testing, and deployment. By anticipating costly mistakes like failing to ask the end-user or client for feedback, SLDC can eliminate redundant rework and after-the-fact fixes.
Stages and Best Practices:
Following the best practices and/or stages of SDLC ensures the process works in a smooth, efficient, and productive way.
1. Identify the Current Problems
“What are the current problems?” This stage of the SDLC means getting input from all stakeholders, including customers, salespeople, industry experts, and programmers. Learn the strengths and weaknesses of the current system with improvement as the goal.
2. Plan
“What do we want?” In this stage of the SDLC, the team determines the cost and resources required for implementing the analyzed requirements. It also details the risks involved and provides sub-plans for softening those risks.
3. Design
“How will we get what we want?” This phase of the SDLC starts by turning the software specifications into a design plan called the Design Specification. All stakeholders then review this plan and offer feedback and suggestions. It’s crucial to have a plan for collecting and incorporating stakeholder input into this document. Failure at this stage will almost certainly result in cost overruns at best and the total collapse of the project at worst.
4. Build
“Let’s create what we want.”
At this stage, the actual development starts. It’s important that every developer sticks to the agreed blueprint. Also, make sure you have proper guidelines in place about the code style and practices.
5. Code Test
“Did we get what we want?” In this stage, we test for defects and deficiencies. We fix those issues until the product meets the original specifications.
In short, we want to verify if the code meets the defined requirements.
Try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, and Python.
6. Software Deployment
“Let’s start using what we got.”
At this stage, the goal is to deploy the software to the production environment so users can start using the product. However, many organizations choose to move the product through different deployment environments such as a testing or staging environment.
Examples
The most common SDLC examples or SDLC models are listed below.
Waterfall Model
This SDLC model is the oldest and most straightforward. With this methodology, we finish one phase and then start the next. Each phase has its own mini-plan and each phase “waterfalls” into the next. The biggest drawback of this model is that small details left incomplete can hold up the entire process.
Agile Model
The Agile SDLC model separates the product into cycles and delivers a working product very quickly. This methodology produces a succession of releases. Testing of each release feeds back info that’s incorporated into the next version. According to Robert Half, the drawback of this model is that the heavy emphasis on customer interaction can lead the project in the wrong direction in some cases.
Iterative Model
This SDLC model emphasizes repetition. Developers create a version very quickly and for relatively little cost, then test and improve it through rapid and successive versions. One big disadvantage here is that it can eat up resources fast if left unchecked.
V-Shaped Model
An extension of the waterfall model, this SDLC methodology tests at each stage of development. As with waterfall, this process can run into roadblocks.
Big Bang Model
This high-risk SDLC model throws most of its resources at development and works best for small projects. It lacks the thorough requirements definition stage of the other methods.
Spiral Model
The most flexible of the SDLC models, the spiral model is similar to the iterative model in its emphasis on repetition. The spiral model goes through the planning, design, build and test phases over and over, with gradual improvements at each pass.
Benefits of the SDLC
SDLC done right can allow the highest level of management control and documentation. Developers understand what they should build and why. All parties agree on the goal upfront and see a clear plan for arriving at that goal. Everyone understands the costs and resources required.
Reference: https://stackify.com
-
GitHub:
At a high level, GitHub is a website and cloud-based service that helps developers store and manage their code, as well as track and control changes to their code. To understand exactly what GitHub is, you need to know two connected principles:
- Version control
- Git
In this article, we’ll first explain those two principles. Then, we’ll dig into more about GitHub and how you can actually use GitHub to work with WordPress and/or Kinsta.
What Is Version Control?
Version control helps developers track and manage changes to a software project’s code. As a software project grows, version control becomes essential.Version control, also known as source control, is the practice of tracking and managing changes to software code. Version control systems are software tools that help software teams manage changes to source code over time. As development environments have accelerated, version control systems help software teams work faster and smarter. They are especially useful for DevOps teams since they help them to reduce development time and increase successful deployments.
What Is Git?
Git is a specific open-source version control system created by Linus Torvalds in 2005.
Specifically, Git is a distributed version control system, which means that the entire codebase and history is available on every developer’s computer, which allows for easy branching and merging.
According to a Stack Overflow developer survey, over 87% of developers use Git.
What Is GitHub?
s a web-based Git repository. This hosting service has cloud-based storage. GitHub offers all distributed version control and source code management functionality of Git while adding its own features. It makes it easier to collaborate using Git.
Additionally, GitHub repositories are open to the public. Developers worldwide can interact and contribute to one another’s code, modify or improve it, making GitHub a networking site for web professionals. The process of interaction and contribution is also called social coding.
How to Create GitHub Account:
If you don’t already have a GitHub account, here’s how to create one.
1. Open https://github.com in a web browser, and then select Sign up.
2. Enter your email address.
3. Create a password for your new GitHub account, and Enter a username, too.Next, choose whether you want to receive updates and announcements via email, and then select Continue.
4. Verify your account by solving a puzzle. Select the Start Puzzle button to do so, and then follow the prompts.
5.After you verify your account, select the Create account button.
6.Next, GitHub sends a launch code to your email address. Type that launch code in the Enter code dialog, and then press Enter.
Congratulations! You’ve successfully created your GitHub account.
Repository:
- A GitHub repository can be used to store a development project.
- It can contain folders and any type of files (HTML, CSS, JavaScript, Documents, Data, Images).
- A GitHub repository should also include a licence file and a README file about the project.
- A GitHub repository can also be used to store ideas, or any resources that you want to share.
Creating Repository step by step without command:
step 1: After successfully setting up GitHub account login to your account. You will see the screen as below.
step 2: Click on the new repository option.
Step 3: After clicking new repository option, we will have to initialize some things like, naming our project, choosing the visibility etc. After performing these steps click Create Repository button.
Step 4: After clicking the button, we will be directed to below page. Right now the only file we have is a readme file.
Step 5: Now click on the “Upload files” button.
Fork the Repository
We can fork any public repository from Github by clicking on the “Fork” button on your upper right-hand side of the page, underneath your user icon:
Now the repository will be forked to your Github account.
To push a new project to an existing GitHub repository, follow these steps:
- Create a GitHub repository for the existing project.
- Copy the GitHub URL for the new repo to the clipboard.
- Perform a
git init
command in the root folder of the existing project. - Add all of the existing project’s files to the Git index and then commit.
- Add the GitHub repo as a remote reference for the existing project.
- Perform a
git push
operation with the-u
and-f
switches. - Verify that the existing project’s files have been pushed to GitHub.
GitHub push tutorial commands:
Many DevOps professionals only want to know the Git commands needed to push their existing project to GitHub. To save those readers from going through the entire example, here are the Git commands used in this tutorial. These commands assume a push to a GitHub repo named existing-website:
git init
git add .
git commit -m "Add existing project files to Git"
git remote add origin https://github.com/cameronmcnz/example-website.git
git push -u -f origin master
Now,Successfully push to the projects.
Branch:
- A GitHub branch is used to work with different versions of a repository at the same time.
- By default a repository has a master branch.
- Any other branch is a copy of the master branch.
Commits:
At GitHub, changes are called commits.
Pull Requests:
- Pull Requests are the heart of GitHub collaboration.
- With a pull request you are proposing that your changes should be merged with the master.
- Pull requests show content differences, changes, additions, and subtractions in colors.
A a great way to learn GitHub, before working on larger projects, is to open pull requests in your own repository and merge them yourself.
References: https://www.w3schools.com , https://kinsta.com/.
-
Regular Expressions in Java
Java Regex
The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.
It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.
java.util.regex package
Regular expressions can be used to perform all types of text search and text replace operations.
Java does not have a built-in Regular Expression class, but we can import the
java.util.regex
package to work with regular expressions. The package includes the following classes:Pattern
Class – Defines a pattern (to be used in a search)Matcher
Class – Used to search for the patternPatternSyntaxException
Class – Indicates syntax error in a regular expression pattern
First, the pattern is created using the
Pattern.compile()
method. The first parameter indicates which pattern is being searched for and the second parameter has a flag to indicates that the search should be case-insensitive. The second parameter is optional.The
matcher()
method is used to search for the pattern in a string. It returns a Matcher object which contains information about the search that was performed.The
find()
method returns true if the pattern was found in the string and false if it was not found.Flags(TBD)
Flags in the
compile()
method change how the search is performed. Here are a few of them:Pattern.CASE_INSENSITIVE
– The case of letters will be ignored when performing a search.Pattern.LITERAL
– Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.Pattern.UNICODE_CASE
– Use it together with theCASE_INSENSITIVE
flag to also ignore the case of letters outside of the English alphabet
Java Regex Metacharacters
We have some meta characters in Java regex, it’s like shortcodes for common matching patterns.
Regular Expression Description \d Any digits, short of [0-9] \D Any non-digit, short for [^0-9] \s Any whitespace character, short for [\t\n\x0B\f\r] \S Any non-whitespace character, short for [^\s] \w Any word character, short for [a-zA-Z_0-9] \W Any non-word character, short for [^\w] \b A word boundary \B A non word boundary There are two ways to use metacharacters as ordinary characters in regular expressions.
- Precede the metacharacter with a backslash (\).
- Keep metacharcter within \Q (which starts the quote) and \E (which ends it).
References: https://www.w3schools.com/java/java_regex.asp , https://www.javatpoint.com/java-regex , https://www.digitalocean.com/community/tutorials/regular-expression-in-java-regex-example .
-
Palindrome in String:
private void String_Practise(String input) { // TODO Auto-generated method stub String reverse = ""; for(int i=input.length()-1;i>=0;i--) { reverse = reverse+input.charAt(i); } if(input.equals(reverse)) { System.out.println("Palindrome");} else { System.out.println("Not Palindrome"); } }
-
Task
Assignment 0:
- Create a class called Theatre
- Have main method in it.
- Create an instance[object] called raja of Theatre class.
- Call method bookTicket(200) eg. raja.bookTicket(100)
- Have method signature for bookTicket method with necessary arguments for handling the input 200.
- Define bookTicket method as below.
- Declare a local variable ticket_price in int datatype.
- Assign 120 as value for ticket_price variable.
- Subtract 120 from method argument (200)
- Store result of above line into another variable called balance of int datatype.
- return this balance to main method.
- In main method, receive this balance as int balance
- In main method, print as below.
System.out.println(“After booking ticket ” + balance);
Program:
package Task; public class Theatre { public static void main(String[] args) { // TODO Auto-generated method stub Theatre raja = new Theatre(); int balance = raja.bookTicket(200); System.out.println("After booking ticket " + balance); } private int bookTicket(int amount) { int ticket_price = 120; int balance = amount - ticket_price ; return balance; } }
Output:
After booking ticket 80
-
Java OOPS Scenarios
OOPs – Java – Practice Scenarios with detailed Explanations.
Each and every scenario presented here are for getting good understanding on OOP(Object Oriented Programming) through Java.
Scenario #1:
(Expected Understanding: Access Modifiers, Single Inheritance, getter methods, Constructor Overloading)
1) Create a Class named “Trainer”. – Have default instance variables String dept, institute – Assign values – “Java”, “Payilagam” to them – Have private instance variable int salary – Assign 10000 as value for salary. – Create getter method for salary. – Have instance method training() with void as return data type – Add a print statement inside training() method - Add main method [public static void main(String[] args)] – Have instance named as ‘trainerKumar’ and pass “CSE”, “payilagam” as arguments to it. – Handle above line with matching Constructor. 2) Create a sub class “SQLTrainer” under “Trainer”. – Have main method in it. – Create instance ram for this class – Handle with proper super class constructor – Access parent class instance variables – Call parent class instance method training() – Access salary using getter method in parent class
Program:
package scenario; public class Trainer { String dept = "Java"; String institute = "Payilagam"; private int salry = 1000; public Trainer(String dept, String institute) { this.dept = dept; this.institute = institute; } public int getSalry() { return salry; } void trainig() { System.out.println("Training"); } public static void main(String[] args) { Trainer trainerkumar = new Trainer("CSE","Payilagam"); System.out.println(trainerkumar.dept); } }
package scenario; class SQLTrainer extends Trainer { public SQLTrainer(String dept, String institute) { super(dept, institute); } public static void main(String[] args) { SQLTrainer ram = new SQLTrainer("IT","Payilagam"); ram.trainig(); System.out.println(ram.getSalry()); } }
Scenario #2:
(Expected Understanding: Interface, Class, static variables, dynamic binding)
1) Create an interface called ‘Actor’ – Have variables boolean makeUpRequired – Assign ‘true’ value for ‘makeUpRequired’ – Have variable String address. – Assign value as “Chennai” to address. – Have void methods act(), dance(), sing() 2) Create class named as ActorSivakumar with main method – implement interface ‘Actor’ to this class. – Give your own definitions for methods from interface – Have static variable String address. – Assign value to address as “Coimbatore”. – Have instance method ‘speaking()’ with void return data type. – Create instance for ActorSivakumar as below ActorSivakumar as = new ActorSivakumar(65, “Audi Car”) – Handle with proper Constructor – Access all the methods from ActorSivakumar class – Access variable address and print the value – Create another instance of interface ‘Actor’ using dynamic binding approach Actor ac = new Sivakumar(); – Handle with proper Constructor – Access methods in ActorSivakumar class. – Access variable address using ‘ac’ intance and print the value – Observe and note down the difference between two instances
Program:
package Scenario2; public interface Actor { boolean makeUpRequired = true; String address = "chennai"; void act(); void dance(); void sing(); }
package Scenario2; class ActorSivakumar implements Actor { static String address = "Coimbatore"; int Age; String Car; public ActorSivakumar(int Age, String Car) { this.Age = Age; this.Car = Car; } @Override public void act() { System.out.println("Acted"); } @Override public void dance() { System.out.println("Dancing"); } @Override public void sing() { System.out.println("Singing"); } public String speaking() { String a = "Speaking"; return a; } public static void main(String[] args) { ActorSivakumar as = new ActorSivakumar(65,"Audi Car"); as.act(); as.dance(); as.sing(); System.out.println(as.speaking()); System.out.println(ActorSivakumar.address); } }
package Scenario2; public class sivakumar extends ActorSivakumar implements Actor { public sivakumar(int Age, String Car) { super(Age,Car); } public static void main(String[] args) { Actor ac = new sivakumar(65,"Benz"); ac.sing(); ac.act(); ac.dance(); System.out.println(ac.address); } }
Scenario #3:
(Expected Understanding: Abstraction, Inheritance, return keyword, Method Arguments, Constructor)
1) Create an abstract class named ‘SmartPhone’ – Add the below abstract methods – int call(int seconds) – void sendMessage() – void receiveCall() – Add non abstract method void browse() – print ‘SmartPhone browsing’ inside browse() method definition – Have constructor as below. public SmartPhone() { System.out.println(“Smartphone under development”); } 2) Create class called ‘FactoryDemo’ as abstract subclass of SmartPhone – Add the below abstract methods – void verifyFingerPrint() – void providePattern() – Add non abstract method void browse() – print ‘Factory Demo browsing’ inside browse() method definition – Add variable boolean isOriginalPiece and assign ‘false’ as value. – Add static variable int price and set value as 0. 3) Create class called ‘Samsung’ with main method as sub class of FactoryDemo. – Add unimplemented methods – Add static variable int price and set value as 5000. – Create instance for Samsung class called sam – Access browse() method using sam instance. – Access price variable using sam instance. – Observe which method is called and note down.
Program:
package Scenario3; public abstract class Smartphone { public Smartphone() { System.out.println("Smartphone under development"); } abstract int call(int seconds); abstract void sendMessage(); abstract void receiveCall(); void browse(){ System.out.println("SmartPhone browsing"); } }
package Scenario3; public abstract class FactoryDemo extends Smartphone { boolean isOriginalPiece = false; static int price = 0; abstract void verifyFingerPrint(); abstract void providePattern(); void browse() { System.out.println("Factory Demo browsing"); } }
package Scenario3; public class Samsung extends FactoryDemo{ int price = 5000; @Override void verifyFingerPrint() { System.out.println("verified FingerPrint"); } @Override void providePattern() { System.out.println("Provided Pattern"); } @Override int call(int seconds) { return 0; } @Override void sendMessage() { System.out.println("Sending Message"); } @Override void receiveCall() { System.out.println("Recive Called"); } public static void main(String[] args) { Samsung sam = new Samsung(); sam.browse(); System.out.println(sam.price); } }
Scenario #4:
(Expected Understanding: Abstraction, Inheritance, Dynamic Binding, Polymorphism (Overriding), Constructor Overloading)
1) Create an abstract class called ‘India’ – Have below abstract methods – void speakLanguage() – void eat() – void dress() – Have static variable String capital = “New Delhi” – Have below Constructor public India(String primeMinister) { System.out.println(“our Prime Minister is” + primeMinister); } 2) Create an abstract class called ‘SouthIndia’ – Make this class as sub class of ‘India’ – Add below non abstract methods – void cultivate() – Print ‘Rice and Wheat cultivation’ inside this method – void livingStyle() – Print ‘Average development’ inside this method 3) Create a class called ‘TamilNadu’ with main method as sub class of ‘South India’. – Add unimplemented methods – Provide your own definitions wherever necessary. – Have static variable String capital = “Chennai” – Add below non abstract methods – void cultivate() – Print ‘Rice and Sugar cane cultivation’ inside this method – void livingStyle() – Print ‘Above Average development’ inside this method – Using class name “India” – access variable ‘capital’ and print the value – Using class name “TamilNadu” – access variable ‘capital’ and print the value. – Create instance for “SouthIndia” as below SouthIndia si = new TamilNadu() – Observe which methods and variables can be accessed using ‘si’ and note down.
Program:
package Scenario4; public abstract class India { static String capital = "New Delhi"; abstract void speakLanguage(); abstract void eat(); abstract void dress(); public India(String primeMinister) { System.out.println("our Prime Minister is " + primeMinister); } }
package Scenario4; public abstract class SouthIndia extends India{ public SouthIndia(String primeMinister) { super(primeMinister); } void cultivate() { System.out.println("Average development"); } }
package Scenario4; public class TamilNadu extends SouthIndia{ public TamilNadu(String primeMinister) { super(primeMinister); } public TamilNadu(){} static String capital = "Chennai"; @Override void speakLanguage() { System.out.println("Speking Tamil"); } @Override void eat() { System.out.println("Eating Idly"); } @Override void dress() { System.out.println("wearing Traditional VestiDostis"); } public void cultivate() { System.out.println("Rice and Sugar cane cultivation"); } public void livingStyle() { System.out.println("Above Average development"); } public static void main(String[] args) { System.out.println(India.capital); System.out.println(TamilNadu.capital); SouthIndia si = new TamilNadu(); si.cultivate(); si.dress(); si.eat(); si.speakLanguage(); } }
Scenario #5:
(Expected Understanding: Interface, access modifiers, Method Overriding)
1) Create a package called tamilnadu.chennai 2) Create an interface ‘TrafficRules’ under this package 3) Make sure this interface is public interface – Add variable String trafficCommisssioner = “Kavin”; – Add below methods – void goByDieselVehicle(); – void goByBicycle(); 4) Create class called ‘CommonManInChennai’ with main method in the same package tamilnadu.chennai – Implement interface ‘TrafficRulesChennai’ – Create instance for this class and access all the methods 5) Now, create another package called ‘india.newDelhi’ 6) Create an interface ‘TrafficRulesDelhi’ under this package 7) Make sure this interface is not public interface – it should be default interface – Add variable String trafficCommisssioner = “Navin”; – Add below methods – void dontGoByDieselVehicle(); – void goByBicycle(); 8) Create class called ‘CommonManInDelhi’ with main method in the same package india.newDelhi – Implement interface ‘TrafficRulesDelhi’ – Create instance for this class and access all the methods – Now, implement interface ‘TrafficRulesChennai’ also. – Add unimplemented methods – Access all the methods and observe the difference.
Program:
package tamilnadu.chennai; public interface TrafficRulesChennai { String trafficCommisssioner = "Kavin"; void goByDieselVehicle(); void goByBicycle(); }
package tamilnadu.chennai; class CommonManInChennai implements TrafficRulesChennai{ @Override public void goByDieselVehicle() { System.out.println("Buying DieselVehicle"); } @Override public void goByBicycle() { System.out.println("Buying Bicycle"); } public static void main(String[] args) { TrafficRulesChennai obj = new CommonManInChennai(); System.out.println(obj.trafficCommisssioner); obj.goByDieselVehicle(); obj.goByBicycle(); } }
package india.newDelhi; interface TrafficRulesDelhi { String trafficCommisssioner = "Navin"; void dontGoByDieselVehicle(); void goByBicycle(); }
package india.newDelhi; import tamilnadu.chennai.TrafficRulesChennai; class CommonManInDelhi implements TrafficRulesDelhi,TrafficRulesChennai{ @Override public void dontGoByDieselVehicle() { System.out.println("Don't Buying Diesel Vehicle"); } @Override public void goByBicycle() { System.out.println("Buying Bicycle"); } @Override public void goByDieselVehicle() { System.out.println("Buying Diesel Vehicle"); } public static void main(String[] args) { TrafficRulesDelhi obj1 = new CommonManInDelhi(); obj1.dontGoByDieselVehicle(); obj1.goByBicycle(); System.out.println(obj1.trafficCommisssioner); TrafficRulesChennai obj2 = new CommonManInDelhi(); obj2.goByDieselVehicle(); obj2.goByBicycle(); System.out.println(obj2.trafficCommisssioner); } }
-
Interface
Interface in Java:
An interface in Java is a blueprint of a class. It has static constants and abstract methods.An
interface
is a completely “abstract class” that is used to group related methods with empty bodies.It includes a group of abstract methods (methods without a body).Why use Java interface?
There are mainly three reasons to use interface. They are given below.
- It is used to achieve abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
We use the
interface
keyword to create an interface in Java. For exampleinterface Selvaraj { public void get_Money(); public void get_GoodJob(); }
Implementing an Interface:
Like abstract classes, we cannot create objects of interfaces.
To use an interface, other classes must implement it. We use the
implements
keyword to implement an interface.Example 1: Java Interface:
interface Selvaraj{ void go_GoodJob();} // implement the Selvaraj interface class Vicky implements Selvaraj{ public static void main(String[] args){ Selvaraj vetri = new Vicky(); vetri.go_GoodJob(); } // implementation of abstract method public void go_GoodJob(){System.out.println("I am looking for a good job");} }
Output:
I am looking for a good job
Implementing Multiple Interfaces:
In Java, a class can also implement multiple interfaces. For example,
interface Selvaraj { void get_Money(); void go_GoodJob(); } interface Selvi { void eating_Food(); void Wake_up(); } class Vicky implements Selvaraj,Selvi { public static void main(String[] args) { Selvaraj vetri = new Vicky(); vetri.get_Money(); vetri.go_GoodJob(); Selvi Vetri = new Vicky(); Vetri.eating_Food(); Vetri.Wake_up(); } public void get_Money(){System.out.println("The Money has Arrived");} public void go_GoodJob(){System.out.println("I am looking for a good job");} public void eating_Food(){System.out.println("I have eaten");} public void Wake_up(){System.out.println("I just woke up");} }
Output:
The Money has Arrived I am looking for a good job I have eaten I just woke up
Extending Multiple Interfaces:
An interface can extend multiple interfaces. For example,
interface Selvaraj { void get_Money(); void go_GoodJob(); } interface Selvi extends Selvaraj { void eating_Food(); void Wake_up(); } class Vicky implements Selvi { public static void main(String[] args) { Selvaraj vetri = new Vicky(); vetri.get_Money(); vetri.go_GoodJob(); Selvi Vetri = new Vicky(); Vetri.eating_Food(); Vetri.Wake_up(); } public void get_Money(){System.out.println("The Money has Arrived");} public void go_GoodJob(){System.out.println("I am looking for a good job");} public void eating_Food(){System.out.println("I have eaten");} public void Wake_up(){System.out.println("I just woke up");} }
Output:
The Money has Arrived I am looking for a good job I have eaten I just woke up
Notes on Interfaces:
- Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an “Animal” object in the MyMainClass)
- Interface methods do not have a body – the body is provided by the “implement” class
- On implementation of an interface, you must override all of its methods
- Interface methods are by default
abstract
andpublic
- Interface attributes are by default
public
,static
andfinal
- An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security – hide certain details and only show the important details of an object (interface).
2) Java does not support “multiple inheritance” (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
References: https://www.javatpoint.com/interface-in-java , https://www.geeksforgeeks.org/interfaces-in-java/ , https://www.w3schools.com/java/java_interface.asp , https://www.programiz.com/java-programming/interfaces .
-
Super Keyword in Java
Super Key Word In Java:
The
super
keyword refers to superclass (parent) objects.It is used to call superclass methods, and to access the superclass constructor.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.
Usage of Java super Keyword:
- super can be used to refer immediate parent class instance variable.
- super can be used to invoke immediate parent class method.
- super() can be used to invoke immediate parent class constructor.
Example:
Using
super
to call the superclass ofVicky
(subclass):class Selvi {// Superclass (parent) void Get_Money(){ System.out.println("Yeah,Getted Money with You"); } } class Vicky extends Selvi{ // Subclass (child) public static void main(String[] args){ Selvi vetri = new Vicky(); // Create a Vicky object vetri.Get_Money(); // Call the method on the Vicky object } void Get_Money(){ super.Get_Money(); // Call the superclass method System.out.println("Yeah,Getted Money with Me"); } }
Super():
Example:
// super keyword with constructor abstract class Parent{ // Superclass (parent) Parent(){ System.out.println("Parent Constructor"); } Parent(int no){ System.out.println("Parent - Single Args Constructor"); } abstract void get_GoodJob(); void grow(){ System.out.println("Organic way"); } } class Child extends Parent{ // Subclass (child) Child(){ System.out.println("Child Constructor "); } Child(int no){ super(no); // invoke or call parent class constructor System.out.println("Child Single Args Constructor "); } public static void main(String[] args) { Child child = new Child(); Child child2 = new Child(10); child.get_GoodJob(); } void get_GoodJob() { System.out.println("On the way "); } }
References : https://www.javatpoint.com , https://www.w3schools.com/java/ref_keyword_super.asp .
-
Abstraction
Abstraction in Java
Data abstraction is the process of hiding certain details and showing only essential information to the user.Abstraction is a process of hiding the implementation details and showing only functionality to the user.
There are two ways to achieve abstraction in java- Abstract class (0 to 100%)
- Interface (100%)(TBD)
Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class in Java.A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
- An abstract class must be declared with an abstract keyword.
- It can have abstract and non-abstract methods.
- It cannot be instantiated.
- It can have constructors and static methods also.
- It can have final methods which will force the subclass not to change the body of the method.
The
abstract
keyword is a non-access modifier, used for classes and methods:- Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
- Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Parent{ abstract void get_GoodJob(); void grow(){ System.out.println("Organic way");} }
From the example above, it is not possible to create an object of the Animal class:
Parent myObj = new Parent(); //will generate an error
To access the abstract class, it must be inherited from another class. Let’s convert the Parent class we used in the Polymorphism chapter to an abstract class:
// Abstract class abstract class Parent{ // Abstract method (does not have a body) abstract void get_GoodJob(); // Regular method void grow(){ System.out.println("Organic way"); } } // Subclass (inherit from parent) class Child extends Parent { public static void main(String[] args) { Child child = new Child(); // Create a Child object child.study(); child.grow(); } void study(){ // The body of study() is provided here System.out.println("Studying Abroad"); } }
References : https://www.w3schools.com/java/java_abstract.asp , https://www.javatpoint.com/abstract-class-in-java .
-
Types of Inheritance
Types of Inheritance(பரம்பரை வகைகள்):
There are five types of inheritance.
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base class for the derived class B.For Example.
// concept of single inheritance package Cuddalore; class Selvaraj //Parent Class { int age = 70; int salary = 15000; public void walking() { System.out.println("Walking"); } void doYoga() { System.out.println("Parent Yoga"); } } package Cuddalore; class Son extends Selvaraj //Child Class { // Driver class public static void main(String[] args) { Son son = new Son(); son.walking(); son.doYoga(); System.out.println(son.salary); System.out.println(son.age); } public void doBusiness() { System.out.println("Doing Business"); } }
2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a superclass and then the same subclass acts as a superclass for another class. For example,
// concept of Multilevel inheritance package Cuddalore; //GrandParent class class Selvaraj { int age = 70; int salary = 15000; public void walking() { System.out.println("Walking"); } void doYoga() { System.out.println("Parent Yoga"); } private void takeMedicine() { System.out.println("Medicines"); } } package Cuddalore; //Parent class class Son extends Selvaraj { int salary = 25000; int age = 35; public static void main(String[] args) { Son son = new Son(); son.walking(); son.doYoga(); System.out.println(son.salary); System.out.println(son.age); } public void walking() { System.out.println("Walking in 5-KMS"); } public void doBusiness() { System.out.println("Doing Business"); } } package Cuddalore; class Daughter extends Son //Child class { public static void main(String[] args) { Daughter daughter = new Daughter(); daughter.study(); daughter.walking(); daughter.doYoga(); } public void study() { System.out.println("Studying"); } }
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For example,
// concept of Hierarchical inheritance package Cuddalore; //Parent class class Selvaraj { int age = 70; int salary = 15000; public void walking() { System.out.println("Walking"); } void doYoga() { System.out.println("Parent Yoga"); } private void takeMedicine() { System.out.println("Medicines"); } } package Cuddalore; class Son extends Selvaraj //Child-1 class { int salary = 25000; int age = 35; public static void main(String[] args) { Son son = new Son(); son.walking(); son.doYoga(); System.out.println(son.salary); System.out.println(son.age); } public void walking() { System.out.println("Walking in 5-KMS"); } public void doBusiness() { System.out.println("Doing Business"); } } package Cuddalore; class Daughter extends Selvaraj { public static void main(String[] args) { Daughter daughter = new Daughter(); daughter.study(); daughter.walking(); daughter.doYoga(); } public void study() { System.out.println("Studying"); } } package Cuddalore; class Daughter2 extends Selvaraj { public static void main(String[] args) { Daughter2 Daughter2 = new Daughter2(); Daughter2.study(); Daughter2.walking(); Daughter2.doYoga(); } public void study() { System.out.println("Studying"); } }
4. Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple superclasses. For example,
package Cuddalore; class Selvaraj { int age = 70; int salary = 15000; public void walking() { System.out.println("Walking"); } void doYoga() { System.out.println("Parent Yoga"); } private void takeMedicine() { System.out.println("Medicines"); } } package Cuddalore; class Son extends Selvaraj { int salary = 25000; int age = 35; public static void main(String[] args) { Son son = new Son(); son.walking(); son.doYoga(); System.out.println(son.salary); System.out.println(son.age); } public void walking() { System.out.println("Walking in 5-KMS"); } public void doBusiness() { System.out.println("Doing Business"); } } package Cuddalore; class Daughter extends Son { public static void main(String[] args) { Daughter daughter = new Daughter(); daughter.study(); daughter.walking(); daughter.doYoga(); } public void study() { System.out.println("Studying"); } } package Cuddalore; class Daughter2 extends Son { public static void main(String[] args) { Daughter2 Daughter2 = new Daughter2(); Daughter2.study(); Daughter2.walking(); Daughter2.doYoga(); } public void study() { System.out.println("Studying"); } }
5. Hybrid Inheritance(TBD)
Hybrid inheritance is a combination of two or more types of inheritance. For example,
-
DataBase Management System:
DataBase
A database is an organized collection of data so that it can be easily accessed. To manage these databases, Database Management Systems (DBMS) are used.
Types of DBMS
In general, there are two common types of databases:
- Non-Relational
- Relational
Introduction to SQL
Structured Query Language (SQL) is a standard query language that is used to work with relational databases.
We use SQL to
- create databases
- create tables in a database
- read data from a table
- insert data in a table
- update data in a table
- delete data from a table
- delete database tables
- delete databases
- and many more database operations
These SQL commands are mainly categorized into four categories as:
- DDL – Data Definition Language
- DQL – Data Query Language
- DML – Data Manipulation Language
- DCL – Data Control Language
- TCL – Transaction Control Language
Pic Coustery : https://www.geeksforgeeks.org/
References : https://www.geeksforgeeks.org/ , https://www.programiz.com/sql/select
-
Java
Java Data Types
Basically Data Types are Divided into two Types :
- Primitive data types – includes
byte
,short
,int
,long
,float
,double
,boolean
andchar
. - Non-primitive data types – such as Strings,Arrays,Classes,Etc.
Primitive Data Types :
The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable’s type and name, as you’ve already.Example: int gear = 1.
In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values.
The eight primitive data types supported by the Java programming language are:
- byte data type
- char data type
- short data type
- int data type
- long data type
- float data type
- boolean data type
- double data type
Data Type Size Description byte
1 byte Whole numbers from -128 to 127 short
2 bytes Whole numbers from -32,768 to 32,767 int
4 bytes Whole numbers from -2,147,483,648 to 2,147,483,647 long
8 bytes Whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float
4 bytes Fractional numbers. Sufficient for storing 6 to 7 decimal digits double
8 bytes Fractional numbers. Sufficient for storing 15 decimal digits boolean
1 bit true or false values char
2 bytes Single character/letter or ASCII values References : https://www.w3schools.com/ ,https://docs.oracle.com/ .
Java OOPs Concepts
Java – What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.
Object-oriented programming has several advantages over procedural programming:
- OOP is faster and easier to execute
- OOP provides a clear structure for the programs
- OOP helps to keep the Java code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
- OOP makes it possible to create full reusable applications with less code and shorter development time
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:
Pic Courtesy : https://www.geeksforgeeks.org/
References : https://www.javatpoint.com/java-oops-concepts , https://www.geeksforgeeks.org/object-oriented-programming-oops-concept-in-java/
Java – Constructors
A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Types of Constructor
In Java, constructors can be divided into 3 types:
- No-Arguments Constructor
- Parameterized Constructor
- Default Constructor
1. Java No-Arg Constructors
Similar to methods, a Java constructor may or may not have any parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-argument constructor.
2. Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are known as parameterized constructors (constructor with parameters).
3. Java Default Constructor
If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor.
The default constructor initializes any uninitialized instance variables with default values.
Type Default Value boolean
false byte
0 short
0 int
0 long
0L char
\u0000 float
0.0f double
0.0d object
Reference null Important Notes on Java Constructors
- Constructors are invoked implicitly when you instantiate objects.
- The two rules for creating a constructor are:
The name of the constructor should be the same as the class.
A Java constructor must not have a return type. - If a class doesn’t have a constructor, the Java compiler automatically creates a default constructor during run-time. The default constructor initializes instance variables with default values. For example, the
int
variable will be initialized to0
- Constructor types:
No-Arg Constructor – a constructor that does not accept any arguments
Parameterized constructor – a constructor that accepts arguments
Default Constructor – a constructor that is automatically created by the Java compiler if it is not explicitly defined. - A constructor cannot be
abstract
orstatic
orfinal
. - A constructor can be overloaded but can not be overridden.
References : https://www.programiz.com/java-programming/constructors , https://www.tutorialspoint.com/java/java_constructors.html
Access Modifiers in Java
There are two types of modifiers in Java: access modifiers and non-access modifiers.
Types of Access Modifier
Before you learn about types of access modifiers, make sure you know about Java Packages.
There are four access modifiers keywords in Java and they are:
- Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
- Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
- Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
- Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
References : https://www.javatpoint.com/access-modifiers , https://www.programiz.com/java-programming/access-modifiers .
- Primitive data types – includes