





































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
CORE JAVA CHEATSHEET. Object Oriented Programming Language:based on the concepts of “objects”. Open Source: Readily available for development.
Typology: Summaries
1 / 45
This page cannot be seen from the preview
Don't miss anything!






































Object Oriented Programming Language: based on the concepts of “objects”. Open Source: Readily available for development. Platform-neutral: Java code is independent of any particular hardware or software. This is because Java code is compiled by the compiler and converted into byte code. Byte code is platform-independent and can run on multiple systems. The only requirement is Java needs a runtime environment i.e, JRE, which is a set of tools used for developing Java applications. Memory Management: Garbage collected language, i.e. deallocation of memory. Exception Handling: Catches a series of errors or abnormality, thus eliminating any risk of crashing the system. THE JAVA BUZZWORDS Java was modeled in its final form keeping in consideration with the primary objective of having the following features: Simple, Small and Familiar Object-Oriented Portable and Platform Independent Compiled and Interpreted Scalability and Performance Robust and Secure Architectural-neutral High Performance Multi-Threaded Distributed Dynamic and Extensible
Primitive Data Types Data Type Default Value Size (in bytes) 1 byte = 8 bits boolean FALSE 1 bit char “ “ (space) 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0 8 byte float 0.0f 4 byte double 0.0d 8 byte Non-Primitive Data Types Data Type String Array Class Interface TYPECASTING It is a method of converting a variable of one data type to another data type so that functions can process these variables correctly. Java defines two types of typecasting: ● Implicit Type Casting (Widening)
Local Variable Global or Instance Variable Static Variable Declared and initialized inside the body of the method, block or constructor. Declared inside the class but outside of the method, block or constructor. If not initialized, the default value is 0. Declared using a “static” keyword. It cannot be local. It has an access only within the method in which it is declared and is destroyed later from the block or when the function call is returned. Variables are created when an instance of the class is created and destroyed when it is destroyed. Variables created creates a single copy in the memory which is shared among all objects at a class level. class TestVariables { int data = 20; // instance variable static int number = 10; //static variable void someMethod() { int num = 30; //local variable } } RESERVED WORDS Also known as keywords, are particular words which are predefined in Java and cannot be used as variable or object name. Some of the important keywords are :
Keywords Usage abstract used to declare an abstract class. catch used to catch exceptions generated by try statements. class used to declare a class. enum defines a set of constants extends indicates that class is inherited final indicates the value cannot be changed finally used to execute code after the try-catch structure. implements used to implement an interface. new used to create new objects. static used to indicate that a variable or a method is a class method. super used to refer to the parent class. this used to refer to the current object in a method or constructor. throw used to explicitly throw an exception. throws used to declare an exception. try block of code to handle exception METHODS IN JAVA The general form of method : type name (parameter list) { //body of the method //return value (only if type is not void) } Where type - return type of the method name - name of the method parameter list - sequence of type and variables separated by a comma return - statement to return value to calling routine
break; case 1 : System.out.println("Rainy"); break; case 2 : System.out.println("Cold"); break; case 3 : System.out.println("Windy"); break; default : System.out.println("Pleasant"); } } } LOOPS IN JAVA Loops are used to iterate the code a specific number of times until the specified condition is true. There are three kinds of loop in Java : For Loop Iterates the code for a specific number of times until the condition is true. class TestForLoop { public static void main (String args[]) { for(int i=0;i<=5;i++) System.out.println("*"); } } While Loop If condition in the while is true the program enters the loop for iteration. class TestWhileLoop { public static void main (String args[]) { int i = 1; while(i<=10) { System.out.println(i); i++; } } } Do While Loop
The program enters the loop for iteration at least once irrespective of the while condition being true. For further iterations, it is depends on the while condition to be true. class TestDoWhileLoop { public static void main (String args[]) { int i = 1; do { System.out.println(i); i++; }while(i<=10); } } JAVA OOPS CONCEPTS An object-oriented paradigm offers the following concepts to simplify software development and maintenance.
1. Object and Class Objects are basic runtime entities in an object-oriented system, which contain data and code to manipulate data. This entire set of data and code can be made into user-defined data type using the concept of class. Hence, a class is a collection of objects of a similar data type. Example: apple, mango, and orange are members of class fruit. 2. Data Abstraction and Encapsulation The wrapping or enclosing up of data and methods into a single unit is known as encapsulation. Take medicinal capsule as an example, we don’t know what chemical it contains, we are only concerned with its effect. This insulation of data from direct access by the program is called data hiding. For instance, while using apps people are concerned about its functionality and not the code behind it. 3.Inheritance Inheritance provides the concept of reusability, it is the process by which objects of one class (Child class or Subclass) inherit or derive properties of objects of another class (Parent class). Types of Inheritance in Java: Single Inheritance
System.out.println("Contents of objB: "); objB.showij(); objB.showk(); System.out.println(); System.out.println("Sum of i, j and k in objB:"); objB.sum(); } } Some limitations in Inheritance : ● Private members of the superclass cannot be derived by the subclass. ● Constructors cannot be inherited by the subclass. ● There can be one superclass to a subclass.
4. Polymorphism Defined as the ability to take more than one form. Polymorphism allows creating clean and readable code. In Java Polymorphism is achieved by the concept of method overloading and method overriding, which is the dynamic approach. ● Method Overriding In a class hierarchy, when a method in a child class has the same name and type signature as a method in its parent class, then the method in the child class is said to override the method in the parent class. In the code below, if we don’t override the method the output would be 4 as calculated in ParentMath class, otherwise, it would be 16. class ParentMath { void area() { int a =2; System.out.printf("Area of Square with side 2 = %d %n", a * a); System.out.println(); } } class ChildMath extends ParentMath {
void area() { int a =4; System.out.printf("Area of Square with side 4= %d %n", a * a); } public static void main (String args[]) { ChildMath obj = new ChildMath(); obj.area(); } } ● Method Overloading Java programming can have two or more methods in the same class sharing the same name, as long as their arguments declarations are different. Such methods are referred to as overloaded, and the process is called method overloading. Three ways to overload a method :
Rectangle rec = new Rectangle(); //object of child class circle Circle cir = new Circle(); //calling the area methods of all child classes to get the area of different objects s.area(); sq.area(length); rec.area(length,breadth); cir.area(length); } } ABSTRACT CLASS Superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to implement its methods. abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class Abstract { public static void main(String args[]) { B b = new B(); b.callme(); b.callmetoo(); } } INTERFACES
A class’s interface can be full abstracted from its implementation using the “interface” keyword. They are similar to class except that they lack instance variables and their methods are declared without any body. ● Several classes can implement an interface. ● Interfaces are used to implement multiple inheritances. ● Variables are public, final and static. ● To implement an interface, a class must create a complete set of methods as defined by an interface. ● Classes implementing interfaces can define methods of their own. interface Area { final static float pi = 3.14F; float compute(float x , float y); } class Rectangle implements Area { public float compute (float x, float y) { return (x*y); } } class Circle implements Area { public float compute (float x, float y) { return (pi * x * x); } } class InterfaceTest { public static void main (String args[]) { float x = 2.0F; float y = 6.0F; Rectangle rect = new Rectangle(); //creating object Circle cir = new Circle(); float result1 = rect.compute(x,y);
vol = mybox2.volume(); System.out.println("Volume is " + vol); } } Parameterized : Used to initialize the fields of the class with predefined values from the user. class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { return width * height * depth; } } class BoxVolP { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; vol = mybox1.volume(); System.out.println("Volume is " + vol); vol = mybox2.volume(); System.out.println("Volume is " + vol); } } ARRAYS IN JAVA
Array is a group of like-type variables that are referred by a common name, having continuous memory. Primitive values or objects can be stored in an array. It provides code optimization since we can sort data efficiently and also access it randomly. The only flaw is that we can have a fixed-size elements in an array. There are two kinds of arrays defined in Java:
for(int a=0;a<=m1.length;a++) { for(int b=0;b<=m2.length;b++) { sum[a][b] = m1[a][b] + m2[a][b]; System.out.print(sum[a][b] + " "); } System.out.println(); } } } STRINGS IN JAVA ● Strings are non-primitive data type that represents a sequence of characters. ● String type is used to declare string variables. ● Array of strings can also be declared. ● Java strings are immutable, we cannot change them. ● Whenever a string variable is created, a new instance is created. Creating String Using Literal Using new keyword String name = “John” ; String s = new String(); String Methods The String class which implements CharSequence interface defines a number of methods for string manipulation tasks. List of most commonly used string methods are mentioned below:
Method Task Performed toLowerCase() converts the string to lower case toUpperCase() converts the string to upper case replace(‘x’ , ‘y’) replaces all appearances of ‘x’ with ‘y’ trim() removes the whitespaces at the beginning and at the end equals() returns ‘true’ if strings are equal equalsIgnoreCase() returns ‘true’ if strings are equal, irrespective of case of characters length() returns the length of string CharAt(n) gives the nth character of string compareTo() returns negative if string 1 < string 2 positive if string 1 > string 2 zero if string 1 = string 2 concat() concatenates two strings substring(n) returns substring returning from character n substring(n,m) returns a substring between n and ma character. toString() creates the string representation of object indexOf(‘x’) returns the position of first occurrence of x in the string. indexOf(‘x’,n) returns the position of after nth position in string ValueOf (Variable) converts the parameter value to string representation Program to show Sorting of Strings: class SortStrings { static String arr[] = { "Now", "the", "is", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "their", "county" }; public static void main(String args[]) { for(int j = 0; j < arr.length; j++) { for(int i = j + 1; i < arr.length; i++) { if(arr[i].compareTo(arr[j]) < 0) { String t = arr[j]; arr[j] = arr[i];