[go: up one dir, main page]

0% found this document useful (0 votes)
3 views14 pages

Java Cheatsheet

This Java cheat sheet provides an overview of the Java programming language, covering key concepts such as JDK setup, data types, control structures, object-oriented programming principles, and methods. It includes examples for basic syntax, variable types, loops, inheritance, and encapsulation. The document serves as a quick reference for understanding essential Java features and programming practices.

Uploaded by

nayakanubhav1098
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Java Cheatsheet

This Java cheat sheet provides an overview of the Java programming language, covering key concepts such as JDK setup, data types, control structures, object-oriented programming principles, and methods. It includes examples for basic syntax, variable types, loops, inheritance, and encapsulation. The document serves as a quick reference for understanding essential Java features and programming practices.

Uploaded by

nayakanubhav1098
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
Java Cheat Sheet Introduction to Java Java is an object-oriented, platform-independent programming language used for building applications. It supports features like multi-threading, automatic memory ‘management, and secure execution of code. JDK Setup IDK (Java Development Kit) includes tools like the compiler (‘javac") and runtime environment (JRE). Installation: Download the JDK from [Oracle] (hutps://www.oracle.com/java/technologievjavase-downloads.htm)), Set JAVA_HOME" environment variable to the JDK Update “PATH? variable to include “JAVA_HOME/bin 3. First Code in Java public class HelloWorld | public static void main(String{] args) { System.out printin("Hello, World!"); © Compile: “javae HelloWorld java © Run: “java HelloWorld 4. How Jaya Works * Source code is compiled to bytecode using the ‘javac’ compiler + The JVM (ava Virtual Machine) interprets bytecode and executes it on any platform, making Java platform-independent, 5. Variables * Variables store data for processing, Java supports local, instance, and statie variables, # Syntax: “dataType variableName = value; + intage = 25; 6. Data Types * Primitive Types**: ‘byte’, ‘short’, ‘int’, ‘long’, “float’, ‘double’, ‘char’, “boolean” ‘+ Non-primitive Types**: Arrays, Classes, Interfaces, etc. + Exampl int num = 10; char letter: . Literals Fixed values assigned to variables. Example: “int a= 10;", “double d= 10.5; , boolean b = true;” . Type Conversion Implicit Conversion: Automatic type conversion by the compiler. Example: inta= 10; double b = a; // Implicit conversion from int to double Explicit Conversion (Casting)**: Manually converting one data type to another, Example: double x= 10, int y = (int) x; / Casting double to int ). Arithmetic Operators SE, F, 7, % (Addition, Subtraction, Multiplication, Division, Modulo) Example: int sum = 10 +5; //'sum = 15 10, Relational Operators © Exampk if(S>3)4 System.out printin("S is greater than 3"); Example: *&& (AND), ‘|! (OR), “! (NOT) boolean result = (5 > 3) && (8 > 6); 12, If Else * Executes a block of code based on a condition. + Exampl if (age >= 18) { System.out.printin("Eligible to vote"); J else { System.out.printin("Not eligible to vote"); 13, If Else If ‘+ Multiple conditions are checked sequentially, + Example: if (marks >= 90) { System.outprintin("A Grade"); } else if (marks >= 75) { System.out printhn("B Grade"); J else { System.out.printin("© Grade"); 14, Ternary Operator Shorthand for “itl Syntax: “condition ? exprl = Example: inta= 10, b= 20; int max =(a>b) 2azb; (max =20 15, Switch Statement + Simplifies code that has multiple conditions, + Example: int day = 3; switeh (day) { case 1: System.out.printin("Monday"); break; ccase 2: System.out printin("Tuesday"); break; case 3: System.out printin("Wednesday"); break: default: System.out printin( "Invalid Day"); 16, Need for Loop © Loops help in executing a block of code repeatedly as long as the condition is true 17, While Loop Repeats as long as the condition is tru. Exampl inti=0; while (i <5) { System.out.printin("i =" +i); 18, Do While Loop # Executes at least once, then checks the condition System.out.printin(*i =" + i); iH } while (i <5); 19. For Loop * Used for a definite number of iterations. + Example: for (inti System.out printin( 20. Which Loop to Use * For Loop: Use when the number of iterations is known, ‘+ While Loop: Use when you want to repeat until a condition changes. + Do-While Loop: Use when you want the loop to execute at least once. 21. Class and Object Theory * Class: Blueprint or template to create objects. * Object: Instance of a class with a state and behavior Example: class Car { // String eolor; // State void drive() { / Behavior System. out.printin("Driving.."); public class Main { public static void main(String{] args) { Car car = new Car(); // Object creation car.color = "Red car drive(); lds, and call methods practically. class Student { int id; String name; void display) { System.out printin(id +" " + name); ” public class Test { public static void main(String{] args) { Student 51 = new Student(); sLid= 101; sLname = "John" sl.display(); 23. JDK, JRE, JVM * IDK (Java Development Kit}: Contains tools to develop Java programs ‘* JRE (ava Runtime Environment): Provides libraries and JVM for running Java programs, * JVM (ava Virtual Machine): Converts bytecode into machine code and executes it 24, Methods © Block of code to perform a spi , invoked by calling it, Example: class MathOperations { intadalint a, int b) { return a+b; 8 Test { static void main(String[] args) { 25. Method Overloading Multiple methods with the same name but different parameters in the same class, © Example: class MathOperations { int add(int a, int b) { return a + by } double add(double a, double b) { return a+b; 26. Stack and Heap # Stack: Stores local variables and function calls. © Heap: Stores objects dynamically created during runtime, 27. Need of Array + Arrays store multiple elements of the same data type, reducing code complexity. 28. Creation of Array * Syntax: ‘dataType{] arrayName = new dataTypefsize]; + Example: int{] numbers = new int{S]; rnumbers[0] = 10; 29, Multi-Dimensional Array * Arrays containing arrays. E.g., 2D arrays for matrix representation. + Example: int(JQ) matrix 30, Jagged and 3D Array Jagged Array: Arrays with va ‘sample: int{J(] jaggedArray = new int(3] JaggedAsray{0] = new int[2]; // First row has 2 columns jaggedArray[1] = new int[3]; // Second row has 3 columns 3D Array: Array with three dimensions. xample: i(J[IU threeDArray = new int(2](3][4] 31. Drawbacks of Array © Fixed size, unable to change dynamically. * Only homogeneous data type storage, 32. Array of Objects Arrays storing object references. Example: class Student { name) { this.name = name; } public class Test { public static void main(String{] args) { ‘Student{] students = new Student{2}; students[0] = new Student("Alice"); students[1] = new Student("Bob’ 33, Enhaneed For Loop erates through arrays or collections without using an index. Example: int{] numbers = {10, 20, 30}; for (int mum : numbers) { System out.printin(num);} 34, What is String racters represented as objects of the “Str "Hello, World!" 35, Mutable vs Immutable String -Immutable: “String” - Once created, cannot be changed. Mutable: *StringBuilder’ or ‘StringBuffer’ ‘vample: String str = "Hello" immutable StringBuilder sb = new StringBuilder("Hello");_// Mutable sb.append(” World"); Buffer and StringBuffer: Thread-safe, slower. StringBuilder: Non-thread-safe, faster. Example: StringBuilder sb = new StringBuilder(” Hello"); sb.append(* World"); 37. Static Variable Belongs to the class rather than any object instance. Example: class Test { static int count = 0; 38, Static Method © Can access only static data members and call other static methods. + Example: class Test { static void display() { System.out.printin( "Static Method"); static Block Executes before the main method, used for initialization xample: class Test { static { yystem.out.printin( "Static Block"); 40. Encapsulation ‘* Bundling data (variables) and methods in a single unit (class) and restricting access using + Examph class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } 41, Getters and Setters jon: Used to access and update the private fields of a class. ‘ample: public class Student { private String name; WV Getter public String getName() { return name; M Setter public void setName(String name) { this.name = name: 42. this’ Keyword Definition: Refers to the current object instance. Examph public class Employee { private int id; public Employeetint id) { this.id =i; J/ this’ distinguishes between class attribute and parameter 43. Constructor + Definition: A special method invoked when an object is created. Used to initialize objects. + Example: public class Car { private String model; 1 Constructor public Car(String model) { this.model = model; 44. Default vs Parameterized Constructor Default Constructor: Constructor with no arguments, provided by Java if'no other constructor is defined, Parameterized Constructor: Takes arguments to initialize an object. Example: public elass Vehicle { private String type; 1! Default Constructor public Vehicle() { this.type = "Unknown’; 1! Parameterized Constructor public Vehicle(String type) { this.type = types } 45, Naming Conventions * Class Names: Use Pascal Case (e.g., ‘Student’, "EmployeeDetails’), © Variable and Method Names: Use camelCase (¢.g., ‘studentName’, ‘calculateTotal’) 46. Anonymous Object * Definition: An object created without being referenced by a variable, © Example: * new Car("Toyota").displayModel(); 47. What is Inheritance tion: Mechanism to acquire properties and behaviors of a parent class Example: public class Animal { void eat() { System.out printin( "Eating. public class Dog extends Animal { void bark() { System.outprintin("Barking..."); } 48. Need of Inheritance ‘* Purpose: Code reusability, method overriding, and to establish a parent-child relationship. wgle and Multilevel Inheritance * Single Inheritance: A class extends one superclass © Multilevel Inheritance: A class is derived from another derived class. Example: i/ Single Inheritance class A { } class B extends A { } w Mul mee class C extends B { } ‘50, Multiple Inheritance Definition: A class cannot extend more than one class in Java due to ambiguity (solved by interfaces), Example: interface A {} interface B { class C implements A, B { } |. “this’ and “super” Keyword this’: Refers to the current instance. ‘+ “super: Refers to the superclass instance and can invoke the superclass’s constructor ‘or methods, Example: class Animal { void sound() { System.out.printin(" Animal Soun class Dog extends Animal { void sound) { super.sound(); 1/ Calls Animal's sound method System.out printin("Dog Barks"); 52. Method Overt Definition: Subclass has a method with the same signature as a method in its Example: class Parent { void show() { System.outprintln("Parent show"); } class Child extends Parent { void show() { System.out.printin("Child show"); } 53. Packages Definition: Grouping related classes and interfaces together. Examph package com.mycompany.project; public class MyClass { } |. Access Modifiers + Types: ‘public’, ‘private’, ‘protected’, and default. * Purpose: Control visibility of classes, methods, and variables. 55, Polymorpl * Definition: Ability to present the same interface for different data types. © Types: Compile-time (method overloading) and Run-time (method overri © Example: class Animal { void sound) { System.out.printin("Generic Animal Sound"); } class Cat extends Animal { void sound) { System.out printin("Cat Meows"); } Method Dispatch * Definition: Method call resolved at runtime based on the object’s actual type. + Exampl Animal a= new Cat(; 1 Upeasting a.sound( 1/ Calls Cat's sound method 57. ‘final’ Keyword * Definition: Used to declare constants, prevent method overriding, and inheritance. © Exampl final class FinalClass { } // Cannot be subclassed. class Test { final void display() { } 1! Cannot be overridden 58. “Object” Class Methods ‘© “equals()': Compares two objects for equality. © “toString()’: Retums string representation of an object. * “hashCode()’: Retums hash code value for the object. 59, Upeasting and Downeasting Upcasting: Casting a subclass type to a superclass type. Downcasting: Casting a superclass type to a subelass type. Example: Animal a= new Cat0; 1/ Upeasting Cat e = (Cat) a; 1) Downeasting 60. Wrapper Class © Definition: Provides a way to use primitive data types as objects (e.g., “Integer’, “Character’). + Example: int num = 10; Integer obj = Integer.valucOf{num); #1 Boxing int n= obj.intVatue() i Unboxing, This cheat sheet covers the basic concepts and examples to help you quickly grasp the main OOP principles in Java. Let me know if you need more details or specific examples on any of these topics!

You might also like