0% found this document useful (0 votes)
10 views

Java Cheat Sheet for WT

This document serves as a Java cheat sheet covering key concepts such as the final, static, and super keywords, constructors, runtime polymorphism, arrays, characteristics of Java, dynamic method dispatch, abstract classes, and the principles of object-oriented programming (OOP). It provides examples to illustrate each concept, highlighting Java's features like platform independence, robustness, and security. The document emphasizes the importance of encapsulation, inheritance, polymorphism, and abstraction in Java programming.

Uploaded by

shizu8145
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java Cheat Sheet for WT

This document serves as a Java cheat sheet covering key concepts such as the final, static, and super keywords, constructors, runtime polymorphism, arrays, characteristics of Java, dynamic method dispatch, abstract classes, and the principles of object-oriented programming (OOP). It provides examples to illustrate each concept, highlighting Java's features like platform independence, robustness, and security. The document emphasizes the importance of encapsulation, inheritance, polymorphism, and abstraction in Java programming.

Uploaded by

shizu8145
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Java cheat sheet for wt

1. Java Final Keyword:


The final keyword in Java is used to restrict the user from changing the
value of a variable, declaring a method that cannot be overridden by
child classes or declaring a class that cannot be inherited. Once the final
keyword is used on any entity, it cannot be changed.

Example:
public class Example {
public final int NUMBER = 10; // final variable
public final void display() { // final method
System.out.println("This is a final method.");
}
}
public class SubExample extends Example {
public void display() { // compile-time error
System.out.println("This method cannot be overridden.");
}
}

2. Java Static Keyword:


The static keyword in Java is used to define a class-level variable or
method that can be accessed without creating an object of the class. The
static variable or method belongs to the class rather than a specific
instance of the class.

Example:
public class Example {
public static int NUMBER = 10; // static variable
public static void display() { // static method
System.out.println("This is a static method.");
}
}
public class SubExample extends Example {
public void show() {
System.out.println(NUMBER); // accessing static variable
display(); // accessing static method
}
}
J3. ava Super Keyword:
The super keyword in Java is used to access the parent class constructor,
parent class methods, and parent class variables. It is mostly used in
inheritance where a child class is derived from a parent class.

Example:
public class ParentClass {
public void display() {
System.out.println("This is a parent class method.");
}
}
public class ChildClass extends ParentClass {
public void display() {
super.display(); // accessing parent class method
System.out.println("This is a child class method.");
}
}

4. Constructors in java:-
In Java, a constructor is a special method that is used to initialize objects
of a class. It is called when an object of a class is created, and its main
purpose is to set the initial values of the object's instance variables.
Constructors have the same name as the class in which they are defined,
and they don't have a return type.

There are three types of constructors in Java:

Default constructor: A default constructor is a constructor that takes no


arguments. If a class doesn't have any constructor defined explicitly, Java
automatically provides a default constructor for that class. It initializes
all instance variables to their default values (e.g., 0 for integers, false for
booleans, null for objects).
Example:
public class Person {
String name;
int age;
// Default constructor
public Person() {
}
}
Parameterized constructor: A parameterized constructor is a constructor
that takes one or more arguments. It is used to set the initial values of
the object's instance variables based on the values passed as arguments.
Example:
public class Person {
String name;
int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

Copy constructor: A copy constructor is a constructor that takes an


object of the same class as a parameter and creates a new object with
the same values as the parameter object. It is used to create a copy of an
existing object.
Example:
public class Person {
String name;
int age;
// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}

Constructors are important in Java because they ensure that objects are
properly initialized before they are used. They also make it easy to
create new objects with different initial values, and to create copies of
existing objects.

5. Java achieves runtime polymorphism through method overriding.


Method overriding allows a subclass to provide its own implementation
of a method that is already provided by its parent class. In order for
method overriding to occur, the method name, parameter types, and
return type must be exactly the same in the subclass as in the parent
class. The subclass must also have an IS-A relationship with the parent
class.

Here is an example that demonstrates runtime polymorphism through


method overriding in Java:

class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Meow");
}
}

public class Main {


public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound();
animal2.makeSound();
}
}
In this example, we have an Animal class with a makeSound() method.
We also have two subclasses Dog and Cat that override the makeSound()
method with their own implementations.

