Sunday, July 19, 2015

Java Synatax and Stuff...

When we consider a Java program it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.
  • Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
  • Class - A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support.
  • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

First Java Program:

Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {

   /* This is my first java program.  
    * This will print 'Hello World' as the output
    */

    public static void main(String []args) {
       System.out.println("Hello World"); // prints Hello World
    }
} 
Let's look at how to save the file, compile and run the program. Please follow the steps given below:
  • Open notepad and add the code as above.
  • Save the file as: MyFirstJavaProgram.java.
  • Open a command prompt window and go o the directory where you saved the class. Assume it's C:\.
  • Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
  • Now, type ' java MyFirstJavaProgram ' to run your program.
  • You will be able to see ' Hello World ' printed on the window.
C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram 
Hello World

Basic Syntax:

About Java programs, it is very important to keep in mind the following points.
  • Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
  • Class Names - For all class names the first letter should be in Upper Case.

    If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.

    Example class MyFirstJavaClass
  • Method Names - All method names should start with a Lower Case letter.

    If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.

    Example public void myMethodName()
  • Program File Name - Name of the program file should exactly match the class name.

    When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile).

    Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
  • public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program..

Java Identifiers:

All Java components require names. Names used for classes, variables and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
  • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
  • After the first character identifiers can have any combination of characters.
  • A key word cannot be used as an identifier.
  • Most importantly identifiers are case sensitive.
  • Examples of legal identifiers: age, $salary, _value, __1_value
  • Examples of illegal identifiers: 123abc, -salary

Java Modifiers:

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:
  • Access Modifiers: default, public , protected, private
  • Non-access Modifiers: final, abstract, strictfp
We will be looking into more details about modifiers in the next section.

Java Variables:

We would see following type of variables in Java:
  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non-static variables)

Java Arrays:

Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

Java Enums:

Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium and large. This would make sure that it would not allow anyone to order any size other than the small, medium or large.

Example:

class FreshJuice {

   enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
   FreshJuiceSize size;
}

public class FreshJuiceTest {

   public static void main(String args[]){
      FreshJuice juice = new FreshJuice();
      juice.size = FreshJuice. FreshJuiceSize.MEDIUM ;
      System.out.println("Size: " + juice.size);
   }
}
Above example will produce the following result:
Size: MEDIUM
Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

Java Keywords:

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while

Comments in Java

Java supports single-line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram{

   /* This is my first java program.
    * This will print 'Hello World' as the output
    * This is an example of multi-line comments.
    */

    public static void main(String []args){
       // This is an example of single line comment
       /* This is also an example of single line comment. */
       System.out.println("Hello World"); 
    }
} 

Using Blank Lines:

A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it.

Inheritance:

In Java, classes can be derived from classes. Basically if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario the existing class is called the superclass and the derived class is called the subclass.

Interfaces:

In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.
An interface defines the methods, a deriving class(subclass) should use. But the implementation of the methods is totally up to the subclass.

First week of Learning Java ended with Null(void)

Okay So another week and still I am nowhere near to Android Development?
What exactly is the best way to learn Java? How to go about it? Infact What is the best way to learn any language for that matter?

I googled these questions and there were some good anwers and this one is what I really liked on Quora-

Read Faizan Ahemad's answer to How can I learn Java? on Quora

Now he did explain pretty much but still where am I lacking?

I did try Java in a Nutshell and Head First Java even Java for Dummies. But where should I stop? Anyway I will try yet again and let's see how it goes...


Thursday, July 9, 2015

How to set up your PC for Java?

Java uses JDK ie Java Development Kit for the development purposes. So you need to install JDK in your PC first; You can install the same from here.

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
  • JDK contents

