Basic Programming In Java





In this tutorial, We are going to describe basic concept in programming language which will help beginners to learn programming as well as who are eager to learn java.

What Is Java?

Java is a computer programming language. It enables programmers to write computer instructions using English based commands, instead of having to write in numeric codes. It’s known as a “high-level” language because it can be read and written easily by humans. Like English, Java has a set of rules that determine how the instructions are written. These rules are known as syntax. Once a program has been written, the high-level instructions are translated into numeric codes that computers can understand and execute.
Actually, Java is an Object Oriented Programming language that enables the user to develop the platform independent application software .The java was propounded by James Gosling for Sun Microsystem Java help to develop the user friendly software which satisfy the user wants .Firstly, it was use in the TV remote to control the Television. Later on, it become popular and is widely use in the development of desktop application , Standalone application and Web Based application.

Simple example of java

classSimple{  
   public static void main(String args[]){  
      System.out.println("Hello Java");  
   }  
} 

What is Variable?

In programming, a variable is a value that can change, depending on conditions or on information passed to the program. Typically, a program consists of instructions that tell the computer what to do and data that the program uses when it is running. The data consists of constants or fixed values that never change and variable values (which are usually initialized to “0” or some default value because the actual values will be supplied by a program’s user).

 

What is DataTypes?

A data type in a programming language is a set of data with values having predefined characteristics. Examples of data types are: integer, floating point unit number, character, string, and pointer. Usually, a limited number of such data types come built into a language. The language usually specifies the range of values for a given data type, how the values are processed by the computer, and how they are stored.

Syntax of variable and data types:

int sum=2;

String name=”Sandeep”;

Here, sum and name are the variables and int, String are the simple data types where in the int sum we can assign the integer value and int string name we can assign the string value.

Features of OOP in java

Image result for OOP

  1. 1.Class
  2. 2.Data Encapsulation
  3. 3.Data Abstraction
  4. 4.Object And Instance
  5. 5.Inheritance
  6. 6.Polymorphism

OOP Features in brief

The programming in which data is logically represented in the form of a class and physically represented in the form an object is called as object oriented programming (OOP). OOP has the following important features.

Class :In OOP concept, it is must to create a class for representing data. Class contains variables for storing data and functions to specify various operations that can be performed on data. Class will not occupy any memory  space and hence it is only logical representation of data.
example of Class:
In this example, we created a Student class containing rollNo and name as a member variables and setRollNo and setName as a member functions.

class Student{
      //member variables
      private int rollNo;
      private String name;
      .................
      //member functions
      public void setRollNo(int roll){
           this.rollNo=roll;
      }
      
      public void setName(String name){
           this.name=name;
      }
}

Data Encapsulation :Within a class variables are used for storing data and functions to specify various operations that can be performed on data. This process of wrapping up of data and functions that operate on data as a single unit is called as data encapsulation.

Data Abstraction: Within a class if a member is declared as private, then that member cannot be accessed from outside the class. I.e. that member is hidden from rest of the program. This process of hiding the details of a class from rest of the program is called as data abstraction. Advantage of data abstraction is security.

Object And Instance: Class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, which is called as an object. When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance and its starting address will be stored in the object in stack memory area.

When an object is created without the keyword new, then memory will not be allocated in heap I.e. instance will not be created and object in the stack contains the value null. When an object contains null, then it is not possible to access the members of the class using that object.
example of Object:
In this example a student object created from the above class Student.

public class StudentRecord{
    public static void main(String[] args) {
        //student object is created from Student class
        Student student=new Student();
        student.setRollNo(10);
        student.setName("Asmin");
    }
}

Inheritance: Creating a new class from an existing class is called as inheritance. When a new class requires same members as an existing class, then instead of recreating those members the new class can be created from existing class, which is called as inheritance. Advantage of inheritance is reusability of the code. During inheritance, the class that is inherited is called as base class and the class that does the inheritance is called as derived class

Polymorphism: Polymorphism means having more than one form. Polymorphism can be achieved with the help of overloading and overriding concepts. Polymorphism is classified into compile time polymorphism and runtime polymorphism.