In the main() method, we create two Animal objects, one of type Dog
and the other of type Cat. When we call the makeSound() method on
each object, Java will use the appropriate implementation of the method
based on the actual type of the object at runtime. This is known as
dynamic method dispatch.

So, when we run this program, it will output:


Woof
Meow

This is an example of runtime polymorphism because the makeSound()


method is called on the Animal objects at runtime, and Java is able to
determine which implementation of the method to use based on the
actual type of the object.

5. Arrays in Java and C share some similarities but also have some
differences.

One major difference is that in Java, arrays are objects, whereas in C,


arrays are just blocks of memory allocated for a certain type of data.
Java arrays are implemented as objects and provide many built-in
methods, such as length(), which returns the number of elements in the
array.

Here's an example to illustrate the difference between Java and C arrays:

Java:
int[] arr = new int[5]; // create an integer array of size 5
arr[0] = 1; // set the first element to 1
arr[1] = 2; // set the second element to 2
System.out.println(arr.length); // prints 5

C:
int arr[5]; // create an integer array of size 5
arr[0] = 1; // set the first element to 1
arr[1] = 2; // set the second element to 2
int len = sizeof(arr)/sizeof(arr[0]); // calculate the length of the array
printf("%d", len); // prints 5

In Java, we declare an array using the new keyword and specify its size.
We can then access the elements of the array using square brackets [].
We can also use the built-in method length() to get the length of the
array.

In C, we declare an array by specifying its size in square brackets []. We


can access the elements of the array using square brackets []. To get the
length of the array, we can calculate the size of the array in bytes using
sizeof() and divide it by the size of one element of the array.

One key difference is that in Java, arrays are objects, while in C, arrays
are a type of data structure. This means that arrays in Java can have
methods and be manipulated using object-oriented principles, while in C,
arrays are typically manipulated using pointers.

One key difference between these two examples is the placement of the
square brackets. In Java, the brackets come after the data type, while in
C, they come after the variable name.

Another difference between Java and C arrays is that in Java, arrays have
a fixed size that is specified when the array is created. In C, arrays can
have a fixed size, but they can also be dynamically allocated at run-time
using functions like malloc() and calloc().

Overall, while there are some similarities between arrays in Java and C,
there are also some significant differences that reflect the different
programming paradigms of the two languages.

6. Characteristics of Java:-

Java is a popular programming language used for developing a wide


range of applications. Some of the key characteristics of Java include:

Object-Oriented: Java is an object-oriented programming language,


which means it focuses on creating objects and their interactions to
build software applications.

Platform Independent: One of the most significant features of Java is


that it is platform-independent, which means that a Java program can
run on any platform, regardless of the hardware or software
environment.
Simple: Java is designed to be simple and easy to learn, with a syntax
that is similar to that of C++ but with fewer low-level features.

Robust: Java is a robust language with built-in mechanisms for handling


errors, exceptions, and memory management. It also includes automatic
garbage collection, which frees developers from having to manage
memory manually.

Secure: Java is designed with security in mind and includes features like
sandboxing, which allows applications to run in a restricted environment
and prevents them from accessing system resources.

Multithreaded: Java supports multithreading, which means that multiple


threads of execution can run simultaneously within the same program,
improving performance and responsiveness.

Portable: Because Java is platform-independent, it is highly portable,


which means that applications written in Java can be easily moved from
one platform to another without having to recompile the code.

Distributed: Java includes support for distributed computing, which


means that applications can be built that run on multiple systems and
communicate with each other over a network.

Overall, these characteristics make Java a popular language for building


robust, secure, and scalable applications that can run on a wide range of
platforms and devices.

7. Dynamic method dispatch is a mechanism in Java that enables a


program to call an overridden method of an object at runtime, rather
than at compile time. This mechanism is also known as runtime
polymorphism or late binding.

When a subclass overrides a method of its superclass, and an object of


the subclass is assigned to a superclass reference variable, then the
overridden method of the subclass is called through the superclass
reference variable. This is possible because the method call is resolved at
runtime, based on the actual type of the object being referred to, rather
than the declared type of the reference variable.
For example, consider the following code:

class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Cat is meowing");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Test {
public static void main(String[] args) {
Animal animal1 = new Cat();
animal1.makeSound(); // Output: Cat is meowing

Animal animal2 = new Dog();


animal2.makeSound(); // Output: Dog is barking
}
}

