View on GitHub

CC

CC practice and cheat sheets

Java Cheat Sheet

Everything you need to know to transition to Java from another language [work in progress]

Data types

float f1 = 35e3f;
double d1 = 12E4d;

Everything is a class

Everything ? Everything.

public class Stuff{
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}

If you decide to make the Stuff class public, it needs to be in a file called Stuff.java Else, you can have multiple non public classes in a file.

Sysout with System.out.println where System.out is the default output stream.

Alternatively, you can use System.out.print() if you don’t want a newline


Compile and Run !

Assuming you have a JDK setup

javac Stuff.java
java Stuff arg1 arg2

where arg1 and arg2 are your command line arguments which are passed into String args[] in the main function.

String Stuff

int number = 823;
System.out.println("Today’s lotto number is:  " + number);

String x = "Hello World";
char c = x.charAt(1);
int len = s.length;
String s1 = x.toLowerCase();

String test = "Programming in Java";
String result[]=test.split(" ");
char c[]=test.toCharArray();

char a[]= {'a','b','c'};
String s = new String(a);

System.out.println(test.contains("learning"));

compareTo returns

Tip: Think of compareTo is subtraction

Math

import java.lang.Math;

double res1 = Math.pow(base,power);
double res2 = Math.sqrt(base);
double ans = 10*Math.PI;

Stuff

System.arraycopy (src,srcindex, dest, destindex , length)
class xyz{
    public int x;
    public static int y;
}
xyz obj = new xyz();
obj.x;
xyz.y;

​ Alternatively, you can have a static block. Static initialisation blocks are executed when the class is loaded, and you can initialise static variables in those blocks.



public class Solution {

    static int B, H;
    static boolean flag = true;
    static{
        Scanner sc = new Scanner(System.in);
        B = sc.nextInt();
        H = sc.nextInt();

        if(B<=0 || H<=0){
            System.out.println("B and H must be posi");
            System.exit(0);
        }
    }

    public static void main(String[] args){
            if(flag){
                int area=B*H;
                System.out.print(area);
            }

        }//end of main

}//end of class


int arr[] = new int[10];

int constant_size = 18*2 + 5 ;
int p[] = new int[constant_size];

arr = new int[50];
// previous data is discarded

System.out.println(arr.length);
// arr.length is a property of the array, not a function

int[][] array2D = { {99, 42, 74, 83, 100}, 
                    {90, 91, 72, 88, 95}, 
                    {88, 61, 74, 89, 96}, 
                    {61, 89, 82, 98, 93}, 
                    {93, 73, 75, 78, 99}, 
                    {50, 65, 92, 87, 94}, 
                    {43, 98, 78, 56, 99} }; 

// or with varying size arrays
int[][] uneven = { { 1, 9, 4 }, 
                  { 0, 2}, 
                  { 0, 1, 2, 3, 4 } }; 

Error Handling

Keyword Description
try put code that might throw an exception in it
catch specify what kind of exception to catch and what to do once you catch it
finally block of code that always executes irrespective of an exception being thrown
throw can manually throw an exception
throws used in a function definition to state that this function might throw an exception
public void some_function() throws IOException {
  // some code that may throw an exception
}
.
.
.

try{  
    //code that may raise exception  
    throw new FileNotFoundException();
    int data=100/0;  
}
catch(Exception e){
  // this will always fire as the order of declaring exceptions matters
}
catch(ArithmeticException e)
{
  System.out.println(e);
  }  
finally{
  //stuff that will always execute
}

What if we want to chain exceptions one after the other ?


try{
    throw new ArithmeticException("divide by zero").cause(new SQLException("could not fetch data"));
}
catch(ArithmeticException e){
	System.out.print(e.getMessage());
    System.out.println(e.getCause());
}


User Input

import java.util.*

Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
    sc.nextLine();
    sc.nextInt();
    sc.nextFloat();
    sc.nextDouble();
    sc.nextLong();
    ...
}
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
String x = br.readLine();
.
.
.
br.close();

Packages

Inheritance and stuff

Types of Inheritance

class A{

}
class B extends A{

}
interface xyz{

}
class A implements xyz{

}

Nested Classes

class outer
{
	public String a;
	protected String b;
	private String c;
	class inner
	{
		public String in1;
		public void display() {
			System.out.println(a+b+c);
		}
	}
	
	public void displayout() {
		
		System.out.println(a+b+c);
		
	}
}
outer outobj = new outer();
outobj.displayout();
outer outobj = new outer();
outer.inner inobj = outobj.new inner();
inobj.display();

Static nested class

class outer
{
	public int a;
	public static int b;
	static class inner
	{
		public void display() {
			
			System.out.println("am the static class method");
			
		}
	}
}

outer.inner d = new outer.inner();
d.display();
Tired of declaring classes ?

Anonymous inner classes to the rescue

interface shape
{
	void displaymessage();
}

shape s = new shape()
{
       public void displaymessage()
       {
       System.out.println("hello message");
       }
};

s.displaymessage();

Finalize what ?

protected void finalize throws Throwable{}
String(Interg)public class demo {
  
    protected void finalize() throws Throwable
    {
        try {
  
            System.out.println("inside demo's finalize()");
        }
        catch (Throwable e) {
  
            throw e;
        }
        finally {
  
            System.out.println("Calling finalize method"
                               + " of the Object class");
  
            // Calling finalize() of Object class
            super.finalize();
        }
    }
}