Basic Structures of Java
In Java, we need to
declare package . For example,
package com.bazlur.Hashmap;
Now,why this package name is like this? Actually if there is a website like bazlur.com, people generally create a package named com.bazlur . Also, this means that under com folder, we have bazlur folder .import statement
If we want to use any other class of a package , we can import it. For example,import java.util.Hashmap;
declare types
In Java, the type can be a Class/Interface/Enum. We mention the class name and also use {}. For example,
public class HelloWorld {}
is type declaration of class HelloWorld where it is public.
Note: In Public class , class name & file name has to be same.
Field Declaration (Declaring different types of variables )
For example,protected final String hello="value"
Method
In Java, methods are associated with a class. For example,
public static void main(String[] args){
}
This is basically main method . To run a program in Java, you must need a main method in a class. Here the main method has few keywords (args) & String array parameter(String []).
In Java, the starts implementing from the main method which can be called as Entry point.
Input
To take an integer input , we will first create an object "scr". Then using the object, we will take input.
Scanner scr=new Scanner(System.in);//creating object scr
int a=scr.nextInt();//Taking integer input
Method
Now a class method may have multiple methods in it.
Let's see a format of a method
<Data type> <method name>(data type1 variable1, data type2 variable 2,............){
<main code>
return <something or 0>;
}
example:
int Addition(int a,int b){
int result=a+b;
return result;
}
Now, lets check a class where we have multiple methods.
import java.util.Scanner; //import this to scan something
public class run {
//main method
public static void main(String[ ] args){
Scanner scr=new Scanner(System.in);
int a=scr.nextInt();
int b=scr.nextInt();
int result=a+b;
}
//Addition method
int Addition(int a,int b){
int result=a+b;
return result;
}
//Subtraction method
int Subtraction(int a,int b){
int result =a-b;
return result;
}
}
A method have 6 components.
Modifier : As the method remains within a class and to interact with other methods, there needs to be some keyword .For example, public, protected, private etc. While using public keyword with a method, other methods can use that public method.
Return type: It generally returns a certain data.
Method name: Method has it's own name.
Parameter list: Method surely has some parameters.
List of exceptions: A method can throw one or more exception .
Method Body: All the codes remain in the method body.
import java.util.Scanner; //import this to scan something
public class run {
//main method
public static void main(String[] args) {
}
//public method printtext declared with a variable text which has a datatype String
public void printText(String text) {
System.out.println(text);
}
//public method writeText which has text1 & text2 parameter with datatype String
public void writeText(String text1, String text2) {
System.out.println(text1);
System.out.println(text2);
}
//public method sum declared which will return a int type of data. Also the parameters are value1,value2 which has a datatype of int
public int sum(int value1, int value2) {
return value1 + value2;
}
//a public method called concat which will return something String type. The parameters are value1 & value2 which has a String datatype.
public String concat(String value1, String value2) throws IllegalArgumentException {//if a method throws an exception, it needs to be declared after the method's name with parenthisis
if (value1 == null) {
throw new IllegalArgumentException("value1 is null");
}
if (value2==null){
throw new IllegalArgumentException("value2 is null");
}
return value1+value2;
}
}
Let's now see a code which covers Package declaration, import statement, class , fields, constructor, methods etc.
import java.util.Scanner; //import this to scan something
import java.awt.Point;
public class run {
//main method
public static void main(String[] args) {
}
//Field width,height,origin
private int width=0;
private int height=0;
private Point origin;
//class name & method name is same thus method does not mention any return type. Rather the codes within this method is going to be constructor
public run(int w, int h){//as the run is a class name and also method name, run method does not need to return any type
//Constructor
origin=new Point(0,0);//an object origin created
width=w;
height=h;
}
//public method move declared with data type of void.
public void move(int x,int y){
origin.x=x;
origin.y=y;
}
//creating a method called getArea which will return int data type
public int getArea(){
return width*height; //returning int data
}
}
Method can be of 2 types:
- Static: Static methods remain within a class & does not need to create object to use it. In static methods, we generally use
static
keyword
Now run.java has
public class run {
//creating square method which return integer type of data(static method)
public static int square(int n){
return n*n;
}
}
and test.java has
public class test{
//main method
public static void main(String[] args) {
int num = 2;
int square = run.square(num); //variable square now has called class run's one of the methods called square
System.out.println(square);
}
}
This is how static method is used.
- Non-static method: Non static method uses object . Run.java has
public class Run {
//Field radius which has data type integer
private int radius;
//constructor
public Run(int radius){
//this.radius is the field called
//radius in the right side is the parameter
this.radius=radius;
}
//creating double type of method getArea
public double getArea(){
return radius*radius*Math.PI;
}
}
Also test.java has
public class test{
//main method
public static void main(String[] args) {
//creating an object run
Run run= new Run(5);
//creating a data type double.
double area= run.getArea(); //using run object to get into the method
System.out.println(area);
}
}
Basically in run.getArea(), we have used run object and used method through it.
Creating an object/instance
For example:
Bicycle bike1 = new Bicycle();
here Bicycle is the class name whose properties you are going to use by creating the object. bike1 is the object name & Bicycle() is the constructor name
To create an object you need to have
Declaration : Here you need to declare Class name & object name. From the example,
Bicycle bike1
is the Declaration.Instantiation: To create an object , you need to use the keyword
new
Initialization: You need to call the constructor of the class here. For example,
Bicycle()
is the constructor here
Now, how you know about constructor, right?
public class run {
//main method
public static void main(String[] args) {
}
//Fields
private int width=0;
private int height=0;
private Point origin;
//Constructor
//The class & run method name is the same
//There is no return type for constructor
public run(int w, int h){//as the run is a class name and also method name, run method does not need to return any type
origin=new Point(0,0);//an object origin created
width=w;
height=h;
}
}
Here the run class has a constructor named run & performs the basic stuff which needs to be used while creating an object. If you don't create any constructor, java by default creates one for you.
Method overloading
In java, you can have multiple methods with same method name. They are just different based on their parameters.
public class run {
//main method
public static void main(String[] args) {
}
//performAddition method with integer return type. 2 integer parameters
int performAddition(int a, int b){
int result=a+b;
return result;
}
//performAddition method with integer return type . 4 integer parameters.
int performAddition(int a,int b, int c,int d){
int result=a+b+c+d;
return result;
}
//performAddition method with float integer type. 2 float parameters.
float performAddition(float a, float b){
float result=a+b;
return result;
}
}
Constructor overloading:
import java.util.Scanner; //import this to scan something
import java.awt.Point;
public class run {
//private fields id,name,age
private int id;
private String name;
private int age;
//main method
public static void main(String[] args) {
}
//Constructor 1 (when no variable is required)
public run(){
}
//Constructor 2 (when 1 variable is used)
public run(int id){
//Left hands (this.id) means the field id (private int id)
this.id=id;//Right hand's id means the parameter declared during the method creation (int id)
}
//Constructor 3 (used when 3 variables are called)
public run(int id,String name,int age){
//this.id means the id field mentioned in (private int id)
//this.name means the name field mentioned in (private String name)
//this.age means the age field mentioned in (private int age)
this.id=id;//right sides id ,name & age means the parameters mentioned in the method run
this.name=name;
this.age=age;
}
}
There can be multiple constructors . Depending on their usage, different constructors are selected/used.
Some good practice:
- If you don't want your field to be changed, make them private. Example:
private String name;
. This is called Data Field Encapsulation. - In getter methods, try to use
get
keyword before the method name. Example:
public int getPropertyName()
, Try to add is
keyword when you need to return Boolean type of data.
- In setter methods, use
set
keyword . Example :
public void setPropertyName()
Printing
basically we use println() to print something and go to next line. But if we use print(), we print that string or code but don't add a new line
so, println()=print()+\n
Remember, everything starts to work from the left side.
For example:
System.out.println(5+3+" Abcd");
here, first it gets 5+3 thus it becomes 8. then 8+" Abcd" . Here " Abcd" is a strings thus this "+" is used for string concatination.
again,
System.out.println(5+3*2+" Abcd");
Output:
11 Abcd
here it first gets 5+3*2 which leads to 5+6. Which again sums to 11. Now, it remains 11+" Abcd". Here. " Abcd" is a string and thus it will be string concatination.
moreover,
System.out.println("Abcd "+5+3);
Now,it starts from left side and it decides that it will add all of the things as string . thus output will be:
Abcd 53
Comment
For documentation , use
/**Documentation*/
and other documentation, we use
/* text*/
and
//text
Type conversion
Converting small data type to big data type is called Type casting.
This is how you can type cast:
byte-> short, int, long, float or double
short-> int, long, float or double
char -> int, long, float or double
int -> long, float or double
long -> float or double
float -> double
Again you can transfer from big data type to small data type:
short -> byte or char
char -> byte or short
int -> byte , short or char
long -> byte, short , char or int
float -> byte, short, char, int or long
double -> byte, short, char, int , long or float