In this example, the Animal class has a method called makeSound(). The
Cat and Dog classes override this method to provide their own
implementation. In the main() method, we create an object of the Cat
class and assign it to an Animal reference variable. Similarly, we create
an object of the Dog class and assign it to another Animal reference
variable. When we call the makeSound() method on these reference
variables, the overridden methods of the Cat and Dog classes are called,
respectively. This is an example of dynamic method dispatch in Java.
8. Abstract Class:-
In Java, an abstract class is a class that is declared abstract and cannot
be instantiated. It can only be used as a base class for other classes that
extend it. Abstract classes provide a way to define a common interface
for a set of subclasses. It is like a blueprint for the subclasses, providing a
skeleton or template for them to follow.

An abstract class may contain both abstract and concrete methods.


Abstract methods are declared but not defined, while concrete methods
are defined with an implementation. Subclasses of an abstract class
must implement all abstract methods of the parent class.

Some of the characteristics of abstract classes are:

An abstract class cannot be instantiated directly; it can only be used as a


superclass for other classes.
An abstract class may contain abstract and/or concrete methods.
Abstract methods must be implemented by subclasses.
An abstract class may contain instance variables.
Abstract classes can have constructors, but they cannot be used to
instantiate objects directly.
A class can extend only one abstract class at a time, but it can implement
multiple interfaces.
Example:
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract void makeSound();
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void makeSound() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
public void makeSound() {
System.out.println("Meow!");
}
}
In the above example, Animal is an abstract class with an abstract
method makeSound(). The Dog and Cat classes extend the Animal class
and implement the makeSound() method.

In Java, a class is a blueprint or template for creating objects. It defines


the properties and behavior of objects that belong to that class.

For example, let's say we want to create a class called Car which
represents a car in a program. The Car class would have properties such
as make, model, year, color, and methods such as start(), stop(),
accelerate(), brake(), etc.

Once we define the Car class, we can create objects (or instances) of the
Car class. Each object will have its own set of properties and can perform
its own set of behaviors. For example, we can create an object of the Car
class called myCar, with properties such as make = "Toyota", model =
"Camry", year = 2022, color = "Red". We can then call the methods of
the myCar object, such as myCar.start(), myCar.accelerate(), etc.

In summary, a class defines the properties and behaviors of a group of


objects, while an object is an instance of a class with its own unique set
of properties and behaviors.
9. OOPs in java:-

OOPs stands for Object-Oriented Programming, which is a programming


paradigm based on the concept of objects. In Java, everything is
considered to be an object, and the program is designed to manipulate
these objects.

The four pillars of OOPs in Java are:

Encapsulation: It is a mechanism of wrapping data and code together as


a single unit. It is used to protect the data from unauthorized access by
providing access only through the methods of the class. In Java, we use
access modifiers like public, private, and protected to provide
encapsulation.
Example:
public class BankAccount {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}

Inheritance: It is a mechanism of creating a new class from an existing


class. The new class inherits the properties and methods of the existing
class. It helps in reusing the code and also promotes code extensibility.
Example:
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: Animal is eating
dog.bark(); // Output: Dog is barking
}
}

Polymorphism: It is a mechanism of performing a single action in


different ways. In Java, polymorphism is achieved through method
overloading and method overriding.
Example:
public class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat is meowing");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound(); // Output: Dog is barking
animal2.makeSound(); // Output: Cat is meowing
}
}

Abstraction: It is a mechanism of hiding the implementation details and