The JDK has as its primary components a collection of programming tools, including:
  • appletviewer – this tool can be used to run and debug Java applets without a web browser
  • apt – the annotation-processing tool
  • extcheck – a utility which can detect JAR-file conflicts
  • idlj – the IDL-to-Java compiler. This utility generates Java bindings from a given Java IDL file.
  • jabswitch – the Java Access Bridge. Exposes assistive technologies on Microsoft Windows systems.
  • java – the loader for Java applications. This tool is an interpreter and can interpret the class files generated by the javac compiler. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new java loader.
  • javac – the Java compiler, which converts source code into Java bytecode
  • javadoc – the documentation generator, which automatically generates documentation from source code comments
  • jar – the archiver, which packages related class libraries into a single JAR file. This tool also helps manage JAR files.
  • javafxpackager – tool to package and sign JavaFX applications
  • jarsigner – the jar signing and verification tool
  • javah – the C header and stub generator, used to write native methods
  • javap – the class file disassembler
  • javaws – the Java Web Start launcher for JNLP applications
  • JConsole – Java Monitoring and Management Console
  • jdb – the debugger
  • jhat – Java Heap Analysis Tool (experimental)
  • jinfo – This utility gets configuration information from a running Java process or crash dump. (experimental)
  • jmap – This utility outputs the memory map for Java and can print shared object memory maps or heap memory details of a given process or core dump. (experimental)
  • jmc – Java Mission Control
  • jps – Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java Virtual Machines (JVMs) on the target system. (experimental)
  • jrunscript – Java command-line script shell.
  • jstack – utility which prints Java stack traces of Java threads (experimental)
  • jstat – Java Virtual Machine statistics monitoring tool (experimental)
  • jstatd – jstat daemon (experimental)
  • keytool – tool for manipulating the keystore
  • pack200 – JAR compression tool
  • policytool – the policy creation and management tool, which can determine policy for a Java runtime, specifying which permissions are available for code from various sources
  • VisualVM – visual tool integrating several command-line JDK tools and lightweight[clarification needed] performance and memory profiling capabilities
  • wsimport – generates portable JAX-WS artifacts for invoking a web service.
  • xjc – Part of the Java API for XML Binding (JAXB) API. It accepts an XML schema and generates Java classes.
Experimental tools may not be available in future versions of the JDK.
The JDK also comes with a complete Java Runtime Environment, usually called a private runtime, due to the fact that it is separated from the "regular" JRE and has extra contents. It consists of a Java Virtual Machine and all of the class libraries present in the production environment, as well as additional libraries only useful to developers, such as the internationalization libraries and the IDL libraries.
Copies of the JDK also include a wide selection of example programs demonstrating the use of almost all portions of the Java API.


Rest you can read on the Wikipedia page -


https://en.wikipedia.org/wiki/Java_Development_Kit

Apart from this you might need an IDE like Eclipse,Netbeans or BlueJ but for now we are good to go with the Notepad app on your PC.


So lets start the journey...


Tuesday, July 7, 2015

Lets get started with Java Part-1

Okay so you have ignited your engines and are all set to take off in the exciting world of Java & Android Development.

But how to go about it ? If you are a beginner lile me then I think Head First with Java and How to think like a Computer Scientist are two books that are compact and covers almost everything you need to know.


You can found both these bools easily on the internet. Here are the links... I will try to cover these books in a span of 2 weeks. Yes it is rash and fast but we simply cant afford to lose anypre time right?..


Lets try something challanging..In the next post I will arrange the topics into Days and for each day we will cover the topics that I have listed...and also solve some Questions.

There are some other great books that you can check




But due to paucity of time we dont have time to get into something so deep that we end up digging up gold. Plus they can get boring over time. And don't worry we will cover almost everything. You need to know about Java with super sonic speed.

Welcome to Java with Sarthak Bhatia!

Hello!
Welcome to my Java Blog...

Its been a while now...infact a month almost and I have been postponing things..

On my head somewhere I have some amazing billion dollar ideas (not kidding!) to make Android apps rather native apps but I don't know how to actually make them.

I know I have to start with Java and I was doing just that but then I think I am just lazy. Every time I start , I mostly end up watching a movie or reruns some tv series.

Infact I know these movies are just waste of time and wont really matter like this post. You will understand if you are on the same page as me.


So lets do a thing...Lets team up and work on learning Java and then Android apps together. Plus to keep things interesting I will share other stuff as well.

So tag along. Bye .