example of polymorphism:
In this example, simply a StudentData class is created which contains student information and from main method in ConstructorOverloading class, two object of StudentData is created which is called using default constructor and parameterized Constructor.

 
First Class
/* In this class default and parameterized constructor is performed. Data is set and get by using the getter and setter method.*/
package ConstructorOverloading;

 public class StudentData {
    private int studentId;
    private String studentName;
    private int studentAge;
    
    //default constructor
    StudentData(){
        studentId=01;
        studentName="Pratikshya";
        studentAge=21;
    }
    
    //parameterized constructior
    StudentData(int Id,String Name,int Age){
        studentId=Id;
        studentName=Name;
        studentAge=Age;
    }
    public int getStudentId() {
        return studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public int getStudentAge() {
        return studentAge;
    }

    
}    

/**Here we do some Constructor Overloading by using default constructor and parameterized constructor*/
Second Class
package ConstructorOverloading;

/*This is the main class we use object to call the constructor*/

public class ConstructorOverloading {
    public static void main(String[] args) {
        //this object creation would call default constructor;
        StudentData studentData=new StudentData();
        System.out.println("Student id is"+studentData.getStudentId());
        System.out.println("Student name is"+studentData.getStudentName());
        System.out.println("Student Age is "+studentData.getStudentAge());
        
        //this object creation would call parameterize
        StudentData studentData1=new StudentData(02,"Sabita",21);
        System.out.println("Student id is"+studentData1.getStudentId());
        System.out.println("Student Name is"+studentData1.getStudentName());
        System.out.println("Student Age is "+studentData1.getStudentAge());
    }
}

Now the given example shows features of OOPs:

This demo example show us the concept of OOP in java. In this example, we created three classes i.e MarkSheet which is used to store the marks in a subject, CalculateMarks which used to calculate grade from the given object of MarkSheet containing marks in a subject and MarksheetApplication which contains main function of our program.

First Class
package marksheetapplication;

/* In this class we store the marks of marksheet by using getter and setter method. */
 
public class MarkSheet {
private float Java;
private float operatingSystem;
private float Science;
private float Accounts;
private float math;

    public float getJava() {
        return Java;
    }

    public void setJava(float Java) {
        this.Java = Java;
    }

    public float getOperatingSystem() {
        return operatingSystem;
    }

    public void setOperatingSystem(float operatingSystem) {
        this.operatingSystem = operatingSystem;
    }

    public float getScience() {
        return Science;
    }

    public void setScience(float Science) {
        this.Science = Science;
    }

    public float getAccounts() {
        return Accounts;
    }

    public void setAccounts(float Accounts) {
        this.Accounts = Accounts;
    }

    public float getMath() {
        return math;
    }

    public void setMath(float math) {
        this.math = math;
    }
    }

Second Class
package marksheetapplication;

/*This class calculate the grade for the given marks.*/

Public class CalculateMarks {
    //we are using  the class MarkSheet as variable so we are making its private;
    private MarkSheet markSheet; 
    
    //it gets the marks and returns to marksheet object.
    public MarkSheet getMarkSheet() { 
        
        return markSheet;
    }

    public void setMarkSheet(MarkSheet markSheet) {
        this.markSheet = markSheet;
    }
    /*this block gets marks and calculate the grade according to the marksheet;
            */
    public String getGrade()
    {
       if((markSheet.getAccounts()<45)||(markSheet.getJava()<45)||(markSheet.getMath()<45)||(markSheet.getOperatingSystem()<45)||(markSheet.getScience()<45)) { return "F"; } else { float total= markSheet.getAccounts()+markSheet.getJava()+markSheet.getMath()+markSheet.getOperatingSystem()+markSheet.getScience(); float percentage=total/5; if(percentage>=90)
                   {
                       return "A";
                      
                   }
                   else if((percentage<90)&&(percentage>=85))
                   {
                       return "A-";
                   }
                   else if((percentage<85)&&(percentage>=80))
                   {
                       return "B+";
                   }
                   else if((percentage<80)&&(percentage>=75))
                   {
                       return "B";
                      
                   }
                   else if((percentage<75)&&(percentage>=70))
                   {
                       return "B-";
                       
                   }
                   else if((percentage<70)&&(percentage>=65))
                   {
                       return "C+";
                       
                   }
                   else if((percentage<65)&&(percentage>=60))
                   {
                       return "C";
                       
                   }
                   else if((percentage<60)&&(percentage>=55))
                   {
                       return "D+";
                       
                   }
                   else if((percentage<55)&&(percentage<=50))
                   {
                       return "D";
                       
                    }
                   else
                   {
                      return "D-";
                   }
                   
                       
                   }
       }
    }

Main Class
package marksheetapplication;

/**this class calls to other class to calculate and show output.*/

public class Marksheetapplication {
    
    public static void main(String[] args) {
        // making the marksheet object for taking data from the user
        MarkSheet markSheet=new MarkSheet();
        markSheet.setJava(62);
        markSheet.setMath(59);
        markSheet.setOperatingSystem(89);
        markSheet.setAccounts(59);
        markSheet.setScience(78);
        
        //this line call the class  calculateMarks
        CalculateMarks calculateMarks= new CalculateMarks();
        calculateMarks.setMarkSheet(markSheet);//calling setMarkSheet marksheet method
        
        //this line calculate the acutal grade
        String grade=calculateMarks.getGrade();
        System.out.println("Grade==>"+grade);
    }
}

Java SQL Connection





As we know, Database Management System is very important in today’s apps and software. It’s because it manages data efficiently and allows users to perform multiple tasks with ease. A database management system stores, organizes and manages a large amount of information within a single software application.

In today’s blog, I will demonstrate you a tutorial to connect with database in Java and perform CRUD operation.

First, you need a connection to your database so I prefer to make separate class for which can be called whenever you need it. That’s why make a class named Connector.java and paste the following code:

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class Connector {

    private static final String URL = "jdbc:mysql://localhost:3306/";
    private static final String LOGIN = "root";
    private static final String PASSWORD = "root";
    private static final String DBNAME = "dbname";
    private static Connector connector;
    private static Connection connection;

    private Connector() {
    }

    public synchronized static Connector getInstance() {
        if (connector == null) {
            connector = new Connector();
        }
        return connector;
    }

    public static Connection getConnection() {
        if (connection == null) {
            Connection c = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                c = DriverManager.getConnection(URL + DBNAME, LOGIN, PASSWORD);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            return c;
        }
        return connection;
    }
}

Now you can just create a object of Connection and call static method getConnection from Connector class use it to connect database and perform any operation something as follows where I have perform Insert operation:

 

try{
    Connection con=Connector.getConnection;
    String sqlToInsert = "INSERT INTO tableName (columnName1,columnName2,columnName3,columnName4) values (?,?,?,?)";
    Statement stmt = con.prepareStatement(sqlToInsertIntoCompany);
    stmt.setString(1, value1);
    stmt.setString(2, value2);
    stmt.setString(3, value3);
    stmt.setString(4, value4);
    stmt.executeUpdate();
}
catch(SQLException ex){
    Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
    if (con != null) {
        try {
            con.close();
        } catch (SQLException ex) {
              Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
       }
 
    }
 }

We can also perform above Insert operation like something down below:

 

try{
    Connection con=Connector.getConnection;
    String sqlToInsert = "INSERT INTO tableName (columnName1,columnName2,columnName3,columnName4) values ('"+value1+"','"+value2+"','"+value3+"','"+value4+"')";
    Statement stmt = con.prepareStatement(sqlToInsertIntoCompany);
    stmt.executeUpdate();
}
catch(SQLException ex){
    Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
    if (con != null) {
        try {
            con.close();
        } catch (SQLException ex) {
              Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
       }
 
    }
 }

Above both examples insert values into tableName table with columns columnName1,columnName2,columnName3,columnName4 but you need to remember that we need to perform Statement.executeUpdate only when we need to perform Insert,Delete and Update Operation. But if we need to execute SELECT operation then we need to perform execute query operation as follows:

 

try {
            Connection con = Connector.getConnection();
            String sql = "SELECT * FROM tableName ";

            Statement stmt = con.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getInt("columnName1");
                System.out.println(rs.getString("columnName2");
                System.out.println(rs.getString("columnName3");
                System.out.println(rs.getString("columnName4");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

        }

You can also write the above code as we did in INSERT operation by using prepareStatement and Statement.setString(); method. In the same way, you can perform UPDATE and DELETE operation.

Thanks for reading this blog,Hope this blog became helpful for you. If you have any comment or question regarding this blog , comments would be preferable. Happy Coding!

AD date to BS in Java





This blog is written in response to one of the requirement to convert the English date to BS.

We explored quite a bit in google to get the suitable jar for the same but couldn’t find so ought to create a converter.

The attached code / java file converts the given AD date to BS

Credit should also go to the PHP code available in internet which I converted in java only.

Limitations:

Converts date between: 2000-2090 BS

The converter has passed a limited testing so I suggest the user to test it thoroughly before using it for production.

Click here for Attachment

 

Java Blog





This Java blog will help you with some basic of Java programming.Reading this Java blog, you will be clear about the basic of Java.
Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. Java is intended to let application developers “write once, run anywhere” (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.

INTRODUCTION

Father of Java: James Ghosling

History:

James A. Gosling, O.C., Ph.D. (born May 19, 1955 near Calgary, Alberta, Canada) is a famous software developer, best known as the father of the Java programming language.
In 1977, James Gosling received a B.Sc in Computer Science from the University of Calgary. In 1983, he earned a Ph.D in Computer Science from Carnegie Mellon University, and his doctoral thesis was titled “The Algebraic Manipulation of Constraints”. While working towards his doctorate, he wrote a version of emacs (gosmacs), and before joining Sun Microsystems he built a multi-processor version of Unix[1] while at Carnegie Mellon University, as well as several compilers and mail systems.
Since 1984, Gosling has been with Sun Microsystems, and is generally known best as the founder of the Java programming language.
He is generally credited as the inventor of the Java programming language in 1991. He did the original design of Java and implemented its original compiler and virtual machine. For this achievement he was elected to the United States National Academy of Engineering. He has also made major contributions to several other software systems, such as NeWS and Gosling Emacs. He also cowrote the “bundle” program, a utility thoroughly detailed in Brian Kernighan and Rob Pike’s book The Unix Programming Environment.
JAVA and ORACLE
Principles

There were five primary goals in the creation of the Java language:[15]

Java must be “simple, object-oriented, and familiar”.
Java must be “robust and secure”.
Java must be “architecture-neutral and portable”.
Java must execute with “high performance”.
Java must be “interpreted, threaded, and dynamic”.
Versions

Main article: Java version history

Copyright © 2016 InfoxIT Portal. All rights reserved.
Seo wordpress plugin by www.seowizard.org.
Scroll To Top
Visit Us On FacebookVisit Us On Google PlusVisit Us On YoutubeCheck Our Feed