Memory Management is one of the important aspect of core java , a good programmer is always the one who always think about memory utilization while doing coding. so lets see how good you are in memory management basic concepts.
Thursday, April 26, 2018
Monday, April 23, 2018
by Admin
The Making of a Python App
Zachary Farley is one of our new contributor , He will mainly contribute articles in python language.
Hope he will be able to help you guys in python concepts. Let see this first article about Python App.
Author: Zachary Farley
Sunday, April 22, 2018
Saturday, April 21, 2018
Thursday, April 19, 2018
Tuesday, April 17, 2018
by Admin
Inheritance in java
In the last tutorial, we talked about Object Oriented Programming, and we mention various concepts in OOP. In that same tutorial, we went into detail about the concepts of Objects and Classes in Java.
In this tutorial, we’ll be dealing with one of the concepts we mention in the last one: Java Inheritance
Before we move further let see what all topic we have covered previously
Inheritance in Java is the process where one object or class acquires all the states (or properties) and behaviour of another object/class. The class whose states and behaviours is being acquired is known as the parent class or superclass, while the one that inherits is called the subclass.
With inheritance, we can create new classes built on existing classes; allowing you to reuse methods and variables from our parent class, add new ones, and arrange our data in a hierarchal order.
Inheritance in Java represents what is known as a parent-child relationship.
What do we use Inheritance in Java?
A major reason for inheritance in Java is for code reusability, as the subclass inherits everything from its parent class, including all variables and methods.
The extends keyword
The extends keyword is used to indicate that the class being created is inheriting properties from an existing class.
An Inheritance example
The following image shows an example of inheritance in Java, whereas a class named Puppy, inherits the properties of our parent class Dog.
Main Class looks like below:
Result :
In our given program, a Dog class is created, with the dogStats method, which takes in String and int variables and return the set print statements. When the Puppy class is created, which inherits from the Dog class, a copy of the parent’s contenst is created within it. This is why we can access the members of the Dog class using the Puppy class.
Trying to access the Puppy class with the Dog class will give an error.
The superclass reference variable can hold the subclass object, but using it will only access the members of the superclass. To access both, you’ll have to create reference variables to the subclass.
Note that the subclass inherits all the members from the super class. Members refers to the fields, methods and nested classes. Constructors are not members, and so cannot be inherited. They can be invoked from the subclass, though.
The IS-A Relationship
Also known as the parent-child relationship, an IS-A relationship simply means that an object is a type of another object. This form of relationship is achieved in inheritance:
Based on the example above, we can say the following:
For example:
A class can implement one or more interfaces, eliminating the need to perform that form of inheritance.
Next tutorial, we shall deal with Method Overriding.
Hope you like this article , Please share it with your friends and colleagues.
Also Read :
Thanks for reading
Noeik
In this tutorial, we’ll be dealing with one of the concepts we mention in the last one: Java Inheritance
Before we move further let see what all topic we have covered previously
- Making Games With Java- Introduction
- Getting Everything you need for Java
- Introduction to Java Programming
- Basic data types and Variables in java
- Basic Data types and Variables in java - Continued...
- User Input using Scanner class in java
- Conditional Logic in java
- Loops in java
- Arrays in java
- Wrapper classes in java
- Methods in java
- What are Object Oriented Programming Practices
Inheritance in Java is the process where one object or class acquires all the states (or properties) and behaviour of another object/class. The class whose states and behaviours is being acquired is known as the parent class or superclass, while the one that inherits is called the subclass.
With inheritance, we can create new classes built on existing classes; allowing you to reuse methods and variables from our parent class, add new ones, and arrange our data in a hierarchal order.
Inheritance in Java represents what is known as a parent-child relationship.
What do we use Inheritance in Java?
A major reason for inheritance in Java is for code reusability, as the subclass inherits everything from its parent class, including all variables and methods.
The extends keyword
The extends keyword is used to indicate that the class being created is inheriting properties from an existing class.
An Inheritance example
The following image shows an example of inheritance in Java, whereas a class named Puppy, inherits the properties of our parent class Dog.
package animal; public class Dog { public void dogStats(String name, int age){ System.out.println("His name is " + name); System.out.println("He is " + age + " year(s) old"); } } class Puppy extends Dog{ ppublic void pupStats(String name, int age){ System.out.println("His name is " + name); System.out.println("He is " + age + " week(s) old"); } }
public static void main(String[] args){ Puppy first = new Puppy(); first.dogStats("Doug",1); first.pupStats("Junior",3); }
His Name is Doug He is 1 year(s) old His name is Junior He is 3 week(s) oldExplaining the Inheritance example
In our given program, a Dog class is created, with the dogStats method, which takes in String and int variables and return the set print statements. When the Puppy class is created, which inherits from the Dog class, a copy of the parent’s contenst is created within it. This is why we can access the members of the Dog class using the Puppy class.
Trying to access the Puppy class with the Dog class will give an error.
The superclass reference variable can hold the subclass object, but using it will only access the members of the superclass. To access both, you’ll have to create reference variables to the subclass.
Note that the subclass inherits all the members from the super class. Members refers to the fields, methods and nested classes. Constructors are not members, and so cannot be inherited. They can be invoked from the subclass, though.
The IS-A Relationship
Also known as the parent-child relationship, an IS-A relationship simply means that an object is a type of another object. This form of relationship is achieved in inheritance:
- The Animal class is the parent of the Mammal and Reptile classes.
- The Dog class is the child or subclass of the Mammal class
- The Lizard class is the child or subclass of the Reptile class
- In an IS-A relationship, we may as well say:
- Mammal IS-A Animal
- Reptile IS-A Animal
- Dog Is-A Mammal
- Lizard IS-A Animal
- The HAS-A Relationship
- Unlike the IS-A relationship, this is based mainly on usage, or behaviour, or basically what an object has. This helps to reduce bugs and duplication of code.
For example:
Basically, we’re saying that the Dog HAS-A Tail. By having a class dedicated solely to the tail, we don’t have to put all the code for the tail in the Dog class, allowing us to reuse if for other classes that may require a tail; like a Cat class for example.
In OOP, the users do not have to worry about which object is actually doing the work. So the Dog class will hide implementation details from its users. Therefore, when the Dog class is to perform an operation, it will either do it by itself or ask another class to do it.
Types of Inheritance
There are about four type of Inheritance in Java:
- Single Inheritance: This takes place when a parent class had only one sub class.
- Multi-Level Inheritance: Here, the parent class has one subclass, and that subclass has its own subclass.
- Hierarchical Inheritance: In this form of inheritance, the parent class can have two or more subclasses.
- Multiple Inheritance: The opposite of Hierarchical Inheritance, this is achieved when a class has two or more parent classes. This is not supported in Java, though, so you cannot do this:
class Mammal extends Dog, Cat{
}
Next tutorial, we shall deal with Method Overriding.
Hope you like this article , Please share it with your friends and colleagues.
Also Read :
- Program to find the Nth Element of a Singly Linked list from the end in java
- [Program]Generic Implementation of custom linked list in java
- Program of Linked List Insertion and Deletion Operations in java
- Stack Implementation program in java
- Breadth first Traversal(BFT) AND Depth First Traversal(DST) Program in java
Thanks for reading
Noeik
Monday, April 16, 2018
by Admin
How to read value from property file in spring boot ?
Spring boot came to remove the boiler code as well as to make the deployment easy and also make so many functionality very easy.
In earlier article we have talk about how to read the value from the property file in java , now in this article we will talk about how to read property file in spring boot project.
You can download the project from GitHub
Lets look for the project structure.
There are two Class file and one application.properties file in this project.
ReadPropertyFileInSpringBootDemoApplication.java
package com.programinjava.learn; import javax.annotation.Resource; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ReadPropertyFileInSpringBootDemoApplication implements CommandLineRunner { @Resource ReadPropertyFileClass readPropertyFileClass; public static void main(String[] args) { SpringApplication.run(ReadPropertyFileInSpringBootDemoApplication.class, args); } @Override public void run(String... args) throws Exception { // TODO Auto-generated method stub readPropertyFileClass.showPropertyKeyValue(); } }
ReadPropertyFileClass.java
package com.programinjava.learn; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class ReadPropertyFileClass { @Value("${propertykey1}") // this annotation is used to read the property file value in spring boot String propertyKey; public void showPropertyKeyValue() { System.out.println("The Value of Property File key is "+propertyKey); } }
application.properties
Explanation:
Spring boot provide the annotation @Value to read the property value from properties file.
what you need to do is you just need to use @Value("${<property-key>}") where property-key will be replace by your property key whatever it is.
ex- @Value({"${key1}")
String keyValue;
Now when you access the keyValue , it will give you the Value of the key defined in properties file.
Hope this is helpful for you to see how to read property file in string boot.
Also read :
- Common Elements in Two Sorted Arrays Program in java
- Most Frequent Occurring Item in an Array program in java
- Program in java for Array Rotation
- Program to get all the substring of the string in java
- Quick Sort Program in java using Array
- Java Interview : Heap Sort Implementation using Array
- Bubble Sort using array Program in Java
- Selection Sort Program Implementation Program in java
- Insertion Sort Program in Java using Array
hope you like this article , please share it with your friends and colleagues.
Thanks for reading
Thanks for reading
Sunday, April 15, 2018
by Admin
How to read value from property file in java
In the tutorial , we will talk about how to read value from property files in java program. As we all know that property file are the best choice when it comes to configure the program without changing it's code. so lets see how to read value from property file in java
Le suppose we have a program where we are reading the values from property file in resource. Below is the code we would use.
You can download the source code from GitHub
You can download the source code from GitHub
The project Structure
Now look for App.java Code
package com.programinjava.learn.ReadPropertyFileDemo; /** * Read property file demo * */ public class App { public static void main( String[] args ) { // Now I will read the property value of property-key String valueOfKey = PropertyUtil.readProperty("property-key"); System.out.println(valueOfKey); } }
PropertyUtil Class Code:
package com.programinjava.learn.ReadPropertyFileDemo; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertyUtil { // define the path of property file private static final String PROPERTY_FILE_PATH="src/main/resources/app.properties"; public static String readProperty(String propName) { Properties prop = new Properties(); InputStream input = null; String propValue = null; try { input = new FileInputStream(PROPERTY_FILE_PATH); prop.load(input); propValue = prop.getProperty(propName); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return propValue; } }
Also read : how to read user input in java
Code Follow (Explanation):
- Basically we have first created new Maven project in eclipse .
- Created new folder called resource inside src/main/ and add new property file called app.property.
- Now , created new class file called App.java ( may be auto generated) , In that wee will create the main method for execution.
- After that we have created a utility class , where we have write the logic of reading property file( see PropertyUtil.java) and it will give use the value of key we will pass for read.
Hope this helps you if you like this post please share it with your friends and colleagues.
Also read :
Thanks for reading
Noeik
Also read :
- Common Elements in Two Sorted Arrays Program in java
- Most Frequent Occurring Item in an Array program in java
- Program in java for Array Rotation
- Program to get all the substring of the string in java
- Quick Sort Program in java using Array
Thanks for reading
Noeik
Tuesday, April 10, 2018
by Admin
Exception handling in java
Exceptions are very important topic of java programming , In this article we will look about Exception in java
We will cover following things in Exception handling:
- What are exceptions?
- Need of exception handling?
- Hierarchy of exception?
- Difference between runtime and compile time exceptions?
- How try – catch-finally work?
So let’s begin with what actually exceptions are and need of exception handling in Java.
Monday, April 9, 2018
Sunday, April 8, 2018
by Admin
How to create a new file in java
Most of the time we stuck in some scenario where we need to create the file or directory by coding in java , Let see how to create file in java from scratch.
Let see the program of creating a file in java
First we will create a project in java , the project structure is as below
Now lets see the program
package com.programinjava.filecreation; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FileCreatorDemo { public static void main(String[] args) throws IOException { FileCreatorDemo demo = new FileCreatorDemo(); // We need to create a file with Name - temp.txt String fileName = "temp.txt"; // call createFile Function if(demo.createFile(fileName)) { System.out.println("File is successefully created"); String writeThis = " We need to write this in file"; byte [] b = writeThis.getBytes(); Files.write(Paths.get(fileName), b); }else { System.out.println("File is not created "); } } public boolean createFile(String fileName) { if(fileName!=null) { File f = new File(fileName); if(!f.exists()) try { if(f.createNewFile()) return true; } catch (IOException e) { e.printStackTrace(); } }else { System.out.println("Filename is null"); return false; } return false; } }
Explanation :
- First we are create one file using the new File() of java IO package.
- then we have used the f.createNewFile() method to create a file .
- now we need to write something in file for which we have put statement in String and then convert it to bytes.
- Now as we have bytes we will now use Files.write function to write that statement , this function required the path of the file and the bytes which need to write.
You can download this from FileCreationDemo.zip
If you have any issue , leave us a comment.
Thanks for reading
Saturday, April 7, 2018
by Admin
Methods in java
Methods are one of the most important part of coding , this article is all about methods in java
before more further let see previous articles in series.
- Making Games With Java- Introduction
- Getting Everything you need for Java
- Introduction to Java Programming
- Basic data types and Variables in java
- Basic Data types and Variables in java - Continued...
- User Input using Scanner class in java
- Conditional Logic in java
- Loops in java
- Arrays in java
- Wrapper classes in java
A method in Java can be defines as a bunch of code that is written to form a particular operation or function. There are quite a lot of methods that are in-built into the java programming language, an example being the System.out.println() method. Though it seems like just one simple line of code, it actually executes several statements in the background in order to do what it does.
To view these background programmes, type out a print statement, select it and right-click. Under the Navigate option, click Go to Source.
In this lesson, you will see how to create your own methods and invoke your methods into your code. This will help you to keep your code concise, organised and more readable.
Defining a Method
An average method consists of a method header and a method body. The method header is the statement that determines the values that the method returns and how easily it can be accessed in and out of a class.
The method header usually consists of the following:
- Access Modifier: This determines how easily the method can be accesses. It is not necessary to add, but is usually advisable.
- Return Type: The type of value the method can return. It’s possible for the method to return no value.
- Method Name
- Parameters: The type, order, and number of parameters a method requires to return a value. A method can have no parameters
The method body is defined by the pair of opened and closed curly brackets immediately after our method header and consists mainly of the code we want the method to run and the return keyword.
Now, let’s look at the method below:
public int add(int firstNumb , int secondNumb){ int result =0; result = firstNumb+ secondNumb; return result; }
If we’re to break it down into the components listed above:
- public : access modifier
- int: return type
- methodName: the method name
- int firstNumb, int secondNumb: parameters
- result = firstNumb + secondNumb: code
- return result: return statement
The above method, named add(), takes two integer parameters firstNumb and secondNumb, and returns their sum, which will be saved in the integer variable result.
Calling your Method
When your code is run, it will only read the code written within the main method. In order to implement our methods in the program, the method will have to be invoked or called into the main method.
The process of doing this is quite simple. When a method is called in our main method, control is transferred from the main method to the called method. The code the executes the code in the curly bracket and returns the set value.
For example, let us call the above mentioned method ‘add’ into our main method:
public class CalculationDemo { public static void main(String[] args) { CalculationDemo demo = new CalculationDemo(); System.out.println("Will Add two number 10 , and 20"); int r =demo.add(10, 20); System.out.println(r); } public int add(int firstNumb , int secondNumb) { int result =0; result = firstNumb+ secondNumb; return result; } }
Result:- Will Add two number 10 , and 20 30
Void Method
So far, we can see that the type of data you set to the method is the type of data that it returns. If you create an integer method, it returns an integer. A string method will therefore return a string, a float method returns a float, a double method a double, and so on.
But there are times you don’t want your code to return any value. You just want it to perform a function and be done with it. This method is called a void method.
Also read : Basic and tricky java Interview Questions
Let’s recreate our last method, but make it void. Outside our last method, create this new method and call it addWithoutReturn:
public void addWithoutReturn(int first , int second) { int result =first +second; System.out.println(result); }
You can notice that it’s basically the same as our original method. The only difference is the absence of the return statement. This is replaced with a print statement, which causes it to automatically print out our variable when the method is called; so we don’t have to call a print statement in the main method.
Access Modifiers
Access Modifiers are keywords that determine how easily a method can be accessed or whether you can access a method within the class, the subclass or the java package. The three major access modifiers are:
- Public
- Private
- default
- Protected
Giving a public modifier will make your method or variable visible everywhere; even outside the java package. It is good practice not to do this, though, so that your variable will not be affected by an external user. It is more advisable to give your method a private or protected modifier.
A private modifier added before a method name will make it accessible to your class only. You won’t be able to access it anywhere outside your class; not even in the package. A protected modifier, on the other hand, will still allow your method to be seen everywhere, except outside the package. This is used mostly during inheritance and other related practices.
It is usually best to make your method or variable private, so that your method will not be manipulated by an external user. You can allow indirect access to your method or variable through the use of a getter and setter function. To access this; right-click your java file, click Insert Code, then click getter and setter. Choose the variable or method you need a getter and setter for, and click OK.
Access Modifiers grouped based on their Access Levels
Modifier
|
Class
|
Package
|
Sub-Class
|
World
|
Public
|
Access
|
Access
|
Access
|
Access
|
Protected
|
Access
|
Access
|
Access
|
No Access
|
No Modifier(default)
|
Access
|
Access
|
No Access
|
No Access
|
Private
|
Access
|
No Access
|
No Access
|
No Access
|
If we give a public modifier before any variable, it is visible everywhere in your project. It is good practice not to do this, though, so that it will not be affected by any other user. It is usually more advisable to declare your variable private or protected.
When your variable or method is declared private, it is only made available in the class. You cannot access it in any other class except its own. If you try to do so, it will give you an err because that class that cannot be accessed.
Protected is the least used among all these access modifiers, and so we won’t discuss it here because it is mostly used in Java Inheritance; so we will discuss that when we start on inheritance.
Next week, we’ll go a step further by talking about how to create classes.
Thanks for reading
Noeik
Subscribe to:
Posts (Atom)