PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/doc/source/java/basic.rst

https://bitbucket.org/pythondsp1/javaguide
ReStructuredText | 1117 lines | 731 code | 386 blank | 0 comment | 0 complexity | 653e0d5b700e0d58b20958f9a102d37a MD5 | raw file
  1. Java
  2. ****
  3. Hello World
  4. ===========
  5. .. warning::
  6. Filename should be same as class-name, otherwise compilation error will be generated.
  7. .. code-block:: java
  8. // HelloWorld.java
  9. public class HelloWorld{
  10. // main method is the starting point for execution
  11. public static void main(String[] args){
  12. System.out.println("Hello World"); // println = print + \n
  13. }
  14. }
  15. .. code-block:: shell
  16. $ javac HelloWorld.java
  17. $ java HelloWorld
  18. Hello World
  19. Variables
  20. =========
  21. .. code-block:: java
  22. // HelloWorld.java
  23. public class HelloWorld{
  24. public static void main(String[] args){
  25. System.out.println("Hello World");
  26. int i = 100;
  27. double j = 10.10;
  28. double k;
  29. k = i + j;
  30. // System.out.println("k= " + k);
  31. System.out.print("k= " + k + "\n");
  32. char c = 'c'; // char in single quote
  33. System.out.println("char = " + c);
  34. boolean b = true; // true/false
  35. System.out.println("Boolean b = " + b);
  36. System.out.println("3>4 :" + (3>4));
  37. // string is not a datatype; it's a predefined class
  38. String name = "Meher Krishna Patel"; // string in double quote
  39. System.out.println("Name = " + name);
  40. }
  41. }
  42. .. code-block:: shell
  43. $ javac HelloWorld.java
  44. $ java HelloWorld
  45. Hello World
  46. k= 110.1
  47. char = c
  48. Boolean b = true
  49. 3>4 :false
  50. Name = Meher Krishna Patel
  51. Printing values in Binary, Hex, Octal and Decimal formats
  52. =========================================================
  53. .. code-block:: java
  54. // hexDec.java
  55. class hexDec{
  56. public static void main(String arg[]){
  57. int x = 15;
  58. System.out.printf("x = %d\n", x);
  59. int h = 0xb;
  60. int o = 013;
  61. System.out.printf(" hex value of x = %x\n", x); // hex
  62. System.out.printf(" oct value of x = %o\n", x); // octal
  63. System.out.printf(" decimal value of x = %d\n\n", x); // decimal
  64. System.out.printf(" hex value of h = %x\n", h); // hex
  65. System.out.printf(" oct value of h = %o\n", h); // octal
  66. System.out.printf(" decimal value of h = %d\n\n", h); // decimal
  67. System.out.printf(" hex value of o = %x\n", o); // hex
  68. System.out.printf(" oct value of o = %o\n", o); // octal
  69. System.out.printf(" decimal value of o = %d\n\n", o); // decimal
  70. }
  71. }
  72. Define constant using 'final'
  73. =============================
  74. .. warning::
  75. 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.
  76. .. code-block:: java
  77. // defineConst.java
  78. public class defineConst{
  79. public static final double pi = 3.14;
  80. public static final String blog = "PythonDSP";
  81. public static void main(String[] args){
  82. final int radius = 2;
  83. double area;
  84. area = pi * Math.pow(radius, 2);
  85. System.out.printf("Area of circle = %f\n", area);
  86. System.out.printf("Blog : %s\n", blog);
  87. }
  88. }
  89. .. code-block:: shell
  90. $ javac defineConst.java
  91. $ java defineConst
  92. Area of circle = 12.560000
  93. Blog : PythonDSP
  94. .. code-block:: shell
  95. $ javac hexDec.java
  96. $ java hexDec
  97. x = 15
  98. hex value of x = f
  99. oct value of x = 17
  100. decimal value of x = 15
  101. hex value of h = b
  102. oct value of h = 13
  103. decimal value of h = 11
  104. hex value of o = b
  105. oct value of o = 13
  106. decimal value of o = 11
  107. Read input from user
  108. ====================
  109. .. code-block:: java
  110. // ReadEx.java
  111. import java.util.Scanner; // used to read input
  112. public class ReadEx{
  113. public static void main(String[] args){
  114. // Create object of Scanner
  115. Scanner scn = new Scanner(System.in);
  116. int x, y, z; // variables
  117. // print
  118. System.out.print("Enter first number: ");
  119. x = scn.nextInt(); // read x
  120. System.out.print("Enter second number: ");
  121. y = scn.nextInt(); // read y
  122. z = x+y; // add
  123. // printf
  124. System.out.printf("Sum = %d\n", z);
  125. }
  126. }
  127. Operators and Control statements
  128. ================================
  129. Operators
  130. ---------
  131. Arithmetic operators
  132. ^^^^^^^^^^^^^^^^^^^^^
  133. .. code-block:: java
  134. // incrementEx.java
  135. public class incrementEx{
  136. public static void main(String[] args){
  137. int i = 1;
  138. System.out.printf("i = %d\n\n", i);
  139. // print first, then increment
  140. System.out.printf("i++ = %d (i.e. access first and then increment): \n", i++); // 1
  141. System.out.printf("i = %d\n\n", i); // 2 (i.e. i is incremented by above statement)
  142. // increment first, then print
  143. System.out.printf("++i = %d (i.e. increment first and then access):\n", ++i); // 3
  144. System.out.printf("i = %d\n", i); // 3
  145. }
  146. }
  147. .. code-block:: shell
  148. $ java incrementEx
  149. i = 1
  150. i++ = 1 (i.e. access first and then increment):
  151. i = 2
  152. ++i = 3 (i.e. increment first and then access):
  153. i = 3
  154. Relational operators
  155. ^^^^^^^^^^^^^^^^^^^^
  156. Logical operators
  157. ^^^^^^^^^^^^^^^^^
  158. Decision statements
  159. -------------------
  160. If-else statements
  161. ^^^^^^^^^^^^^^^^^^
  162. .. code-block:: java
  163. // ElseIfEx.java
  164. import java.util.Scanner; // used to read input
  165. public class ElseIfEx{
  166. public static void main(String[] args){
  167. // Create object of Scanner
  168. Scanner scn = new Scanner(System.in);
  169. System.out.print("Enter Grade: ");
  170. String input = scn.next();
  171. char grade = input.charAt(0);
  172. // if grade is A or a
  173. if (grade == 'A' || grade == 'a') // logical operator
  174. System.out.printf("Excellent Student\n");
  175. else if ((grade == 'B') || (grade == 'b'))
  176. System.out.printf("Very Good Student\n");
  177. else if (grade == 'C' || grade == 'c')
  178. System.out.printf("Good Student\n");
  179. else if (grade == 'D' || grade == 'd')
  180. System.out.printf("Need improvements\n");
  181. else
  182. System.out.printf("Invalid grade\n");
  183. }
  184. }
  185. .. code-block:: shell
  186. $ javac ElseIfEx.java
  187. $ java ElseIfEx
  188. Enter Grade: b
  189. Very Good Student
  190. $ java ElseIfEx
  191. Enter Grade: 4
  192. Invalid grade
  193. Switch case
  194. ^^^^^^^^^^^
  195. .. code-block:: java
  196. // switchCase.java
  197. import java.util.Scanner; // used to read input
  198. public class switchCase{
  199. public static void main(String[] args){
  200. // Create object of Scanner
  201. Scanner scn = new Scanner(System.in);
  202. System.out.print("Enter Grade: ");
  203. String input = scn.next();
  204. char grade = input.charAt(0);
  205. switch(grade){
  206. case ('A'):
  207. System.out.printf("A: performance is excellent\n");
  208. break;
  209. case 'B' :
  210. System.out.printf("B: performance is good\n");
  211. break;
  212. case 'C' :
  213. System.out.printf("C: performance is not bad\n");
  214. break;
  215. default :
  216. System.out.printf("Invalid grade\n");
  217. }
  218. }
  219. }
  220. .. code-block:: shell
  221. $ javac switchCase.java
  222. $ java switchCase
  223. Enter Grade: A
  224. A: performance is excellent
  225. $ java switchCase
  226. Enter Grade: a
  227. Invalid grade
  228. Conditional operator (?:)
  229. ^^^^^^^^^^^^^^^^^^^^^^^^^
  230. Loops
  231. -----
  232. For loop
  233. ^^^^^^^^
  234. .. code-block:: java
  235. // forLoop.java
  236. public class forLoop{
  237. public static void main(String[] args){
  238. int i;
  239. // print 0 to 4
  240. for (i=0; i<5; i++){
  241. System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
  242. }
  243. // value of i is 5
  244. System.out.printf("\n");
  245. System.out.printf("Value of i = %d\n", i); // Value of i = 5
  246. }
  247. }
  248. .. code-block:: shell
  249. $ javac forLoop.java
  250. $ java forLoop
  251. 0, 1, 2, 3, 4,
  252. Value of i = 5
  253. While loop
  254. ^^^^^^^^^^
  255. .. code-block:: java
  256. // whileLoop.java
  257. public class whileLoop{
  258. public static void main(String[] args){
  259. int i=0;
  260. // print 0 to 4
  261. while(i < 5){
  262. System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
  263. i = i+1;
  264. }
  265. // value of i is 5
  266. System.out.printf("\n");
  267. System.out.printf("Value of i = %d\n", i); // Value of i = 5
  268. }
  269. }
  270. .. code-block:: shell
  271. $ javac whileLoop.java
  272. $ java whileLoop
  273. 0, 1, 2, 3, 4,
  274. Value of i = 5
  275. Do while loop
  276. ^^^^^^^^^^^^^
  277. .. code-block:: java
  278. // dowhileLoop.java
  279. public class dowhileLoop{
  280. public static void main(String[] args){
  281. int i=0;
  282. // print 0 to 4
  283. do{
  284. System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
  285. i = i+1;
  286. }while(i < 5);
  287. // value of i is 5
  288. System.out.printf("\n");
  289. System.out.printf("Value of i = %d\n", i); // Value of i = 5
  290. }
  291. }
  292. .. code-block:: shell
  293. $ javac dowhileLoop.java
  294. $ java dowhileLoop
  295. 0, 1, 2, 3, 4,
  296. Value of i = 5
  297. Continue and Break statements
  298. -----------------------------
  299. Continue
  300. ^^^^^^^^
  301. .. code-block:: java
  302. // forContinueLoop.java
  303. public class forContinueLoop{
  304. public static void main(String[] args){
  305. int i;
  306. // print 0 to 4
  307. for (i=0; i<5; i++){
  308. if (i%2==0)
  309. continue;
  310. System.out.printf("%d, ", i); //0, 1, 2, 3, 4,
  311. }
  312. // value of i is 5
  313. System.out.printf("\n");
  314. System.out.printf("Value of i = %d\n", i); // Value of i = 5
  315. }
  316. }
  317. .. code-block:: shell
  318. $ javac forContinueLoop.java
  319. $ java forContinueLoop
  320. 1, 3,
  321. Value of i = 5
  322. Break
  323. ^^^^^
  324. .. code-block:: java
  325. // whileBreakLoop.java
  326. public class whileBreakLoop{
  327. public static void main(String[] args){
  328. int i=0;
  329. // print 0 to 6 (break at 7)
  330. while(i < 15){
  331. System.out.printf("%d, ", i);
  332. i = i+1;
  333. if (i%7==0)
  334. break;
  335. }
  336. System.out.printf("\n");
  337. System.out.printf("Value of i = %d\n", i);
  338. }
  339. }
  340. .. code-block:: shell
  341. $ javac whileBreakLoop.java
  342. $ java whileBreakLoop
  343. 0, 1, 2, 3, 4, 5, 6,
  344. Value of i = 7
  345. Array
  346. =====
  347. .. code-block:: java
  348. // arrayEx.java
  349. public class arrayEx{
  350. public static void main(String[] args){
  351. int i;
  352. int[] a; // uninitialized array of size 5 i.e. a[0]-a[4]
  353. a = new int[10];
  354. double[] b={2, 4.5, 6}; // initialized array of size 3
  355. int[] c = {3, 5};
  356. System.out.printf("a[1] = %d\n", a[1]); // uninitialized array has 0 value
  357. System.out.printf("c[0] = %d\n", c[0]); // 3
  358. // print all values of array b
  359. // %10s create the width of 10 after 'element'
  360. // and 'value' will be printed as right-aligned e.g. see 4.5 in output
  361. System.out.printf("%s %10s\n", "element", "value");
  362. for (i=0; i<3; i++){
  363. System.out.printf("%4d %12.1f\n", i, b[i]); // %12.1f = show minimum 12 integer & 1 decimal
  364. }
  365. // assign values of array a
  366. for (i=0; i<5; i++){
  367. a[i] = 2*i;
  368. }
  369. // print values of array a
  370. System.out.printf("%s %10s\n", "element", "value");
  371. for (i=0; i<5; i++){
  372. System.out.printf("%4d %12d\n", i, a[i]); // %12.1f = show minimum 12 integer and 1 decimal place
  373. }
  374. }
  375. }
  376. .. code-block:: shell
  377. $ javac arrayEx.java
  378. $ java arrayEx
  379. a[1] = 0
  380. c[0] = 3
  381. element value
  382. 0 2.0
  383. 1 4.5
  384. 2 6.0
  385. element value
  386. 0 0
  387. 1 2
  388. 2 4
  389. 3 6
  390. 4 8
  391. OOPs
  392. ====
  393. Class and object
  394. ----------------
  395. * Class Jungle
  396. .. code-block:: java
  397. // Jungle.java
  398. public class Jungle{
  399. // public : to allow access outside the class
  400. public void welcomeMessage(){
  401. System.out.println("Welcome to Jungle");
  402. }
  403. }
  404. * Object 'j' of class Jungle
  405. .. code-block:: java
  406. // JungleTest.java
  407. public class JungleTest{
  408. public static void main(String[] args){
  409. Jungle j = new Jungle();
  410. j.welcomeMessage();
  411. }
  412. }
  413. * Code execution
  414. .. code-block:: shell
  415. $ javac Jungle.java
  416. $ javac JungleTest.java
  417. $ java JungleTest
  418. Welcome to Jungle
  419. .. note::
  420. We can compile multiple file as below,
  421. .. code-block:: shell
  422. $ javac Jungle.java JungleTest.java
  423. or
  424. $ javac *.java
  425. Method with parameters
  426. ----------------------
  427. .. code-block:: java
  428. // Jungle.java
  429. public class Jungle{
  430. // public : to allow access outside the class
  431. public void welcomeMessage(String name){
  432. System.out.printf("Hello %s! Welcome to Jungle\n", name);
  433. }
  434. }
  435. .. code-block:: java
  436. // JungleTest.java
  437. public class JungleTest{
  438. public static void main(String[] args){
  439. Jungle j = new Jungle();
  440. j.welcomeMessage("Meher");
  441. }
  442. }
  443. .. code-block:: shell
  444. $ javac *.java
  445. $ java JungleTest
  446. Hello Meher! Welcome to Jungle
  447. set and get method
  448. ------------------
  449. .. code-block:: java
  450. // Jungle.java
  451. public class Jungle{
  452. private String visitorName;
  453. // set (save) visitor name
  454. public void setVisitorName(String name){
  455. visitorName = name;
  456. }
  457. // get visitor name
  458. public String getVisitorName(){
  459. return visitorName;
  460. }
  461. // print message
  462. public void welcomeMessage(){
  463. System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
  464. }
  465. }
  466. .. code-block:: java
  467. // JungleTest.java
  468. public class JungleTest{
  469. public static void main(String[] args){
  470. Jungle j = new Jungle();
  471. // save visitor name
  472. j.setVisitorName("Krishna");
  473. // print message
  474. j.welcomeMessage();
  475. }
  476. }
  477. .. code-block:: shell
  478. $ javac *.java
  479. $ java JungleTest
  480. Hello Krishna! Welcome to Jungle
  481. Constructor
  482. -----------
  483. * Initialize object using constructor
  484. .. code-block:: java
  485. // Jungle.java
  486. public class Jungle{
  487. private String visitorName;
  488. // Constructor : name should be same as class
  489. public Jungle(String name){ // constructor with one argument
  490. visitorName = name;
  491. }
  492. // set (save) visitor name
  493. public void setVisitorName(String name){
  494. visitorName = name;
  495. }
  496. // get visitor name
  497. public String getVisitorName(){
  498. return visitorName;
  499. }
  500. // print message
  501. public void welcomeMessage(){
  502. System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
  503. }
  504. }
  505. .. code-block:: java
  506. // JungleTest.java
  507. public class JungleTest{
  508. public static void main(String[] args){
  509. Jungle j = new Jungle("Patel");
  510. // print message
  511. j.welcomeMessage();
  512. }
  513. }
  514. .. code-block:: shell
  515. $ javac *.java
  516. $ java JungleTest
  517. Hello Patel! Welcome to Jungle
  518. Inheritance
  519. -----------
  520. .. code-block:: java
  521. // RateJungle.java
  522. public class RateJungle extends Jungle{
  523. private int feedback;
  524. private String name;
  525. public RateJungle(String name){
  526. super(name); // call the base class constructor
  527. feedback = 0; // set feedback to 0
  528. }
  529. public void setFeedback(int val){
  530. feedback = val;
  531. }
  532. public void printRating(){
  533. System.out.printf("Thanks %s\n", getVisitorName());
  534. System.out.printf("Your feedback is set as : %d\n", feedback);
  535. }
  536. }
  537. .. code-block:: java
  538. // RateJungleTest.java
  539. public class RateJungleTest{
  540. public static void main(String[] args){
  541. RateJungle m = new RateJungle("Meher");
  542. RateJungle k = new RateJungle("Krishna");
  543. m.printRating();
  544. m.setFeedback(2);
  545. m.printRating();
  546. k.printRating();
  547. }
  548. }
  549. .. code-block:: shell
  550. $ javac *.java
  551. $ java RateJungleTest
  552. Thanks Meher
  553. Your feedback is set as : 0
  554. Thanks Meher
  555. Your feedback is set as : 2
  556. Thanks Krishna
  557. Your feedback is set as : 0
  558. multiple constructor
  559. --------------------
  560. .. code-block:: java
  561. // RateJungle.java
  562. public class RateJungle extends Jungle{
  563. private int feedback;
  564. private String name;
  565. // constructor 1
  566. public RateJungle(String name){
  567. super(name); // call the base class constructor
  568. feedback = 0; // set feedback to 0
  569. }
  570. // constructor 2
  571. public RateJungle(String name, int val){
  572. super(name);
  573. feedback = val;
  574. }
  575. // constructor 3 : empty constructor
  576. public RateJungle(){
  577. }
  578. public void setFeedback(int val){
  579. feedback = val;
  580. }
  581. public void printRating(){
  582. System.out.printf("Thanks %s\n", getVisitorName());
  583. System.out.printf("Your feedback is set as : %d\n", feedback);
  584. }
  585. }
  586. * Since child class has empty constructor, therefore we need to add empty constructor in parent class as well.
  587. .. code-block:: java
  588. // Jungle.java
  589. public class Jungle{
  590. private String visitorName;
  591. // Constructor : name should be same as class
  592. public Jungle(String name){ // constructor with one argument
  593. visitorName = name;
  594. }
  595. // empty constructor : as child class has an empty constructor
  596. public Jungle(){
  597. }
  598. // set (save) visitor name
  599. public void setVisitorName(String name){
  600. visitorName = name;
  601. }
  602. // get visitor name
  603. public String getVisitorName(){
  604. return visitorName;
  605. }
  606. // print message
  607. public void welcomeMessage(){
  608. System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
  609. }
  610. }
  611. .. code-block:: java
  612. // RateJungleTest.java
  613. public class RateJungleTest{
  614. public static void main(String[] args){
  615. RateJungle m = new RateJungle("Meher");
  616. RateJungle k = new RateJungle("Krishna", 5);
  617. RateJungle p = new RateJungle();
  618. p.setVisitorName("Patel");
  619. p.setFeedback(2);
  620. m.printRating();
  621. k.printRating();
  622. p.printRating();
  623. }
  624. }
  625. .. code-block:: shell
  626. $ javac *.java
  627. $ java RateJungleTest
  628. Thanks Meher
  629. Your feedback is set as : 0
  630. Thanks Krishna
  631. Your feedback is set as : 5
  632. Thanks Patel
  633. Your feedback is set as : 2
  634. Polymorphism
  635. ------------
  636. .. code-block:: java
  637. // Animal.java
  638. public class Animal{
  639. public void scarySound(){
  640. System.out.println("Animals are running away due to scary sound.");
  641. }
  642. }
  643. .. code-block:: java
  644. // Bird.java
  645. public class Bird{
  646. public void scarySound(){
  647. System.out.println("Birds are flying away due to scary sound.");
  648. }
  649. }
  650. .. code-block:: java
  651. // Insect.java
  652. // empty class
  653. public class Insect{
  654. }
  655. .. code-block:: java
  656. // PolymorphismTest.java
  657. public class PolymorphismTest{
  658. public static void main(String[] args){
  659. Animal a = new Animal();
  660. Bird b = new Bird();
  661. a.scarySound();
  662. b.scarySound();
  663. }
  664. }
  665. .. code-block:: shell
  666. $ javac *.java
  667. $ java PolymorphismTest
  668. Animals are running away due to scary sound.
  669. Birds are flying away due to scary sound.
  670. Abstract class
  671. --------------
  672. .. code-block:: java
  673. // Abstract_Jungle.java
  674. // abstract class
  675. public abstract class Abstract_Jungle{
  676. private String visitorName;
  677. // set (save) visitor name
  678. public void setVisitorName(String name){
  679. visitorName = name;
  680. }
  681. // get visitor name
  682. public String getVisitorName(){
  683. return visitorName;
  684. }
  685. // print message
  686. public void welcomeMessage(){
  687. System.out.printf("Hello %s! Welcome to Jungle\n", getVisitorName());
  688. }
  689. // abstract method
  690. public abstract void scarySound();
  691. }
  692. .. code-block:: java
  693. // Animal.java
  694. public class Animal extends Abstract_Jungle{
  695. public void scarySound(){
  696. System.out.println("Animals are running away due to scary sound.");
  697. }
  698. }
  699. .. code-block:: java
  700. // Bird.java
  701. public class Bird extends Abstract_Jungle{
  702. public void scarySound(){
  703. System.out.println("Birds are flying away due to scary sound.");
  704. }
  705. }
  706. .. code-block:: java
  707. // Abstract_JungleTest.java
  708. public class Abstract_JungleTest{
  709. public static void main(String[] args){
  710. Animal a = new Animal();
  711. Bird b = new Bird();
  712. Insect i = new Insect();
  713. a.scarySound();
  714. b.scarySound();
  715. i.scarySound();
  716. }
  717. }
  718. .. code-block:: shell
  719. $ javac *.java
  720. $ java Abstract_JungleTest
  721. Animals are running away due to scary sound.
  722. Birds are flying away due to scary sound.
  723. Insects do not care about scary sound.
  724. .. error::
  725. If we do not define the 'scarySound()' in class Insect, then following error will be generated.
  726. .. code-block:: shell
  727. $ javac *.java
  728. Insect.java:4: error: Insect is not abstract and does not override abstract method scarySound() in Abstract_Jungle
  729. public class Insect extends Abstract_Jungle{
  730. ^
  731. 1 error