Search Logic Blocks

Monday, December 30, 2019

Java: What is package?

In previous posts, I had used package java.util, so I thought it is very necessary to explain this topic in detail. Packages are very important part of java. I mentioned earlier we import packages to reuse classes, fields or methods from Java API or other sources.

A package is a group of related classes, interfaces, enumerations, annotations etc. and is used in order to prevent name conflicts and easy access to similar and related types (classes, interfaces, enumerations and annotations). We can also create our own packages.

To create a package, the package declaration statement should be the first line of the source code file and should be included in every source file in the package. Package name is same as the folder name in which all the compiled class files are stored. Below, I have created a package named as cards, which has 4 classes in package cards - spade, club, diamond and heart -
package cards; // Class Spade

public class spade {
// Class Spade fields and methods
}
package cards; // Class Club

public class club {
// Class Club fields and methods
}
package cards; // Class Diamond

public class diamond {
// Class Diamond fields and methods
}
package cards; // Class Heart

public class heart {
// Class Heart fields and methods
}
To access the package cards, the following import statement should be in the first line after package statement (if there is any package) - 
import cards.*;

or

import cards.spade // If you want to use particular class
Few examples of Java API packages commonly used, given below -
  • java.lang
  • java.util
  • java.awt
  • java.io
  • java.time
  • java.text
  • java.math

NOTE: We will learn more about other packages as needed.

Sunday, December 29, 2019

Java: Write a program to get input of type double and print the same.

Class GetInput (GetInput.java)
import java.util.Scanner;

public class GetInput {
public static void main(String args[]) {
// Creates an object of Scanner class by calling Constructor method and
// passed System.in (InputStream class object) as an argument
Scanner sc = new Scanner(System.in);

// Asks to user to enter an integer number
System.out.print("Enter the double number: ");

// Prompts for user to enter the number and wait till user press enter button
// The number is assigned to variable i
var i = sc.nextDouble(); // Or double i = sc.nextDouble();

// Prints the number user entered
System.out.println("You entered number " + i);
}

} 

Note: All code can be found at Github link.

Java: Write your first java program and print your name on the console.

Suppose your name is John Smith - 

Class myName (myName.java)

public class myName {
public static void main(String args[]) {
System.out.println("John Smith");
}
}
Note: All code can be found at Github link.

Friday, December 27, 2019

Java: How to get input from console

In the last post, we learned how we write a string to console using System.out.println() method. Sometimes, we need input from the user and then process the details (calculations, string manipulation, storing and retrieving data etc.) and then the program generates the output data as required. Here is an example which gets an integer input from the user and prints the same number  -

Class GetInput (GetInput.java)
import java.util.Scanner;

public class GetInput {
public static void main(String args[]) {
// Creates an object of Scanner class by calling Constructor method and
// passed System.in (InputStream class object) as an argument
Scanner sc = new Scanner(System.in);

// Asks to user to enter an integer number
System.out.print("Enter the integer number: ");

// Prompts for user to enter the number and wait till user press enter button
// The number is assigned to variable i
var i = sc.nextInt(); // Or int i = sc.nextInt();

// Prints the number user entered
System.out.println("You entered number " + i);
}
}
In the above example, we use the import statement as the first statement. When we want to reuse any classes, fields or methods from Java API or other sources, we need to have import statement as first statement in the program to include the whole package or specific class. Till now, we have used only System class, which is defined in the java.lang package. We don't need to import java.lang package in any java code as it is included by default. We can use all java.lang package classes, methods, interfaces and fields without importing the package. In the above program, we need to import class Scanner from package java.util to get the user input from the console -
import java.util.Scanner;
Scanner Class
Scanner class has a final class imported from the package java.util, to get the input from the different sources. Final class means you can not inherit (subclass) from the Scanner class. Scanner is used to get inputs from various sources, like the input stream, file, buffered reader and breaks input into tokens by using the delimiter. Scanner uses white space (white space characters include blanks, tabs and line terminators) as a default delimiter, but there are methods to set the different delimiter. (We will discuss later more about delimiters.) Following statement creates an object of Scanner - 
Scanner sc = new Scanner(System.in);
In Java, mostly an object is created by calling the constructor method from the class. Constructor method name is the same as the class name - in this case, Scanner. We passed System.in (a field in class System of type InputStream) as an argument to the constructor, which represents console / terminal.
System.out.print("Enter the integer number: ");
var i = sc.nextInt(); // Or int i = sc.nextInt();
Here, the program asks the user to enter an integer number by calling the Scanner's method nextInt(), which prompts the user to enter an integer number and assigns the number to variable i. We can use var or int keywords to declare the integer variables.
System.out.println("You entered number " + i);
Finally, we print the same entered number to the console using the method System.out.println(). Here we use a fixed text "You entered number" and then use the value of the variable i. We use the + sign here to make it one string. This is called string concatenation. Here is the output - 

Enter the integer number: 8
You entered number 8

NOTE: We will talk later more about constructors, packages, inheritance, I/O Streams in detail. We will also learn more about Scanner class by using more advanced methods to get specific input and how to make sure to validate the input data.

