0% found this document useful (0 votes)
4 views15 pages

Java Cheatsheet

This document is a Java cheatsheet that covers fundamental concepts such as program structure, printing output, user input, comments, access modifiers, variables, control flow statements, object-oriented programming principles, constructors, arrays, strings, and exception handling. It provides code examples and explanations for each topic, making it a useful reference for Java programming. Key topics include the use of the Scanner class for user input, the significance of access modifiers, and the basics of exception handling with try-catch blocks.

Uploaded by

ameersohail0420
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)
4 views15 pages

Java Cheatsheet

This document is a Java cheatsheet that covers fundamental concepts such as program structure, printing output, user input, comments, access modifiers, variables, control flow statements, object-oriented programming principles, constructors, arrays, strings, and exception handling. It provides code examples and explanations for each topic, making it a useful reference for Java programming. Key topics include the use of the Scanner class for user input, the significance of access modifiers, and the basics of exception handling with try-catch blocks.

Uploaded by

ameersohail0420
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/ 15
Page tof 17 Pom eR Oe Toco Ce ec) Java Cheatsheet Java Program Structure Package Declaration (Optional) Seu Cee toc tac Impor Sem rstarsl eeu wean eee ate Tet PSEC CMC Lg Pes] Sec stant .Surt Printing Hello World The following code prints Hello World on the console — zy public class Helloworld { PORES cece CRMC Sura apie ScunaSusirg 4 Page2 of 17 public static void main The main() method is the starting point where JVM (Java Virtual Machine) begins executing the Java program. Output - System.out.printin() We can use Syste! .out.printin() to print something to the output console in Java. The printin() method The printin() method is used to print text in Java. A new line will be added after each call. Double Quotes In Java, double quotes are used to define string literals. can eae eC eo See oC ue aa rere The Print() Method The printin() method is used to print text in Java. A new line will be added after each call. Page3 of 17 User Input In Java, we use the Scanner class to get input from the user. It is in the java.util package. mport java.util.Scanner; re Sem TT aca ( Bast PCL Ts Java Comments Java comments are two types: single-line and multi-line comments. Single Line comment Single-line comments in Java start with double forward slashes // and text between them are ignored by the Java compiler. reat eS Multi-line Comments Multi-line comments in Java start with /* and end with */ and text between is ignored by the Java compiler. Access Modifiers in Java In Java, access modifiers are keywords used to set the accessibility of classes, methods, constructors, and fields, Types of Access Modifiers = Public - Can be accessed from any other class or package. = Private — Restricted to the defining class only; not accessible from outside. Paged of 17 ™ Protected — Accessible within the same package and by subclasses,even in different packages. = Default (no modifier) — Accessible only within classes in the same package. Variables Java Variables are containers that hold data values, with each variable being defined according to its assigned data type Types of Variables = Local Variables — A local variable is defined within a method, block, or constructor and is only accessible within that specific scope. = Instance Variables — Instance variables are non-static and are declared within a class but outside of any method, constructor, or block. = Static Variables — Static variables are declared using the static keyword within a class, outside of any method, constructor, or block. Built-in Type Variables The eight primitives defined in Java are int, byte, short, long, float, double, boolean, and char. byte byte is a primitive data type that only takes up 8 bits of memory. It can store numbers from -128 to 127. long Long is another primitive data type related to integers that can store whole numbers from -9223372036854775808 to 9223372036854775808, long takes up 64 bits of memory. float The float keyword is a data type that can store fractional numbers from 3.4038 to 3.4e+038 char Char is a 16-bit integer representing a Unicode-encoded character. Page of 17 int The int keyword is a primitive data type that can store numbers from -2147483648 to 2147483647 short The short keyword is a data type that can store numbers from -32768 to 32767. Control Flow If-Else Statement ent executes a block of code based on a condition. Switch Statement The switch statement selects one of many code blocks to be executed, It is similar to the if-else-if ladder statement. itch (day) { For Loop The Java for loop is used to iterate a block of code a specified number of times. While Loop The Java while loop is used to iterate a block of code while a condition is tru Ree ans Break Statement The Java break statement is used to terminate the current flow of the program at specified conditions. z PU SeCRSEES Uc sci aG public static void main(String[] args) { for(int i=1;i<=10;i++){ Icha Ne Tua aes Pere yy Secunia Continue Statement The Java continue statement is used to continue the current flow of the program. It is used to jump to the next part of the program. y Eriaet ContinueExample { EUSEtS id CTS Uane und a for(int i=1;i<=10;i++){ rece Sac Pree Me eee + Bs (i)s Java OOP Concepts 1. Classes and Objects ™ Class — A blueprint for creating objects. = Object - An instance of a class. 2. Inheritance Inheritance allows a class to inherit fields and methods from another class. Example Ue co Pe Pecos Era Ying Poteet st) [steer ae Cat cat = new Cat(); ou Pea} OTA Example Carve (ome Carry ane lone Se tarse rem rtd Pek Laan (SK) EC ECM rera myDog. sound(); myCat.sound(); GCM Com TLC rae Suen one new Dog()5 ew Cat()5 OMe ee cy CNet eee 4. Encapsulation Encapsulation Is the technique of wrapping data (variables) and code (methods) together as a single unit. Example by eeCE TCT Steet CEE PTS BCan Te: (double amount) { if (amount > @) { Pore sy Petar aed fer ae CTs public class Main EUS E tates) Crue Woe Cri een a aa RCE tae LO Era ( 3 vu RTS GCE ac COVELL) 5. Abstraction Open Compiler OS eas Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object. Example Eee ct OF; Page 10 of 17 Pcie Tone See a Sans PTSEtCRoe ear tne¢ Sirsa cee ra ae CeO eee rare) Constructors In Java, a constructor is a code block that initializes a new class instance. It is called when an object is created, allocating memory for it. Types of Constructors = Default Constructor — This type of constructor does not require any parameters If no constructor is explicitly declared in a class, the compiler automatically generates a default constructor with no arguments. = Parameterized Constructor — This type of constructor requires parameters and is used to assign custom values to a class's fields during initialization. Arrays Arrays are data structures that store multiple values of the same data type in contiguous memory locations. Single-Dimensional Arrays Freee Pe ORE Example 2 public class SingleDimensional { PUTER estan] CiSUra neu oes nt[] arr = ne A ear et (or Ge Multi-Dimensional Arrays Arrays can also be multi-dimensional, allowing the storage of data in a matrix format. Here is a Java program to implement 2-Dimensional arrays — z cae Probes Ds cucr cay ane EUSEtS vst} (String args[]) { trata Oe Page 12 of 17 PW cee) Saar espe CL aT ED Ing (arr[i][5] + 5 Seu Os Strings Java strings represent a sequence of characters. String Methods . — Returns the length of the string. . — Returns the character at the specified index. . — Returns a substring from the specified index to the end. . — Returns the index of the first occurrence of the specified substring. . — Converts the string to lowercase. . — Converts the string to uppercase. . — Removes leading and trailing whitespace. String Concatenation String concatenation is the process of combining two or more strings into a single string. The + Operator String str1 = "Hello, ist sores Sst a eee a The concat() Method string ast string Page 13 of 17 String Comparison When comparing strings in Java, you need to be aware of the difference between comparing string references and string content. Using equals() Method String str1 = new String(“Hello") Raster ee ees tt Pest iReRSU saci eee Css Ree coo CICA Chae Exception Handling java exception handling is a process to handle runtime errors to maintain the flow of the program Java try-catch block The Try-cateh block is used to handle the code that may throw the exception. Syntax Tay atch (Exception e) as Java finally block The finally block is used to execute the specific code whether the exception is handled or not. Example 2 public class FinallyExample { PSE cota Ot) (oasurieiel isoane cus ("Inside try block."); pa 0 Cee CWA CR eeu ret) } catch (Arithmeticexception e) { Ba cus Decca Cea } finally ¢ Sa cunis GUreR ae cao Java throw Exception The Java throw keyword is used to throw an exception explicitly. Syntax Example zy public class ThrowExample { public static void [ele en tee cna leer Ce ea ELM SC) pec mesB LU Tica st OE cue e Ger aes net } Beret eC Mata TAC Uae OI FCC CG SRR eee tunes eC Gr Rae Ca d SACU usar Cn cece TOP TUTORIALS CUR cT SCO MImc ecu] Te RECT loa Cau) Pemcur ec Coat aCe ac omens TRENDING TECHNOLOGIES Cloud Computing Tutorial eae ac eee aC lamer) eae Re ar Rac Dryer at Cem Ca MMe ccc SDLC Tutorial

You might also like