Beginner Program – Parameterized Constructor (Java)

public class BankAccount{
//Data members are called as states of object
private int accNumber;
private String accName;
private int accBalance;
//Parameterized Constructor
public BankAccount(int accNumber, String accName, int accBalance){
this.accNumber = accNumber;
this.accName = accName;
this.accBalance = accBalance;
}
public void display(){
//In-built functions usually begin with capital letter (Note 'S' below)
// + is used for concatenation
System.out.println("The account number is: " + accNumber);
System.out.println("The account name is: " + accName);
System.out.println("The account balance is: " + accBalance);
}
//Member functions are called behaviours of object
//boolean is return type of the function below
public boolean deposit(int amount){
if(amount<99){
return false;
}
this.accBalance += amount;
return true;
}
public int withdraw(int amt){
//If you have more than one condition and
//those conditions are independent of other conditions
//use || (or)
if(amt>accBalance || amt<0){
return 1;
}
this.accBalance -= amt;
return 0;
}
//below defines the entry point of your program in java
public static void main(String [] args){
System.out.println("Hello Java\n");
/* Note:
* 1. Memory is allocated on heap.
* 2. b1 is a reference of type BankAccount
*/
BankAccount b1 = new BankAccount(101, "Pratik", 1000);
//Member functions can only be called through reference
b1.display();
}
}