showing only the essential features of the object. In Java, we use
abstract classes and interfaces to achieve abstraction.
Example:
public abstract class Shape {
public abstract double area();
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double area() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(5, 10);
System.out.println("Area of Circle: " + shape1.area()); // Output:
Area of Circle: 78.53981633974483
System.out.println("Area of Rectangle: " + shape2.area()); // Output
Encapsulation is one of the fundamental concepts of object-oriented
programming (OOP) that describes the principle of data hiding. It refers
to the practice of hiding internal data and methods of an object from the
outside world and providing access to them only through publicly
exposed methods, which are also known as getters and setters.
Encapsulation allows the programmer to implement the concept of data
abstraction by restricting access to the implementation details of an
object and exposing only what is necessary.

In Java, encapsulation is achieved through the use of access modifiers,


such as private, public, and protected. Private members of a class are
not accessible outside the class, while public members can be accessed
from anywhere. Protected members can be accessed by classes in the
same package or by derived classes.

The following is an example of encapsulation in Java:


public class BankAccount {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
public double getBalance() {
return balance;
}
}
In this example, the balance variable is marked as private, which means
it is not accessible outside the BankAccount class. The deposit and
withdraw methods are public, which means they can be accessed from
outside the class. However, they modify the balance variable indirectly
through method calls, rather than directly accessing it. The getBalance
method is also public, but it only returns the value of the balance
variable and does not modify it. This is an example of encapsulation,
where the implementation details of the BankAccount class are hidden
from the outside world, and access to the balance variable is controlled
through publicly exposed methods.
INHERITANCE in java:-
Inheritance is a mechanism in object-oriented programming where a
class can inherit properties and behaviors from a parent class. The child
class or subclass can reuse the code from the parent class or superclass,
and also add new methods and properties specific to the child class.

There are several types of inheritance in Java:

Single inheritance: A subclass extends a single superclass. For example:


class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
In this example, Dog is a subclass of Animal. It inherits the eat() method
from Animal and adds a new method bark() specific to Dog.

Multi-level inheritance: A subclass extends another subclass. For


example:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Mammal extends Animal {
void move() {
System.out.println("Mammal is moving");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("Dog is barking");
}
}
In this example, Mammal is a subclass of Animal, and Dog is a subclass of
Mammal. Dog inherits both eat() and move() methods from its ancestors.

Hierarchical inheritance: Multiple subclasses extend a single superclass.


For example:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing");
}
}
In this example, both Dog and Cat are subclasses of Animal. They inherit
the eat() method from Animal, and add their own specific methods bark()
and meow().

Command Line Arguments in java:-


In Java, command line arguments are the parameters or inputs that are
passed to the main method of a Java program when it is run from the
command line. These arguments can be used to customize the behavior
of the program based on user input.

Command line arguments are passed to the main method of a Java


program as an array of strings, where each element of the array
represents a separate argument. The first element of the array (args[0])
is the first argument, the second element (args[1]) is the second
argument, and so on.

Here's an example of how to use command line arguments in Java:


public class CommandLineArgsExample {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No arguments provided");
} else {
System.out.println("Arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
}
In this example, the program checks whether any command line
arguments were provided. If no arguments were provided, it prints a
message saying so. If arguments were provided, it prints each argument
to the console.

For example, if we run the program with the following command line
arguments:

java CommandLineArgsExample arg1 arg2 arg3


The output will be:
Arguments:
arg1
arg2
arg3

Method Overloading: It is the feature of Java that allows a class to have


multiple methods with the same name, but with different parameters or
arguments. The method that gets called during runtime depends on the
number, order, and type of arguments passed. Here's an example:

public class Calculator {


public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
In the above example, the add() method is overloaded with three
different signatures. The first one takes two integers, the second one
takes two doubles, and the third one takes three integers.

Method Overriding: It is the feature of Java that allows a subclass to


provide its own implementation of a method that is already defined in
its superclass. The method in the subclass must have the same name,
return type, and parameters as the method in the superclass. Here's an
example:
public class Animal {
public void speak() {
System.out.println("Animal speaks");
}
}
public class Dog extends Animal {
public void speak() {
System.out.println("Dog barks");
}
}
In the above example, the Dog class overrides the speak() method of the
Animal class to provide its own implementation.

Final Keyword: It is a keyword in Java that is used to restrict the


modification of variables, methods, and classes. If a variable is declared
as final, its value cannot be changed. If a method is declared as final, it
cannot be overridden by a subclass. If a class is declared as final, it
cannot be subclassed. Here's an example:
public class Circle {
public final double PI = 3.14159;
public final void printArea() {
System.out.println("Area is calculated using PI");
}
}
In the above example, the PI variable is declared as final, which means
its value cannot be changed. The printArea() method is also declared as
final, which means it cannot be overridden by a subclass.
Super Keyword: It is a keyword in Java that is used to refer to the
superclass of a subclass. It is used to call the constructor, methods, and
variables of the superclass. Here's an example:
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println("Animal speaks");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void speak() {
System.out.println("Dog barks");
}
}
In the above example, the Dog class calls the constructor of the Animal
class using the super keyword to initialize the name variable.

Constructor with Super Keyword: It is a feature of Java that allows a


subclass constructor to call the constructor of its superclass using the
super keyword. This is useful when the superclass constructor needs to
be called to initialize the instance variables of the subclass. Here's an
example:
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
}
public class Dog extends Animal {
String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
}
In the above example, the Dog class calls the constructor of the Animal
class using the `super

JVM (Java Virtual Machine) is an abstract machine that executes Java


bytecode. It is responsible for providing a runtime environment for Java
applications. The JVM architecture consists of several components, as
follows:

Class Loader: Class Loader is responsible for loading classes into the JVM.
It loads the bytecode of the class and creates an internal representation
of the class in the JVM.

Memory Area: Memory Area is a collection of various memory pools that


are used by the JVM during the execution of a Java application. It is
divided into three parts:

a. Heap Memory: Heap memory is the memory used for object


allocation. It is shared among all threads of the application.

b. Stack Memory: Stack memory is used for storing method-specific data.


Each method call creates a new frame in the stack memory.

c. Method Area: Method Area is used for storing class-level data, such as
the bytecode of the methods, constant pool, and static fields.

Execution Engine: Execution Engine is responsible for executing the


bytecode of the application. It consists of two parts:

a. Interpreter: Interpreter interprets the bytecode and executes the


instructions one by one.

b. Just-In-Time Compiler (JIT): JIT compiles the frequently used bytecode


into native machine code for faster execution.

Native Method Interface (NMI): Native Method Interface is used to call


the native methods of the underlying operating system.
Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
When we compile and run this code, the JVM executes the following
steps:

Class Loader loads the bytecode of the HelloWorld class into the JVM.
Memory Area allocates memory for the HelloWorld object in the heap
memory and memory for the main() method in the stack memory.
Execution Engine executes the bytecode of the main() method using the
interpreter.
Interpreter executes the System.out.println("Hello, World!") statement,
which prints "Hello, World!" to the console.
Native Method Interface is used to call the native methods of the
operating system for printing to the console.
This is a basic example of how the JVM architecture works.

Inner class in java:-


In Java, an inner class is a class that is defined inside another class. It is
used to encapsulate related functionality within a class and can access
private members of the outer class. There are four types of inner classes
in Java:

Nested inner class: A nested inner class is a class defined inside another
class. It can access all members of the outer class, including private
members. Here is an example:
public class OuterClass {
private int x = 10;
public class InnerClass {
public void printX() {
System.out.println("x = " + x);
}
}
}
// Create an instance of the outer class
OuterClass outer = new OuterClass();
// Create an instance of the inner class
OuterClass.InnerClass inner = outer.new InnerClass();
// Access a member of the inner class
inner.printX();

Static inner class: A static inner class is a nested class that is marked as
static. It does not have access to the instance variables of the outer class.
Here is an example:
public class OuterClass {
private static int x = 10;
public static class InnerClass {
public void printX() {
System.out.println("x = " + x);
}
}
}
// Create an instance of the inner class
OuterClass.InnerClass inner = new OuterClass.InnerClass();
// Access a member of the inner class
inner.printX();

Local inner class: A local inner class is a class defined inside a method or
block. It has access to the variables of the enclosing method or block,
but those variables must be final or effectively final. Here is an example:
public class OuterClass {
public void printMessage(String message) {
// Define a local inner class
class InnerClass {
public void print() {
System.out.println(message);
}
}
// Create an instance of the inner class
InnerClass inner = new InnerClass();
// Call a method of the inner class
inner.print();
}
}
// Create an instance of the outer class
OuterClass outer = new OuterClass();
// Call a method of the outer class
outer.printMessage("Hello, world!");

Anonymous inner class: An anonymous inner class is a class defined


without a name. It is typically used to implement an interface or extend
a class. Here is an example
public class OuterClass {
public void printMessage(final String message) {
// Create an instance of an anonymous inner class that implements
Runnable
new Runnable() {
public void run() {
System.out.println(message);
}
}.run();
}
}
// Create an instance of the outer class
OuterClass outer = new OuterClass();
// Call a method of the outer class
outer.printMessage("Hello, world!");

You might also like