/doc/source/java/basic.rst
ReStructuredText | 1117 lines | 731 code | 386 blank | 0 comment | 0 complexity | 653e0d5b700e0d58b20958f9a102d37a MD5 | raw file
- Java
- ****
- Hello World
- ===========
- .. warning::
- Filename should be same as class-name, otherwise compilation error will be generated.
- .. code-block:: java
- // HelloWorld.java
- public class HelloWorld{
- // main method is the starting point for execution
- public static void main(String[] args){
- System.out.println("Hello World"); // println = print + \n
- }
- }
- .. code-block:: shell
- $ javac HelloWorld.java
- $ java HelloWorld
- Hello World
- Variables
- =========
- .. code-block:: java
- // HelloWorld.java
- public class HelloWorld{
- public static void main(String[] args){
- System.out.println("Hello World");
- int i = 100;
- double j = 10.10;
- double k;
- k = i + j;
- // System.out.println("k= " + k);
- System.out.print("k= " + k + "\n");
- char c = 'c'; // char in single quote
- System.out.println("char = " + c);
- boolean b = true; // true/false
- System.out.println("Boolean b = " + b);
- System.out.println("3>4 :" + (3>4));
- // string is not a datatype; it's a predefined class
- String name = "Meher Krishna Patel"; // string in double quote
- System.out.println("Name = " + name);
- }
- }
- .. code-block:: shell
- $ javac HelloWorld.java
- $ java HelloWorld
- Hello World
- k= 110.1
- char = c
- Boolean b = true
- 3>4 :false
- Name = Meher Krishna Patel
- Printing values in Binary, Hex, Octal and Decimal formats
- =========================================================
- .. code-block:: java
- // hexDec.java
- class hexDec{
- public static void main(String arg[]){
- int x = 15;
- System.out.printf("x = %d\n", x);
- int h = 0xb;
- int o = 013;
-
- System.out.printf(" hex value of x = %x\n", x); // hex
- System.out.printf(" oct value of x = %o\n", x); // octal
- System.out.printf(" decimal value of x = %d\n\n", x); // decimal
- System.out.printf(" hex value of h = %x\n", h); // hex
- System.out.printf(" oct value of h = %o\n", h); // octal
- System.out.printf(" decimal value of h = %d\n\n", h); // decimal
- System.out.printf(" hex value of o = %x\n", o); // hex
- System.out.printf(" oct value of o = %o\n", o); // octal
- System.out.printf(" decimal value of o = %d\n\n", o); // decimal
- }
- }
- Define constant using 'final'
- =============================
- .. warning::
- Since method 'main' is of type **static**, therefore variables 'pi' and 'blob' should be of type '**static**', otherwise these can not be used in 'main' function.
- .. code-block:: java
- // defineConst.java
- public class defineConst{
- public static final double pi = 3.14;
- public static final String blog = "PythonDSP";
-
- public static void main(String[] args){
- final int radius = 2;
- double area;
- area = pi * Math.pow(radius, 2);
- System.out.printf("Area of circle = %f\n", area);
- System.out.printf("Blog : %s\n", blog);
- }
- }
- .. code-block:: shell
- $ javac defineConst.java
- $ java defineConst
- Area of circle = 12.560000
- Blog : PythonDSP
-
- .. code-block:: shell
- $ javac hexDec.java
- $ java hexDec
- x = 15
- hex value of x = f
- oct value of x = 17
- decimal value of x = 15
- hex value of h = b
- oct value of h = 13
- decimal value of h = 11
- hex value of o = b
- oct value of o = 13
- decimal value of o = 11
- Read input from user
- ====================
- .. code-block:: java
- // ReadEx.java
- import java.util.Scanner; // used to read input
- public class ReadEx{
- public static void main(String[] args){
- // Create object of Scanner
- Scanner scn = new Scanner(System.in);
-
- int x, y, z; // variables
- // print
- System.out.print("Enter first number: ");
- x = scn.nextInt(); // read x
- System.out.print("Enter second number: ");
- y = scn.nextInt(); // read y
- z = x+y; // add
- // printf
- System.out.printf("Sum = %d\n", z);
- }
- }
- Operators and Control statements
- ================================
- Operators
- ---------
- Arithmetic operators
- ^^^^^^^^^^^^^^^^^^^^^
- .. code-block:: java
- // incrementEx.java
- public class incrementEx{
- public static void main(String[] args){
- int i = 1;
- System.out.printf("i = %d\n\n", i);
-
- // print first, then increment
- System.out.printf("i++ = %d (i.e. access first and then increment): \n", i++); // 1
- System.out.printf("i = %d\n\n", i); // 2 (i.e. i is incremented by above statement)
- // increment first, then print
- System.out.printf("++i = %d (i.e. increment first and then access):\n", ++i); // 3
- System.out.printf("i = %d\n", i); // 3
- }
- }
- .. code-block:: shell
- $ java incrementEx
- i = 1
- i++ = 1 (i.e. access first and then increment):
- i = 2
- ++i = 3 (i.e. increment first and then access):
- i = 3
- Relational operators
- ^^^^^^^^^^^^^^^^^^^^
- Logical operators
- ^^^^^^^^^^^^^^^^^
- Decision statements
- -------------------
- If-else statements
- ^^^^^^^^^^^^^^^^^^
- .. code-block:: java
- // ElseIfEx.java
- import java.util.Scanner; // used to read input
- public class ElseIfEx{
- public static void main(String[] args){
- // Create object of Scanner
- Scanner scn = new Scanner(System.in);
-
- System.out.print("Enter Grade: ");
- String input = scn.next();
- char grade = input.charAt(0);
-
- // if grade is A or a
- if (grade == 'A' || grade == 'a') // logical operator
- System.out.printf("Excellent Student\n");
- else if ((grade == 'B') || (grade == 'b'))
- System.out.printf("Very Good Student\n");
- else if (grade == 'C' || grade == 'c')
- System.out.printf("Good Student\n");
- else if (grade == 'D' || grade == 'd')
- System.out.printf("Need improvements\n");
- else
- System.out.printf("Invalid grade\n");
- }
- }
- .. code-block:: shell
- $ javac ElseIfEx.java
- $ java ElseIfEx
- Enter Grade: b
- Very Good Student
- $ java ElseIfEx
- Enter Grade: 4
- Invalid grade
- Switch case
- ^^^^^^^^^^^
- .. code-block:: java
- // switchCase.java
- import java.util.Scanner; // used to read input
- public class switchCase{
- public static void main(String[] args){
- // Create object of Scanner
- Scanner scn = new Scanner(System.in);
-
- System.out.print("Enter Grade: ");
- String input = scn.next();
- char grade = input.charAt(0);
-
- switch(grade){
- case ('A'):
- System.out.printf("A: performance is excellent\n");
- break;
- case 'B' :
- System.out.printf("B: performance is good\n");
- break;
- case 'C' :
- System.out.printf("C: performance is not bad\n");
- break;
- default :
- System.out.printf("Invalid grade\n");
- }
- }
- }
- .. code-block:: shell
- $ javac switchCase.java
- $ java switchCase
- Enter Grade: A
- A: performance is excellent
- $ java switchCase
- Enter Grade: a
- Invalid grade
- Conditional operator (?:)
- ^^^^^^^^^^^^^^^^^^^^^^^^^
- Loops
- -----
- For loop
- ^^^^^^^^
- .. code-block:: java
- // forLoop.java
- public class forLoop{
- public static void main(String[] args){
- int i;
- // print 0 to 4
- for (i=0; i<5; i++){
- System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
- }
- // value of i is 5
- System.out.printf("\n");
- System.out.printf("Value of i = %d\n", i); // Value of i = 5
- }
- }
- .. code-block:: shell
- $ javac forLoop.java
- $ java forLoop
- 0, 1, 2, 3, 4,
- Value of i = 5
- While loop
- ^^^^^^^^^^
- .. code-block:: java
- // whileLoop.java
- public class whileLoop{
- public static void main(String[] args){
- int i=0;
- // print 0 to 4
- while(i < 5){
- System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
- i = i+1;
- }
- // value of i is 5
- System.out.printf("\n");
- System.out.printf("Value of i = %d\n", i); // Value of i = 5
- }
- }
- .. code-block:: shell
- $ javac whileLoop.java
- $ java whileLoop
- 0, 1, 2, 3, 4,
- Value of i = 5
- Do while loop
- ^^^^^^^^^^^^^
- .. code-block:: java
- // dowhileLoop.java
- public class dowhileLoop{
- public static void main(String[] args){
- int i=0;
- // print 0 to 4
- do{
- System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
- i = i+1;
- }while(i < 5);
- // value of i is 5
- System.out.printf("\n");
- System.out.printf("Value of i = %d\n", i); // Value of i = 5
- }
- }
- .. code-block:: shell
- $ javac dowhileLoop.java
- $ java dowhileLoop
- 0, 1, 2, 3, 4,
- Value of i = 5
- Continue and Break statements
- -----------------------------
- Continue
- ^^^^^^^^
- .. code-block:: java
- // forContinueLoop.java
- public class forContinueLoop{
- public static void main(String[] args){
- int i;
- // print 0 to 4
- for (i=0; i<5; i++){
- if (i%2==0)
- continue;
- System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
- }
- // value of i is 5
- System.out.printf("\n");
- System.out.printf("Value of i = %d\n", i); // Value of i = 5
- }
- }
- .. code-block:: shell
- $ javac forContinueLoop.java
- $ java forContinueLoop
- 1, 3,
- Value of i = 5
- Break
- ^^^^^
- .. code-block:: java
- // whileBreakLoop.java
- public class whileBreakLoop{
- public static void main(String[] args){
- int i=0;
- // print 0 to 6 (break at 7)
- while(i < 15){
- System.out.printf("%d, ", i);
- i = i+1;
- if (i%7==0)
- break;
- }
- System.out.printf("\n");
- System.out.printf("Value of i = %d\n", i);
- }
- }
- .. code-block:: shell
- $ javac whileBreakLoop.java
- $ java whileBreakLoop
- 0, 1, 2, 3, 4, 5, 6,
- Value of i = 7
- Array
- =====
- .. code-block:: java
- // arrayEx.java
- public class arrayEx{
- public static void main(String[] args){
- int i;
-
- int[] a; // uninitialized array of size 5 i.e. a[0]-a[4]
- a = new int[10];
-
- double[] b={2, 4.5, 6}; // initialized array of size 3
- int[] c = {3, 5};
-
- System.out.printf("a[1] = %d\n", a[1]); // uninitialized array has 0 value
- System.out.printf("c[0] = %d\n", c[0]); // 3
- // print all values of array b
- // %10s create the width of 10 after 'element'
- // and 'value' will be printed as right-aligned e.g. see 4.5 in output
- System.out.printf("%s %10s\n", "element", "value");
- for (i=0; i<3; i++){
- System.out.printf("%4d %12.1f\n", i, b[i]); // %12.1f = show minimum 12 integer & 1 decimal
- }
- // assign values of array a
- for (i=0; i<5; i++){
- a[i] = 2*i;
- }
- // print values of array a
- System.out.printf("%s %10s\n", "element", "value");
- for (i=0; i<5; i++){
- System.out.printf("%4d %12d\n", i, a[i]); // %12.1f = show minimum 12 integer and 1 decimal place
- }
- }
- }
- .. code-block:: shell
- $ javac arrayEx.java
- $ java arrayEx
- a[1] = 0
- c[0] = 3
- element value
- 0 2.0
- 1 4.5
- 2 6.0
- element value
- 0 0
- 1 2
- 2 4
- 3 6
- 4 8
- OOPs
- ====
- Class and object
- ----------------
- * Class Jungle
- .. code-block:: java
- // Jungle.java
- public class Jungle{
- // public : to allow access outside the class
- public void welcomeMessage(){
- System.out.println("Welcome to Jungle");
- }
- }
- * Object 'j' of class Jungle
- .. code-block:: java
- // JungleTest.java
- public class JungleTest{
- public static void main(String[] args){
- Jungle j = new Jungle();
- j.welcomeMessage();
- }
- }
- * Code execution
- .. code-block:: shell
- $ javac Jungle.java
- $ javac JungleTest.java
- $ java JungleTest
- Welcome to Jungle
- .. note::
- We can compile multiple file as below,
- .. code-block:: shell
-
- $ javac Jungle.java JungleTest.java
- or
- $ javac *.java
- Method with parameters
- ----------------------
- .. code-block:: java
- // Jungle.java
- public class Jungle{
- // public : to allow access outside the class
- public void welcomeMessage(String name){
- System.out.printf("Hello %s! Welcome to Jungle\n", name);
- }
- }
- .. code-block:: java
- // JungleTest.java
- public class JungleTest{
- public static void main(String[] args){
- Jungle j = new Jungle();
- j.welcomeMessage("Meher");
- }
- }
- .. code-block:: shell
- $ javac *.java
- $ java JungleTest
- Hello Meher! Welcome to Jungle
- set and get method
- ------------------
- .. code-block:: java
- // Jungle.java
- public class Jungle{
- private String visitorName;
- // set (save) visitor name
- public void setVisitorName(String name){
- visitorName = name;
- }
- // get visitor name
- public String getVisitorName(){
- return visitorName;
- }
- // print message
- public void welcomeMessage(){
- System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
- }
- }
- .. code-block:: java
- // JungleTest.java
- public class JungleTest{
- public static void main(String[] args){
- Jungle j = new Jungle();
- // save visitor name
- j.setVisitorName("Krishna");
- // print message
- j.welcomeMessage();
- }
- }
- .. code-block:: shell
- $ javac *.java
- $ java JungleTest
- Hello Krishna! Welcome to Jungle
- Constructor
- -----------
- * Initialize object using constructor
-
- .. code-block:: java
- // Jungle.java
- public class Jungle{
- private String visitorName;
- // Constructor : name should be same as class
- public Jungle(String name){ // constructor with one argument
- visitorName = name;
- }
- // set (save) visitor name
- public void setVisitorName(String name){
- visitorName = name;
- }
- // get visitor name
- public String getVisitorName(){
- return visitorName;
- }
- // print message
- public void welcomeMessage(){
- System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
- }
- }
- .. code-block:: java
- // JungleTest.java
- public class JungleTest{
- public static void main(String[] args){
- Jungle j = new Jungle("Patel");
- // print message
- j.welcomeMessage();
- }
- }
- .. code-block:: shell
- $ javac *.java
- $ java JungleTest
- Hello Patel! Welcome to Jungle
- Inheritance
- -----------
- .. code-block:: java
- // RateJungle.java
- public class RateJungle extends Jungle{
- private int feedback;
- private String name;
- public RateJungle(String name){
- super(name); // call the base class constructor
- feedback = 0; // set feedback to 0
- }
- public void setFeedback(int val){
- feedback = val;
- }
- public void printRating(){
- System.out.printf("Thanks %s\n", getVisitorName());
- System.out.printf("Your feedback is set as : %d\n", feedback);
- }
- }
-
-
- .. code-block:: java
- // RateJungleTest.java
- public class RateJungleTest{
- public static void main(String[] args){
- RateJungle m = new RateJungle("Meher");
- RateJungle k = new RateJungle("Krishna");
- m.printRating();
- m.setFeedback(2);
- m.printRating();
-
- k.printRating();
- }
- }
- .. code-block:: shell
- $ javac *.java
- $ java RateJungleTest
- Thanks Meher
- Your feedback is set as : 0
- Thanks Meher
- Your feedback is set as : 2
- Thanks Krishna
- Your feedback is set as : 0
- multiple constructor
- --------------------
- .. code-block:: java
- // RateJungle.java
- public class RateJungle extends Jungle{
- private int feedback;
- private String name;
- // constructor 1
- public RateJungle(String name){
- super(name); // call the base class constructor
- feedback = 0; // set feedback to 0
- }
- // constructor 2
- public RateJungle(String name, int val){
- super(name);
- feedback = val;
- }
- // constructor 3 : empty constructor
- public RateJungle(){
- }
- public void setFeedback(int val){
- feedback = val;
- }
- public void printRating(){
- System.out.printf("Thanks %s\n", getVisitorName());
- System.out.printf("Your feedback is set as : %d\n", feedback);
- }
- }
-
-
- * Since child class has empty constructor, therefore we need to add empty constructor in parent class as well.
- .. code-block:: java
- // Jungle.java
- public class Jungle{
- private String visitorName;
- // Constructor : name should be same as class
- public Jungle(String name){ // constructor with one argument
- visitorName = name;
- }
- // empty constructor : as child class has an empty constructor
- public Jungle(){
- }
- // set (save) visitor name
- public void setVisitorName(String name){
- visitorName = name;
- }
- // get visitor name
- public String getVisitorName(){
- return visitorName;
- }
- // print message
- public void welcomeMessage(){
- System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
- }
- }
- .. code-block:: java
- // RateJungleTest.java
- public class RateJungleTest{
- public static void main(String[] args){
- RateJungle m = new RateJungle("Meher");
- RateJungle k = new RateJungle("Krishna", 5);
- RateJungle p = new RateJungle();
- p.setVisitorName("Patel");
- p.setFeedback(2);
- m.printRating();
- k.printRating();
- p.printRating();
- }
- }
- .. code-block:: shell
- $ javac *.java
- $ java RateJungleTest
- Thanks Meher
- Your feedback is set as : 0
- Thanks Krishna
- Your feedback is set as : 5
- Thanks Patel
- Your feedback is set as : 2
- Polymorphism
- ------------
- .. code-block:: java
- // Animal.java
- public class Animal{
- public void scarySound(){
- System.out.println("Animals are running away due to scary sound.");
- }
- }
- .. code-block:: java
- // Bird.java
- public class Bird{
- public void scarySound(){
- System.out.println("Birds are flying away due to scary sound.");
- }
- }
- .. code-block:: java
- // Insect.java
- // empty class
- public class Insect{
- }
- .. code-block:: java
- // PolymorphismTest.java
- public class PolymorphismTest{
- public static void main(String[] args){
- Animal a = new Animal();
- Bird b = new Bird();
- a.scarySound();
- b.scarySound();
- }
- }
- .. code-block:: shell
- $ javac *.java
- $ java PolymorphismTest
- Animals are running away due to scary sound.
- Birds are flying away due to scary sound.
- Abstract class
- --------------
- .. code-block:: java
- // Abstract_Jungle.java
- // abstract class
- public abstract class Abstract_Jungle{
- private String visitorName;
- // set (save) visitor name
- public void setVisitorName(String name){
- visitorName = name;
- }
- // get visitor name
- public String getVisitorName(){
- return visitorName;
- }
- // print message
- public void welcomeMessage(){
- System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
- }
- // abstract method
- public abstract void scarySound();
- }
- .. code-block:: java
- // Animal.java
- public class Animal extends Abstract_Jungle{
- public void scarySound(){
- System.out.println("Animals are running away due to scary sound.");
- }
- }
- .. code-block:: java
- // Bird.java
- public class Bird extends Abstract_Jungle{
- public void scarySound(){
- System.out.println("Birds are flying away due to scary sound.");
- }
- }
- .. code-block:: java
- // Abstract_JungleTest.java
- public class Abstract_JungleTest{
- public static void main(String[] args){
- Animal a = new Animal();
- Bird b = new Bird();
- Insect i = new Insect();
- a.scarySound();
- b.scarySound();
- i.scarySound();
- }
- }
- .. code-block:: shell
- $ javac *.java
- $ java Abstract_JungleTest
- Animals are running away due to scary sound.
- Birds are flying away due to scary sound.
- Insects do not care about scary sound.
- .. error::
- If we do not define the 'scarySound()' in class Insect, then following error will be generated.
- .. code-block:: shell
- $ javac *.java
- Insect.java:4: error: Insect is not abstract and does not override abstract method scarySound() in Abstract_Jungle
- public class Insect extends Abstract_Jungle{
- ^
- 1 error