Output:
Hello Java
The account number is: 101
The account name is: Pratik
The account balance is: 1000
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Arrays snippet w/ string illustration (Java)
public class Collection {
public static void main( String [] args){
int [] arr, arr1; //int arr []; is also allowed but not preferred
arr = new int[5];
arr1 = new int[] {10, 12, 33,43};
for(int i : arr){
System.out.println(i);
}
System.out.println("-------------------------");
for(int i = 0; i < arr1.length ; i++){
System.out.println(arr1[i]);
}
System.out.println("-------------------------");
int [] [] arr3 = new int[3][];
arr3[0] = new int[2];
arr3[1] = new int[3];
arr3[2] = new int[2];
for(int i = 0; i < arr3.length ; i++){
for(int j=0;j<arr3[i].length;j++){
System.out.printf(arr3[i][j] + " "); //printf so that on each loop new line is not automatically generated
}
System.out.println();
}
System.out.println("-------------------------");
for(String str : args){ //This is for command line arguement. The class name is not counted as arguement in case of java but in C++ it is counted
System.out.println(str);
}
System.out.println("-------------------------");
String str, str1;
str = "Pratik";
System.out.println(str);
str1 = "Professional";
if(str.contains("a")){
System.out.println("The String "+str+" contains 'a' at location " + str.lastIndexOf("a"));
}
if(str.equals(str1)){
System.out.println("Both Strings are equal \n");
}
else
System.out.println("Both Strings are not equal. \n");
}
}
Output:
Pratik
The String Pratik contains ‘a’ at location 2
Both Strings are not equal.
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
All about static snippet (Java)
import java.util.Random;
public class Emp {
//To get a unique employee id i.e. it doesn't starts with 0
static private int empId;
private int actualEmpid;
private String empName;
private int empSal;
static private String compName;
static private int totalEmp = 0;
//Java has 3 things: Static data, static function and static block
static{
//This is executed just after creation of object. After object creation, static datas are created n then static block.
System.out.println("Static block created...");
Random random = new Random();
//Random number in the range 0-1000
empId = random.nextInt( 1000 );
}
Emp(){ //Constructor
//Post increment so that it is assigned first and then incremented
this.actualEmpid = empId++;
Emp.totalEmp++;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpSal() {
return empSal;
}
public void setEmpSal(int empSal) {
this.empSal = empSal;
}
public static String getCompName() {
return compName;
}
public static void setCompName(String compName) {
Emp.compName = compName;
}
public static int getTotalEmp() {
return totalEmp;
}
public static void setTotalEmp(int totalEmp) {
Emp.totalEmp = totalEmp;
}
public void display(){
System.out.println("Emp. ID : " + this.actualEmpid + " Name: " + empName + " Emp. Salary: " + empSal + " Company Name: " + Emp.compName);
}
public static void main(String [] args){
//because of static we can do this before creation of any object.
Emp.setCompName("Rambo");
Emp e1 = new Emp();
e1.setEmpName("Pratik");
e1.setEmpSal(5000);
Emp e2 = new Emp();
e2.setEmpName("Rohit");
e2.setEmpSal(6000);
e1.display();
e2.display();
System.out.println("The total number of employees registered are: " + Emp.getTotalEmp());
}
}
Output:
Static block created…
Emp. ID : 905 Name: Pratik Emp. Salary: 5000 Company Name: Rambo
Emp. ID : 906 Name: Rohit Emp. Salary: 6000 Company Name: Rambo
The total number of employees registered are: 2
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Exception Handling snippet – try, catch, finally (Java)
public class Main {
//Keywords : Try, catch, finally, throw, throws
public static void main(String[] args) {
//Throwable class is base for Class of Errors and
//Class of Exception. Then in Exception class you have specific classes
//like arrayoutofbound i.e. they are derived classes
try{
int a = 10;
int b = 0;
int c = a/b; //Code will crash here so further statements won't be executed
System.out.println(c);
int arr [] = {1,2,3,4};
System.out.println(arr[1]);
System.out.println(arr[4]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("You are crossing the limit where no value exists\n\n");
}
catch (ArithmeticException e) {
System.out.println("Aw, sorry you can't divide by 0. Please contact Arryabhatta for more details :) \n\n");
}
catch(Exception e){ //This general block should always be last after specific catch blocks
e.printStackTrace();
}
finally{
System.out.println("Program crashed but I still execute. #ThugLife");
}
}
}
Output:
Aw, sorry you can’t divide by 0. Please contact Arryabhatta for more details 🙂
Program crashed but I still execute. #ThugLife
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Exception Handling snippet – throw(s) (Java)
//******************* Employee.java *******************
public class Employee {
private int ID;
private int Salary;
private String Name;
public Employee(int ID, int Salary, String Name) throws NegativeSalaryException {
this.ID = ID;
this.Name = Name;
if(Salary<0)
throw new NegativeSalaryException(Salary, "You have entered negative salary");
this.Salary = Salary;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Name: "+ Name + " ID: "+ ID + " Salary: "+ Salary;
}
}
//******************* Main.java *******************
public class Main {
public static void main(String[] args) throws NegativeSalaryException {
Employee employee = new Employee(111, -1000, "Pratik");
System.out.println(employee);
}
}
//******************* NegativeSalaryException.java *******************
public class NegativeSalaryException extends Exception {
private int sal;
private String exMsg;
public NegativeSalaryException(int sal, String exMsg) {
this.sal = sal;
this.exMsg = exMsg;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "\n Salary: " + sal + "\n ExMsg: " + exMsg;
}
}
Output:
Exception in thread “main”
Salary: -1000
ExMsg: You have entered negative salary
at Employee.<init>(Employee.java:12)
at Main.main(Main.java:6)
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Inheritance snippet – Vehicle (Java)
//******************* Vehicle.java *******************
public class Vehicle {
private String PNo;
private int CNo;
Vehicle(){
System.out.println("Vehicle() ");
PNo = "NA";
CNo = 0;
}
Vehicle(String PNo, int CNo){
System.out.println("Vehicle( String, int ) ");
this.PNo = PNo;
this.CNo = CNo;
}
public String getPNo(){
return this.PNo;
}
public void setPNo(String PNo){
this.PNo = PNo;
}
public int getCNo(){
return this.CNo;
}
public void setCNo(int CNo){
this.CNo = CNo;
}
}
//******************* Car.java *******************
public class Car extends Vehicle{
private int type;
private String color;
Car(){
System.out.println(" Car() ");
type = 0;
color = "NA";
}
Car(String PNo, int CNo, String color , int type){
//This should be the first statement if we are overriding the default constructor to be called by base class.
super( PNo, CNo);
System.out.println("Car( String, int, String, int )");
//setPNo("MH12 1213"); //By doing this we are overwriting the default values of 0 which is being set by the default constructor of vehicle. So extra CPU cycles are invested
//setCNo(12334);
this.type = 2;
this.color = "Black";
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void display(){
//System.out.println("PNo : " + PNo); This is invalid as it breaks encapsulation
System.out.println("PNo : " + getPNo() );
System.out.println("CNo : " + getCNo() );
System.out.println("Color : " + color );
System.out.println("Type : " + type );
}
}
//******************* Main.java *******************
public class Main {
public static void main( String [] args){
Car c1 = new Car("MH12 233", 23445, "Red", 1);
c1.display();
/* Commented since we are using parameterized constructor
c1.setPNo("MH12J3552");
c1.setCNo(213432);
c1.setColor("Red");
c1.setType(2); //2 means diesel lol
*/
//Vehicle v1 = new Vehicle(); //There is no connection with c1. It is a different object
//v1.setPNo("MH21");
//v1.setCNo(9999);
//Commented since we have display
//print(c1); //since it is static we can directly call. Note: c1 is passed and not v1. We cannot pass v1. If it were Vehicle v in function's formal parameters. We could have passed c1 and v1 in print()
System.out.println("------------------------");
//c1.display();
}
public static void print( Car c ){
System.out.println("PNo : " + c.getPNo() );
System.out.println("CNo : " + c.getCNo());
}
}
Output:
Vehicle( String, int )
Car( String, int, String, int )
PNo : MH12 233
CNo : 23445
Color : Black
Type : 2
————————
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Inheritance snippet – Shape (Java)
//******************* Shape.java *******************
public class Shape {
private int x;
private int y;
private String color;
private String shape;
Shape(){ //This is needed to be defined since we are going to work with inheritance
x = 0; y = 0; color = " "; shape = "polygon";
}
Shape(int x, int y, String color, String shape){
this.x = x;
this.y = y;
this.color = color;
this.shape = shape;
}
public int getXCoordinate(){
return this.x;
}
public void setXCoordinate(int x){
this.x = x;
}
public int getYCoordinate(){
return this.y;
}
public void setYCoordinate(int y){
this.y = y;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int Area(){
return 0;
}
public void display(){
System.out.println("The x coordinate is : " + x);
System.out.println("The y coordinate is : " + y);
System.out.println("The color of " + shape + " is : " + color);
}
public void printinfo( Shape s ){
System.out.println("The area of " + s.shape + " is : " + s.Area());
}
}
//******************* Rectangle.java *******************
public class Rectangle extends Shape{
private int length;
private int breadth;
Rectangle(){
}
Rectangle(int x, int y, String color, String shape, int length, int breadth){
super(x,y,color, shape);
this.length = length;
this.breadth = breadth;
}
public int Area(){
return length*breadth;
}
}
//******************* Square.java *******************
public class Square extends Shape{
private int side;
Square(int side){
this.side = side;
}
public int Area(){
return side*side;
}
}
//******************* Circle.java *******************
public class Circle extends Shape{
private int radius;
final private double pie = 3.14;
Circle(int x, int y, String color, String shape, int radius){
super(x, y, color, shape);
this.radius = radius;
}
public int Area(){
return (int)(pie*(radius * radius));
}
}
//******************* Main.java *******************
public class Main {
public static void main( String [] args){
Shape s = new Shape(0, 0, "Black", "Polygon");
Rectangle r = new Rectangle(1, 1, "Blue", "Rectangle", 3, 5);
Circle c = new Circle(2, 2, "Orange", "Circle" , 5);
s.display();
System.out.println("------------------------");
r.display();
s.printinfo(r);
System.out.println("------------------------");
c.display();
s.printinfo(c);
System.out.println("------------------------");
}
}
Output:
The x coordinate is : 0
The y coordinate is : 0
The color of Polygon is : Black
————————
The x coordinate is : 1
The y coordinate is : 1
The color of Rectangle is : Blue
The area of Rectangle is : 15
————————
The x coordinate is : 2
The y coordinate is : 2
The color of Circle is : Orange
The area of Circle is : 78
————————
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Singleton snippet (Java)
public class singleton {
private static singleton obj;
private singleton(){
System.out.println("Constructor is called only once.");
}
public static singleton getInstance(){
if(obj == null){
obj = new singleton();
}
return obj;
}
public int add(int i, int j){
return (i + j);
}
public int sub(int i, int j){
return (i-j);
}
public static void main( String [] args){
singleton obj1 = singleton.getInstance();
singleton obj2 = singleton.getInstance();
singleton.getInstance();
singleton.getInstance();
singleton.getInstance();
// 'n' number of object creation won't call constructor 'n' times. This is singleton feature.
System.out.println(singleton.getInstance().add(5, 6)); //it is object.function() call
}
}
Output:
Constructor is called only once.
11
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Run Time Type Information snippet (RTTI – Java)

//************************* Manager.java *************************
public class Manager extends Employee {
public Manager(int empId, String empName) {
super(empId, empName);
}
public void salary(){}
public void bonus(){}
}
//************************* Employee.java *************************
public class Employee {
//Run Time Type Info
int empId;
String empName;
public Employee(int empId, String empName) {
this.empId = empId;
this.empName = empName;
}
public void fun(){}
public void test(){}
@Override
public String toString() {
return "ID: " + empId + " Employee Name: "+empName ;
}
}
//************************* Main.java *************************
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
Employee employee1 = new Employee(111, "Patrick");
System.out.println(employee1);
Employee employee2 = new Employee(112, "Pratik");
System.out.println(employee2);
//RTTI
Class myClass; //This is provided by java
myClass = employee1.getClass(); //This stores the reference's classname
System.out.println("Class Name: " + myClass.getClass().getName());
System.out.println("--------------------------");
System.out.println("Now we change reference of employee");
System.out.println("--------------------------");
Employee employee = new Manager(113, "Code");
myClass = employee.getClass();
System.out.println("Class Name: " + myClass.getClass().getName());
System.out.println("Super Class Name: " + myClass.getSuperclass().getName());
//Now for printing methods name
Method[] methods = employee.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println("Method Name: " + methods[i].getName());
}
}
}
Output:
ID: 111 Employee Name: Patrick
ID: 112 Employee Name: Pratik
Class Name: java.lang.Class
————————–
Now we change reference of employee
————————–
Class Name: java.lang.Class
Super Class Name: Employee
Method Name: salary
Method Name: bonus
Method Name: toString
Method Name: test
Method Name: fun
Method Name: wait
Method Name: wait
Method Name: wait
Method Name: equals
Method Name: hashCode
Method Name: getClass
Method Name: notify
Method Name: notifyAll
View Article Page
Download
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.
Close