Code can be found here at Github link.

Exercise: Write a program to get input of type Double and print the same.

Wednesday, December 25, 2019

Simple Program in Java

In Java, we start writing the programs by creating a new class starting with keyword class and any valid class name. Class names should be mixed case with first letter capitalized (recommended but not necessary). The program runs starting with the class having the main() method (which is the entry point for the program). 

We save the code in a plain text file named as the same name as the class name ending with .java extension. When the source file is compiled, a byte code file is generated ending with extension .class. The java application launcher (java) runs the same application .class on JVM (Java Virtual Machine) on different platforms (Windows, Unix / Linux, MacOS etc.) to convert the class file into specific machine instructions. (We will discuss later more about JVM.) Standard program structure in java programs is given below - 
public class [Class Name]{
// Define some variables
public static void main(String args[]) {
// Entry code
}
// Define some methods
}
The main() method is always the entry point in any java application. Its signature is always the same as given below - 
public static void main(String args[])
public is access modifier, and it means that the main method can be accessed from anywhere. static means, that there is no need to create an object to call the method and run the application. void keyword tells the system that main() method returns nothing. args[] is the String array, which represents the command line arguments passed. (Command line arguments are passed through command prompt on the terminal.)

Welcome Program
Let's start our first program. Mostly all the beginners write their first program by writing "Hello World" program. I will start the program by welcoming all to my Logic Blocks blog. "Welcome to Logic Blocks!!"

Class Welcome (Welcome.java)
public class Welcome 
{
public static void main(String args[]) {
System.out.println("Welcome to Logic Blocks!!");
}
}
Above code has two components - class definition and the main() method. Class definition begins with the keywords public (access modifier - optional) class (mandatory). Class is named as Welcome and it has only one method main() method. main() method has only one statement, which instructs the computer to print the Welcome message. We save the source file as Welcome.java. If you are using the command prompt to compile the source file, use the javac compiler command as below -

javac Welcome.java

When the file Welcome.java is compiled, java programming language compiler (javac compiler) generates a byte code class file named as Welcome.class. To run the class file, you have to give the command below -

java Welcome

And it will print the following message -

Welcome to Logic Blocks!!

Code can be found at Github link.

NOTE: So, now we are familiar of java program structure, and ready to learn more about this powerful language, and how we can use in our daily life to solve complex problems. As I already mentioned earlier, that this blog is not any kind of tutorial. We will focus more on the concepts and to create logic for solving the problems. Gradually, we will discuss more advanced topics.

Exercise: Install java (jdk) from the Oracle website. The instructions can be found in the Java tutorials mentioned in the post Java References. Write your first java program and print your name on the console / terminal.

Monday, December 23, 2019

Java Reference

So, I started this blog with explanation - What is Object Oriented Programming and What is Java language. I am going to explain the Java concepts in detail, and how can a programmer use Java's built-in classes and packages to write their own custom classes to solve complex problems. To start the programming in Java, few useful links / resources are given below - 

Java Tutorial Websites

https://www.tutorialspoint.com/java/index.htm

https://www.geeksforgeeks.org/java-tutorials/

https://docs.oracle.com/javase/tutorial/

http://programmingbydoing.com

https://examples.javacodegeeks.com

Java Books

Head First Java

Beginning Programming with Java For Dummies

Java Programming Basics for Absolute Beginners

Java: A Beginner's Guide

Core Java Volume I - Fundamentals

Friday, December 20, 2019

Why Logic Blocks?

What is logic?
When I started learning programming 20 years back, I learnt different languages FORTRAN, COBOL, BASIC which were used for specific purposes and are now rarely used. And also learnt other languages, which are still used, like C, C++ and then Java. After learning so many languages, I understood that you can learn any language easily when you understood the concepts. But the main problem is how to implement those concepts. How to utilize those concepts to solve any problem?

So, logic is to divide your problem into small small steps and get your desired result. If you know, what a particular code or method is doing it will be easier to debug complex problems too. You will be able to understand code written by other developers too. And  you can only learn it through practicing and developing logical and analytical skills. There are few strategies to analyze and solve your problem - 

Suppose we have a small stationary shop and a student comes and buys some stationary items like pencils, erasers, notebook etc. - 
  • Make organized lists / chart / diagram (flow chart) - 
    • List all your information already available to you (Data) - We as shopper already know what is the price for each item.
    • List what is the targeted result, what are the requirements (output) - We need to calculate total amount of money the student has to pay.
    • List what do you require from user (input) - We have to ask student what item and how many he needs. 
    • List the steps how will you use input and data to get the output - Do all the calculations required
    • Check if there are some conditions and which one is suitable (if, if else, switch case etc.) - 
    • Check the pattern in steps, how many steps are you repeating for different data - so do we need loops (for, foreach, while, do etc.) or creating methods for reuse - We have to repeat multiplication for each item - price * item quantity.
    • List what can go wrong - data mismatch (wrong input), calculation (division by 0) etc.

So, break down a complex problem into small problems and write down steps for each problem. Start writing small small programs and practice for improving your logical and analytical skills.

