java cheat sheet

117

Click here to load reader

Upload: saifur-rahman

Post on 17-Aug-2015

115 views

Category:

Education


9 download

TRANSCRIPT

  1. 1. Java Programming Language Md. Saifur Rahman Java Programming Basic Concept
  2. 2. 1 Java TABLE OF CONTENTS Chapter Search Topic CHAPTER 1 ............................................................................. # SECTION 1.1 ...........................................................................................# Subsection 1.1.a ...............................................................................# Subsection 1.1.b ...............................................................................# Subsection 1.1.c................................................................................# SECTION 1.2 ...........................................................................................# SECTION 1.3 ...........................................................................................# CHAPTER 2 ............................................................................. # SECTION 2.1 ...........................................................................................# SECTION 2.2 ...........................................................................................# Subsection 2.2.a ...............................................................................# Subsection 2.2.b ...............................................................................# Subsection 2.2.c................................................................................# SECTION 2.3 ...........................................................................................# CHAPTER 3 ............................................................................. # SECTION 3.1 ...........................................................................................# SECTION 3.2 ...........................................................................................# SECTION 3.3 ...........................................................................................# Subsection 3.3.a ...............................................................................# Subsection 3.3.b ...............................................................................# Subsection 3.3.c.....................................................................................# CHAPTER 3 ............................................................................. # SECTION 3.1 ...........................................................................................# SECTION 3.2 ...........................................................................................# SECTION 3.3 ...........................................................................................# Subsection 3.3.a ...............................................................................# Subsection 3.3.b ...............................................................................# Subsection 3.3.c.....................................................................................# CHAPTER 3 ............................................................................. # SECTION 3.1 ...........................................................................................# SECTION 3.2 ...........................................................................................# SECTION 3.3 ...........................................................................................# Subsection 3.3.a ...............................................................................# Subsection 3.3.b ...............................................................................# Subsection 3.3.c.....................................................................................# UseCtrl+F STRING TOPIC Complex programs FILE I/O TOPIC THREAD TOPIC CLASS TOPIC INHERITANCE TOPIC CONSTRUCTOR TOPIC OBJECTTOPIC METHODTOPIC POLYMORPHISM TOPIC EXCEPTION TOPIC ENCAPSULATION TOPIC PACKAGES, INHERITANCEANDINTERFACES TOOPIC STATIC KEYWORDTOPIC ABSTRACT KEYWORD TOPIC Link Web resource tutorials http://www.c4learn.com/javaprogramming/ http://www.programmingsimplified.com/java/source-code/java- hello-world-program http://www.similarsites.com/site/c4learn.com http://docs.oracle.com/javase/tutorial/java/ http://beginnersbook.com/2013/05/method-overloading/ http://www.tutorialspoint.com/java/ http://www.javatpoint.com/static-keyword-in-java http://guru99.com/java-tutorial.html http://crunchify.com/java-tips-never-make-an-instance-fields-of-class-public/ Background colors RGB Color code Color sample RGB Color code Color sample 234, 224, 215 200, 213, 204 209, 187, 211 213, 241, 179 172, 185, 202 190, 225, 192 199, 208, 219 227, 215, 229 208, 208, 207 191, 222, 198 6+
  3. 3. 2 198, 198, 197 214, 199, 174 204, 192, 174 234, 220, 197 237, 203, 200 221, 206, 184 192, 204, 172 205, 193, 183 172, 182, 170 197, 213, 205 226, 239, 217 235, 239, 255 245, 245, 220 210, 210, 210 233, 233, 233 233, 234, 234 211, 211, 211 255, 251, 230 225, 230, 246 210, 225, 240 220, 225, 237 237, 237, 237 227, 204, 233 208, 216, 222 233, 226, 171 242, 236, 185 175, 201, 194 253, 248, 212 234, 217, 154 196, 207, 187 250, 224, 206 Importance of topics
  4. 4. 3 *** Most important ** Less important * important Introduction to Computers and Java The smallest data item in a computer can assume the value 0 or the value 1. Such a data item is called a bit characters are composed of bits. characters that are composed of two bytes fields are composed of characters or bytes. A field is a group of characters or bytes that conveys meaning. Compiling a Java Program into Bytecodes
  5. 5. 4 To compile javac Welcome.java To execute java Welcome Things We need to know The three types of languages discussed in the chapter are machine languages, assembly languages, high-level languages. The programs that translate high-level language programs into machine language are called compilers Android is a smartphone operating system based on the Linux kernel and Java. Ashiq sir in class main concepts Lecture 1 1. Lecture 2
  6. 6. 5 (9/29/2014) tools NetBeans ide 8.1 link https://netbeans.org/downloads/ books java the complete reference 9th edition herbert schildt Filecreate File > new Project> java > java Application > projectname + projectlocation > finish Javaprogramworks Few littleconcepts 1. Function = method 2. Add = class name (With starting capital letter) 3. add() = Method (With starting lower case) 4. In java main() is not mandatory but not execute 5. In business wecan give class file not sourcefile but class file can convertinto Sourcecode C Java include import Object 1. Object = set of attributes = like structure OOP must have3 things 1. Encapsulation ( ) 2. Polymorphism( ) 3. Inheritance( ) Class 1. Domain 2. Idea 3. Environment 4. For object we need an environment thats why we use class Suppose messi is the best player. But he cannot play in banani park. He must need an good field or environment where he can play football. Messi = object Environment = class 5. User defined data-type 6. Set of objects Fruit is a class then object = (mango , jackfruit, banana, etc) Declaration class className { member variable declaration; member fuction defination; } Classnaming conventions/rules 1. Name starts with a uppercase 2. Main class name = file name First program package class2; import java.io.*; class Class2 { public static void main(String args[]) { System.out.println("Hello world"); } } package class2; import java.io.*; public class Method_overloading1 { public static void main(String args[]) { int num = 7; if(num % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); } 1. program begins with a call to main() method. 2. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. (Arrays are collections of similar objects.) 3. Output is actually accomplished by the built-in println( ) method & displays the string which is passed to it. & println( ) can be used to display other types of information, too. The line begins with System.out, System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. 4. All statements in Java end with a semicolon. 5. Class Member Member Variable Member Function
  7. 7. 6 } } Programprocess 1. Comments // This is a single line comment /* This is a Multiline comment */ Lecture 3 (Wednesday, October 01, 2014) packageclass3; import java.util.Scanner; public class Input { public static void main(String args[]) { System.out.print("Enterta number to check odd/even = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); if(input %2 == 0) { System.out.println(input+" is even..."); } else System.out.println(input+" is odd "); } } Function calling Wrong Process packageclass3; import java.util.Scanner; public class OddEvenCheckWithFuncCall { int oddeven(int input) { if(input %2 == 0) { System.out.println(input+" is even..."); } else System.out.println(input+" is odd "); Process one packageclass3; import java.util.Scanner; class OddEvenCheck { int oddeven(int input) { if(input %2 == 0) { System.out.println(input+" is even..."); } else System.out.println(input+" is odd "); return 0; } Process two packageclass3; import java.util.Scanner; class OddEvenCheck { int oddeven(int input) { if(input %2 == 0) return 1; else return 0; } } public class OddEvenCheckWithFuncCall Output Low Run Execute Interprete Starts from main() High 1. Compile 2. Convert machine code to electric signal
  8. 8. 7 return 0; } public static void main(String args[]) { System.out.print("Enterta number to check odd/even = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); oddeven(input); non-static method oddeven(int) cannot be referenced from a static context so this cannot run in java but c can compile it } } } public class OddEvenCheckWithFuncCall { public static void main(String args[]) { System.out.print("Enterta number to check odd/even = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); OddEvenCheck oec = new OddEvenCheck(); oec.oddeven(input); } } { public static void main(String args[]) { System.out.print("Enterta number to check odd/even = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); OddEvenCheck oec = new OddEvenCheck(); int out = oec.oddeven(input); if(out == 1) System.out.println(input+" is even number"); else System.out.println(input+" is odd number"); } } Introduction to Java Applications { = an opening left brace } = the closing right brace C T
  9. 9. 8 Complex programs packageclass3; import java.util.Scanner; public class OddEvenCheckWithFuncCall { public static void main(String args[]) { System.out.print("Enter a number to make a pyramid = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); for(intr = 0; r0) { pos=pos+1; } else if(a[i] we hired one person (guard), name getter. The responsibility of the person was to provide exact duplicate copy of the cake. > we put a lock on the class and gave the key to guard. so no one can directly eat the cake, one has to ask getter for cake. Bingo ! problem solved ??, Not yet; there was another issue that happened - I got the copy of cake and found that it was not sweet enough. I added the sugar and asked the guard to replace this cake with original one. Guard said - "that's not my duty". So we took another step: > we hired one more person (guard), name setter. The responsibility of the setter was to replace the original cake. I gave the new cake, with enough sweetness, to setter and he replaced it. Problem Solved ??, Not yet, one guy mixed the poison into cake and asked the setter to replace it. So we were in problem again, so we took anothe step, we gave addition responsbility to setter - > Test the cake before replacing. Replace it if and only if it passes certain test. OK !! This is the concept behined ENCAPSULATION.In Technical terms - >Box act as Class >Cake act as Field of the class >guards act as public methods of the class >responsibilities of guards act as action performed by methods So Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Medicine store example to explain Encapsulation: Lets say you have to buy some medicines. You go to the medical store and ask the chemist for the meds. Only the chemist has access to the medicines in the store based on your prescription. The chemist knows what medicines to give to you. This reduces the risk of you taking any medicine that is not intended for you. In this example, MEDICINES == Member Variables. CHEMIST == Member Methods. You == External Application or piece of Code. So, If Any external Application has to access the Member Variables It has to call the appropriate Member Methods which will do the task for it.(If You have to access the Medicines You have to ask the Chemist). This way the member variables are secure and encapsulated by a layer of Member Methods. The Member Methods and Member Variables are bundled together in to objects and can be accessed only by the objects. So you need 2 steps if you have to access a public member of a class you have to: 1. Create an object of the class 2. Then access the member through object. You need 3 steps if you want to access the private members of a class 1. You have to create an object of the class 2. Then access the public method of the class through the object 3. Then access the private member of the class through the public method which has access to it. Also, encapsulation ensures that you do not accidentally modify something else. i.e. if you call the method setMy1stMemberVariable() it modifies only my1stMemberVariable and does not changes my2ndMemberVariable i.e. there are no side effects! Now refer to the above program and read the comments. You should understand it properly.
  10. 32. 31 Packages, Inheritance And Interfaces Toopic No Term Definition 1 Inheritance Inheritance is a process where one object acquires the properties of another object 2 Subclass Class which inherits the properties of another object is called assubclass 3 Superclass Class whose properties are inherited by subclass is called assuperclass 4 Keywords Used extends and implements Finding Packages and CLASSPATH -classpath option with java and javac to specify the path to your classes inheritance public class Vehicle{ } public class FourWheeler extends Vehicle{ } public class TwoWheeler extends Vehicle{ 1. Vehicle is the superclass of TwoWheeler class. 2. Vehicle is the superclass of FourWheeler class. 3. TwoWheeler and FourWheeler are sub classes of Vehicle class. 4. WagonR is the subclass of both FourWheeler and Vehicle classes. IS-A relationship of above example is - TwoWheeler IS-A Vehicle FourWheeler IS-A Vehicle WagonR IS-A FourWheeler
  11. 33. 32 } public class WagonR extends FourWheeler{ } publicclass Caller { publicstaticvoid main( String[] args ) { FourWheeler v1 = new FourWheeler(); TwoWheeler v2 = new TwoWheeler(); WagonR v3 = new WagonR(); System.out.println(v1instanceofVehicle); System.out.println(v2instanceofVehicle); System.out.println(v3instanceofVehicle); System.out.println(v3instanceofFourWheeler); } } publicclass Vehicle { } true true true true publicclass FourWheeler extends Vehicle { } publicclass TwoWheeler extends Vehicle { } publicclass WagonR extends FourWheeler { } Packages and Interfaces package interfaces_2.pack1; importinterfaces_2.pack2.Balance; publicclassCaller { publicstaticvoidmain(Stringargs[]) { Balance obj[] =newBalance[3]; obj[0] = newBalance("Saifur",100); obj[1] = newBalance("hasan",5000); obj[2] = newBalance("sazzad",100000); //obj[0].show(); //obj[1].show(); //obj[2].show(); for(inti = 0;i b) = "+ (a > b)); boolean c = (a < b); System.out.println("c = (a < b) = "+ c); } } Char class ex1 { public static void main(String args[]) { char ch1 = 'A', ch2 = 65; System.out.println("ch1 = "+ ch1); System.out.println("ch1 = "+ ch2); } } Int Integer Data Type : 1. Integer Data Type is used to store integer value. 2. Integer Data Type is Primitive Data Type in Java Programming Language. 3. Integer Data Type have respective Wrapper Class Integer. 4. Integer Data Type is able to store both unsigned ans signed integer values so Java opted signed, unsigned concept of C/C++. Class IntDemo { public static void main(String args[]) { int number=0; System.out.println("Total Number : " + number); } } Explanation : 1. Primitive Variable can be declared using int keyword. 2. Though Integer contain default Initial Value as 0 , still we have assign 0 to show assignment in Java. 3. + operator is used to concatenate 2 strings. 4. Integer is converted into String internally and then two strings are concatenated. Float class ex1 { public static void main(String args[]) { float a = 3.1415F, b = 5.3432923423f; System.out.println("a = "+ a); System.out.println("b = "+ b); } } Double class ex1 { public static void main(String args[]) { double a = 3.1415, b = 5.3432923423; System.out.println("a = "+ a); System.out.println("b = "+ b); } } Double & Float class ex1 { public static void main(String args[]) { float a = 9E5f; double b = 9E5; System.out.println("a = "+ a); System.out.println("b = "+ b); } } Type conversion & cast operation class ex1 { public static void main(String args[]) { int a = 14; float b = 3.1413424f; int c = a % (int)b ; System.out.println("c = "+ c); }
  12. 57. 56 } Variable Input/Output import java.io.*; class ex1 { public static void main(String args[]) { DataInputStream in = new DataInputStream(System.in); char ch; try{ System.out.print("Enter a character : "); ch = (char) System.in.read(); System.out.println("You have entered : "+ ch); } catch (Exception e){} } } import java.io.*; class ex1{ public static void main(String[] args){ try{ InputStreamReader IN = new InputStreamReader(System.in); BufferedReader BR = new BufferedReader(IN); String s = BR.readLine(); System.out.println(s); } catch(Exception E){} } } import java.io.*; class ex1{ public static void main(String[] args){ try{ InputStreamReader IN = new InputStreamReader(System.in); BufferedReader BR = new BufferedReader(IN); System.out.print("Enter Your age : "); String s = BR.readLine(); int age = Integer.parseInt(s); System.out.println("Your age is : " + age); } catch(Exception E){} } } Type conversion String s = BR.readLine(); int age = Integer.parseInt(s); String s = BR.readLine(); float age = Float.parseFloat(s); Chapter 2 (Variables & Data Types)
  13. 58. 57 Chapter 3 (Control Statements) switch() import java.io.BufferedReader; import java.io.InputStreamReader; class ex1{ public static void main(String[] args){ try{ InputStreamReader IN = new InputStreamReader(System.in); BufferedReader BR = new BufferedReader(IN); System.out.print("Enter your academic year : "); String s = BR.readLine(); int year = Integer.parseInt(s); switch(year){ case 1: System.out.println("This is first year"); break; case 2: System.out.println("This is Second year");
  14. 59. 58 break; case 3: System.out.println("This is third year"); break; case 4: System.out.println("This is fourth year"); break; default: System.out.println("You didn't entered Right year"); } } catch (Exception E){} } } Loop Fibonacci series import java.io.BufferedReader; import java.io.InputStreamReader; class ex1{ public static void main(String[] args){ try{ InputStreamReader IN = new InputStreamReader(System.in); BufferedReader BR = new BufferedReader(IN); System.out.print("Enter your how many fibonacci numbers : "); String s = BR.readLine(); int input = Integer.parseInt(s); int f0 = 0, f1 = 1, f2; for (int i = 0; i
  15. 60. 59 } Nested loop System.out.print("Enter number up to : "); String s = BR.readLine(); int input = Integer.parseInt(s); int i, j; for (i = 1 ; i