NOTE: My main aim for this blog is to make people, who have just started programming, to make them to understand logic for each program. Nowadays, you can get solution for each problem, but programming is much more than cut, copy and paste. Logical thinking is must for each programmer.

Wednesday, December 18, 2019

Java

Why Java?
Java is a high level and object oriented programming language. Java programming language was developed originally by James Gosling at Sun Microsytems in 1995. Today, Java is the foundation of almost every type of application globally like, video games, mobile and web applications, enterprise software, networked applications. Java is a robust and secure language as it has following few advantages -
  • Object Oriented - My previous post explains what is an Object Oriented Programming. In Java, everything is an object. Java is class based, classes contain data (variables) and member methods / functions or procedures. Objects are the instances of classes. Java provides a library of built-in / ready-made classes and a developer can create their own custom classes and can reuse readily available classes through Java library.
  • Platform independent - Java runs almost on every hardware platform, as java programs are compiled into byte code and are run on Java Virtual Machine (JVM). JVM is an engine that provides runtime environment to run java code. It converts Java byte code into machine language.
  • Architecture neutral and portable - Java doesn't depend on any platform or architecture how the information is stored, so it's implementation is easy and can be run its programs on any platform using JVM (Java Virtual Machine). 
  • Interpreted - Java compiler compiles the java source program and generates the platform-independent byte code, and JVM interprets the byte code into computer instructions for any machine.
  • High Performance - Java enables high performance with use of JIT (Just In Time) compiler. JIT compiler is a program on JVM, which is used to interpret byte code into computer instructions.
  • Distributed - Java works on all kind of networks including internet.

Java is much more than I mentioned in above points. But as the beginner, we can learn gradually how Java is so much robust and powerful language, and is used in mostly all areas.

NOTE: Java is vast language and supports several features. I don't want to overwhelm the beginners who just started to learn. I will cover all the concepts in coming posts one by one.

Sun Microsystems - SUN (Stanford University Network) Microsystems was founded on 24 Feb, 1982 by Scott McNealy, Vinod Khosla, Andy Bechtolsheim and Bill Joy. The company was acquired by Oracle in 2010.

Byte code - Java programs are compiled into the byte code, which is not dependent on the machine / hardware-platform. Same byte code can be run on any hardware platform (MacOS, Windows, Unix, Linux etc.) using its software-platform JVM (Java Virtual Machine).

JVM (Java Virtual Machine) - JVM is a software platform specific for each hardware platform, converts the byte code into the machine dependent instructions.

JIT (Just In Time) compiler - JIT compiler is a feature of JVM (Java Virtual Machine), when it compiles the methods using dynamic runtime information in the runtime environment.

Monday, December 16, 2019

Object Oriented Programming

What is an Object?
An object is any thing which can be categorized, and described by its characteristics and its style of act and react depending on situations. In real life, we see a lot of living things and non-living things around us. Let's talk about few examples -
  • Dog - Dog is an animal. So, we categorize dog as an animal, but dogs are different kinds. We can further categorize them like Beagle, Boxer, Golden Retriever etc. Each kind of dog has its own features like - size, weight, color, coat, and its activity style like - barking, running, licking, playing etc. 
  • Employee - An employee is a person with name, age, height, weight, qualifications, designation, department, salary, perks etc. Depending on the designation, employee has to work, manage the team, report to boss and complete his tasks. 
  • Company - A company is an organization with name, type, logo, no of employees, revenue, etc. And it works depending on its type - like if it is software company, it mainly works on software projects. But if it is a pharmaceutical company, it can manufacture different drugs. 
  • Numbers - Who doesn't know about numbers. We daily deal with numbers. Numbers are several kind of numbers - whole numbers, even and odd numbers, prime numbers, composite numbers. We can add, subtract, multiply, divide, square, square root, cube, factorial, fraction them. Numbers are used in different calculations. 
  • Shapes - Shapes can be categorized into any polygon with more than 2 sides and closed on all corners or any round shape like circle, sphere, oval, parabola. There are different methods to calculate their area, perimeter, circumference etc.

What is a class?
When we categorized objects with some common features - that is called classification. A class is a prototype which includes common features and behavior. For example -
  • Dog is an animal, so dog is an instance of class animal. Dog itself is also a class but all dogs are instance of this class and have common features and behaviors.
  • Employee is a class and every employee is an instance of this class. Company can be a separate class itself, and Employee class can be part of the class Company.
  • Likewise, we can have different classes for Numbers and Shapes, and they can have their own methods.

Object Oriented Programming
So, when we say Object Oriented Programming, we are coding with different classes and their objects. In old languages like FORTRAN, COBOL, BASIC and C etc., code was written in procedural and structured way. The code was executed from top to bottom. 

But in object oriented approach, a computer program is written by using class definition (prototype) and creating an instance of the class, object. The class definition will have variables as data (features / properties) and methods as behaviors (any kind of instructions). Examples of object oriented languages are C++, Java, Python etc.

NOTE: This is just an introduction to start to explain the concepts in an easy way. I tried to write it in very simple language and tried to use very less technical terms. In coming posts, I am going to explain more basic concepts with examples.