├── .vscode ├── launch.json └── settings.json ├── README.md ├── conditionallogic └── conditionallogicexampledescriptions.md ├── loops └── loopsexampledescriptions.md ├── methods ├── accessmodifiertable.md ├── example1.java ├── example2.java ├── example3.java ├── methodexampledescriptions.md └── shareLoop.java ├── stringformatting ├── stringformattingexample1.java └── stringformattingexampledescriptions.md └── strings └── stringexampledescriptions.md /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "java", 9 | "name": "Launch example1", 10 | "request": "launch", 11 | "mainClass": "example1", 12 | "projectName": "javaforbeginners_d6da72fc" 13 | }, 14 | { 15 | "type": "java", 16 | "name": "Launch example2", 17 | "request": "launch", 18 | "mainClass": "example2", 19 | "projectName": "javaforbeginners_d6da72fc" 20 | }, 21 | { 22 | "type": "java", 23 | "name": "Launch example3", 24 | "request": "launch", 25 | "mainClass": "example3", 26 | "projectName": "javaforbeginners_d6da72fc" 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "markdownlint.config": { 3 | "MD028": false, 4 | "MD025": { 5 | "front_matter_title": "" 6 | } 7 | }, 8 | "java.project.sourcePaths": [ 9 | "methods", 10 | "stringformatting" 11 | ] 12 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaforBeginners -------------------------------------------------------------------------------- /conditionallogic/conditionallogicexampledescriptions.md: -------------------------------------------------------------------------------- 1 | # Conditional Logic Concepts 2 | 3 | Conditional logic helps to control the flow of a code in Java. It consists of the following components: 4 | 5 | * Test expression(s) 6 | * Body/code block to be executed 7 | 8 | ## Operators 9 | 10 | ### Logical operators 11 | 12 | * && AND operator 13 | * ! NOT operator 14 | * || OR operator 15 | * Order of evaluation - Paranthesis, NOT, AND, OR 16 | 17 | Examples: 18 | 19 | ```java 20 | boolean x = true || false; 21 | boolean y = false && true; 22 | 23 | System.out.println(!x); 24 | >> true 25 | ``` 26 | 27 | ### Conditional operators 28 | 29 | * \> greater than 30 | * \>= greater than or equal to 31 | * < less than 32 | * <= less than or equal to 33 | * == equal to 34 | * != not equal to 35 | 36 | ## if statement 37 | 38 | * Evaluates test expression given in paranthesis 39 | * If test expression evaluates to `true`, then the statements in the code block are executed 40 | 41 | Syntax: 42 | 43 | ```code 44 | if(condition) { 45 | statements.. 46 | } 47 | ``` 48 | 49 | Example: 50 | 51 | ```java 52 | // Print if number is odd or even 53 | if(number % 2 == 0) { 54 | System.out.println("number is even"); 55 | } 56 | ``` 57 | 58 | ## if-else statement 59 | 60 | * Evaluates test expression given in paranthesis 61 | * If test expression evaluates to `true`, then the statements in the code block are executed 62 | * If test expression evaluates to `false`, then the statements under the `else` block are executed 63 | 64 | Syntax: 65 | 66 | ```code 67 | if(condition) { 68 | statements.. 69 | } 70 | else { 71 | statements.. 72 | } 73 | ``` 74 | 75 | Example: 76 | 77 | ```java 78 | // Print if number is odd or even 79 | if(number % 2 == 0) { 80 | System.out.println("number is even"); 81 | } 82 | else { 83 | System.out.println("number is odd"); 84 | } 85 | ``` 86 | 87 | ## Handling Multiple Conditions 88 | 89 | * Chaining and nesting can make the code difficult to read 90 | 91 | ### if... else if... else 92 | 93 | Syntax: 94 | 95 | ```code 96 | if(condition1) { 97 | statements.. 98 | } 99 | else if(condition2){ 100 | statements.. 101 | } 102 | else { 103 | statements.. 104 | } 105 | ``` 106 | 107 | Example: 108 | 109 | ```java 110 | // Print if number is odd or even 111 | if(number == 0) { 112 | System.out.println("number is 0"); 113 | } 114 | else if(number % 2 == 0) { 115 | System.out.println("number is even"); 116 | } 117 | else { 118 | System.out.println("number is odd"); 119 | } 120 | ``` 121 | 122 | ### switch (Java 7+) 123 | 124 | * Multiple possible execution paths 125 | * Chooses one possibility out of multiple options 126 | * `break` statement is used to terminate statement flow 127 | * `default` statement is optional 128 | 129 | Syntax: 130 | 131 | ```code 132 | switch(expression) { 133 | case value1 : 134 | statements.. 135 | break; 136 | 137 | case value2 : 138 | statements.. 139 | 140 | default : 141 | statements.. 142 | } 143 | ``` 144 | 145 | Example: 146 | 147 | ```java 148 | String dayOfTheWeek = getDayOfTheWeek(); 149 | boolean weekend; 150 | switch (dayOfTheWeek) { 151 | case "monday": 152 | case "tuesday": 153 | case "wednesday": 154 | case "thursday": 155 | case "friday": 156 | weekend = false; 157 | break; 158 | case "saturday": 159 | case "sunday": 160 | weekend = true; 161 | break; 162 | default: 163 | System.out.println("Unknown day of the week!"); 164 | } 165 | ``` 166 | 167 | ### switch (Java 14+) 168 | 169 | ```code 170 | switch(expression) { 171 | case value1 -> boolean; 172 | case value2 -> boolean; 173 | case value3 -> boolean; 174 | default :-> { 175 | statements.. 176 | } 177 | } 178 | ``` 179 | 180 | Example: 181 | 182 | ```java 183 | String dayOfTheWeek = getDayOfTheWeek(); 184 | boolean weekend = switch (dayOfTheWeek) { 185 | case "monday" -> false; 186 | case "tuesday" -> false; 187 | case "wednesday"-> false; 188 | case "thursday" -> false; 189 | case "friday" -> false; 190 | case "saturday" -> true; 191 | case "sunday" -> true; 192 | default -> { 193 | System.out.println("Unknown day of the week!"); 194 | } 195 | } 196 | ``` 197 | -------------------------------------------------------------------------------- /loops/loopsexampledescriptions.md: -------------------------------------------------------------------------------- 1 | # Java Loop Concepts 2 | 3 | Loops in Java are used to repeat certain code or set of instructions for a certain number of times. 4 | A loop generally has the following four components: 5 | 6 | * Initialization expression(s) 7 | * Test expression(s) 8 | * Update expression(s) 9 | * Body/code block to be executed 10 | 11 | ## while loop 12 | 13 | * Entry-controlled loop 14 | * Evaluates test expression given in paranthesis 15 | * If test expression evaluates to `true`, then the statements in the body of the loop are executed 16 | * Test expression is evaluated again 17 | * Loop is executed until test expression is evaluated to `false` 18 | * If test expression is false the control flow does not enter the body of loop 19 | * Do not forget to satisfy the exit criteria in the body of the loop for it to exit 20 | 21 | Syntax: 22 | 23 | ```code 24 | while(condition) { 25 | statements.. 26 | } 27 | ``` 28 | 29 | Example: 30 | 31 | ```java 32 | // Print numbers below 5 33 | int number = 0; 34 | while(number < 5) { 35 | System.out.println(number); 36 | number++; 37 | } 38 | ``` 39 | 40 | ### Empty while loop 41 | 42 | * Does not contain any statements in the body of code 43 | * Typically used as time delay loops 44 | 45 | ```java 46 | // Time delay loop 47 | long timeDelay = 0; 48 | while(++timeDelay < 10000) 49 | ; 50 | ``` 51 | 52 | ### Infinite while loop 53 | 54 | * Update expression is not provided 55 | * Test expression always evaluates to `true` 56 | * Program has to be abruptly halted 57 | 58 | ```java 59 | // Infinite while loop 60 | int number = 5; 61 | while(number == 5) { 62 | System.out.println("This is unending!"); 63 | } 64 | 65 | ``` 66 | 67 | ## do-while loop 68 | 69 | * Exit-controlled loop 70 | * Starts with executing statements in code block 71 | * Test expression is evaluated 72 | * Code block is executed till test expression evaluates to `false` 73 | * The statements in the code block are executed at least once 74 | 75 | Syntax: 76 | 77 | ```code 78 | do 79 | { 80 | statements.. 81 | } 82 | while(condition); 83 | ``` 84 | 85 | Example: 86 | 87 | ```java 88 | // Print numbers below 5 89 | int number = 0; 90 | do { 91 | System.out.println(number); 92 | number++; 93 | } 94 | while(number < 5); 95 | ``` 96 | 97 | ## for loop (classic style) 98 | 99 | * Entry-controlled loop 100 | * Initialization expression, test expression, update expression 101 | * Initialization expression executed only once 102 | * Statements in code block are executed till test expression is satisfied 103 | 104 | Syntax: 105 | 106 | ```code 107 | for(initialization ; test expression ; update expression) { 108 | statements.. 109 | } 110 | ``` 111 | 112 | Example: 113 | 114 | ```java 115 | // Print numbers below 5 116 | for(int number = 0; number < 5; number++) { 117 | System.out.println(number); 118 | } 119 | ``` 120 | 121 | ```java 122 | String[] names = new String[] {"John", "Jane", "Doe"}; 123 | for(int i = 0; i < names.lenght; i++) { 124 | System.out.println(names[i]); 125 | } 126 | ``` 127 | 128 | ### Nested for loop 129 | 130 | * Loop inside another loop 131 | * Inner loop executes completely each time 132 | 133 | Example: 134 | 135 | ```java 136 | for(int i = 1; i < 5; i++) { 137 | for(int j = 1; j < 5; j++) { 138 | System.out.println(i + " " + j); 139 | } 140 | } 141 | ``` 142 | 143 | ### Infinite for loop 144 | 145 | Example: 146 | 147 | * Test expression never evaluates to `false` 148 | 149 | ```java 150 | for(int i = 1; i < 5;) { 151 | System.out.println("This is unending!"); 152 | } 153 | 154 | ``` 155 | 156 | ## for loop (iterable) 157 | 158 | * for-each loop 159 | * Iterate through elements of a collection or an array 160 | * Read-only loop 161 | 162 | Syntax: 163 | 164 | ```code 165 | for (T element:Collection of object/array) { 166 | statements... 167 | } 168 | ``` 169 | 170 | Example: 171 | 172 | ```java 173 | List names = new LinkedList<>(); 174 | names.add("John"); 175 | names.add("Jane"); 176 | 177 | for (String name : names) { 178 | System.out.println(name); 179 | } 180 | ``` 181 | -------------------------------------------------------------------------------- /methods/accessmodifiertable.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Here's a handy reference table for modifiers 7 | 8 | |----------------|--------------|----------------|-----------------|-----------------| 9 | |Access Modifier | in class | in package | outside package | outside package | 10 | | | | | by subclass only| | 11 | |----------------|--------------|----------------|-----------------|-----------------| 12 | |Private | Y | N | N |N | 13 | |----------------|--------------|----------------|-----------------|-----------------| 14 | |Public | Y | Y | Y |Y | 15 | |----------------|--------------|----------------|-----------------|-----------------| 16 | |Default | Y | Y | N |N | 17 | |----------------|--------------|----------------|-----------------|-----------------| 18 | |Protected | Y | Y | Y |N | 19 | |----------------|--------------|----------------|-----------------|-----------------| 20 | -------------------------------------------------------------------------------- /methods/example1.java: -------------------------------------------------------------------------------- 1 | public class example1 { 2 | 3 | public static void main(String[] args) 4 | 5 | { 6 | 7 | System.out.println("Ex 1 Instance variables go here, Before the Loop"); 8 | int x = 1; 9 | 10 | while (x < 4) { 11 | System.out.println("Ex 1 Running a loop"); 12 | System.out.println("Ex 1 Value of x is " + x); 13 | x = x + 1; 14 | } 15 | System.out.println("Ex 1 This is where values are returned, if any, after the loop"); 16 | 17 | } 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /methods/example2.java: -------------------------------------------------------------------------------- 1 | public class example2 { 2 | 3 | //Note: 4 | //Access modifiers: public, private, protected, default(none) 5 | //Declarations: static, final, abstract, synchronized, native, strictfp: 6 | //Return value types: void, int, float, double, long, short, char, boolean, byte 7 | 8 | public static void main(String [] args) { 9 | //constructor - creates a new class instance 10 | example2 e = new example2(); 11 | e.loop(); 12 | } 13 | 14 | void loop() { 15 | 16 | System.out.println("Ex 2 Instance variables loop here, Before the Loop"); 17 | int x = 1; 18 | 19 | 20 | while (x < 4) { 21 | System.out.println("Ex 2 Running a loop"); 22 | System.out.println("Ex 2 Value of x is " + x); 23 | x = x + 1; 24 | } 25 | System.out.println("Ex 2 This is where values are returned, if any, after the loop"); 26 | 27 | } 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /methods/example3.java: -------------------------------------------------------------------------------- 1 | class example3 { 2 | 3 | public static void main(String [] args) { 4 | //Call the shareLoop constructor to create two new objects 5 | 6 | shareLoop s1 = new shareLoop(); 7 | shareLoop s2 = new shareLoop(); 8 | 9 | 10 | //set the value of the shareLoop instance variables 11 | s1.setSharey(1); 12 | s1.shareLoop(s1.getSharey(), s1.sharez()); 13 | 14 | s2.setSharey(2); 15 | s2.shareLoop(s2.getSharey(), s2.sharez()); 16 | 17 | 18 | //If you try to use instance variables - you get an error 19 | // "Cannot make a static reference to the non-static field" 20 | //local variables or fixed values work, but have limited use 21 | //int a=0; 22 | //int b=0; 23 | //shareLoop s3 = new shareLoop(); 24 | //s3.shareLoop(a,b); 25 | //s3.shareLoop(0,0); 26 | 27 | //public static final instance variable f = public to the class and to all instances 28 | //it can be called here even if it is not initialized 29 | System.out.println("Ex 3 Value of public final (constant) f is: " + s2.f); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /methods/methodexampledescriptions.md: -------------------------------------------------------------------------------- 1 | # Java for Beginners - Methods 2 | 3 | ## Example 1 - A simple method and where it goes 4 | 5 | ### Java classes and methods 6 | 7 | * A source file has a .java extension. 8 | * Every .java file or Java application has at least one class, and at least one main method 9 | * A JVM looks for a class provided at startup, either via the command line or a manifest 10 | * Then it looks for the main method in a class 11 | * A JVM runs everything between the curly braces {} of your main method. 12 | * A class creates an object that runs methods 13 | * One or more methods can be located inside a class 14 | * Method code is a set of statements, which are instructions on how that method should be performed 15 | * Methods return one value. That value can be an array to handle multiple return values. 16 | * A method that returns no value must be declared void 17 | 18 | ## Example 2 - Calling methods 19 | 20 | ### Method declarations 21 | 22 | Method components: 23 | 24 | * The method name 25 | * Access modifiers: public, private, protected, default 26 | * Non-access Modifiers — static, final 27 | * Keywords: abstract (for templates), synchronized (for single-thread methods), native (non-java code),strictfp (floating point calculations only) 28 | * The parameter list - comma-delimited, enclosed by parentheses (). No parameters = empty parentheses (). 29 | * An optional exception list 30 | * The method body, enclosed between curly braces {} 31 | * Return values if the method is not void 32 | 33 | ### Parameters and variables 34 | 35 | * A value passed to a method is called an argument. 36 | * A value received from an argument is called a parameter 37 | * More than one argument or parameter is separated by commas 38 | * Passing a method as an argument is permitted, with the correct parameter type(s) and order. 39 | 40 | ### Instance variables and local variables 41 | 42 | * Instance variables are declared inside a class but outside a method 43 | * Local variables are declared within a method 44 | * Local variables must be initialized, instance variables have default values so they don’t need initialization to run. 45 | * A method uses parameters to receive a passed variable, which behaves like a local variable 46 | 47 | ## Example 3 - calling methods with arguments and parameters 48 | 49 | ### passing and managing variables 50 | 51 | * Java is always pass by value 52 | * Because of this, values cannot be passed directly 53 | * Getters and setters (encapsulation) use public and private access modifiers 54 | * private getters and setters are used for access control. 55 | * Local variables are created inside methods 56 | * Instance variables are created in classes but outside of methods. 57 | 58 | ### Stacks, heaps, objects and variables: 59 | 60 | * Java handles memory in two ways, via the stack and the heap 61 | * A JVM stack stores local variables and manages invocation and management of methods 62 | * The stack is never manipulated directly 63 | * A JVM heap is shared among all applications and threads running on a single JVM 64 | * All objects, classes, and related instance variables are stored in the heap 65 | * Java uses space in the heap for stack management, but does not allow direct control over stack allocation 66 | * Objects in the stack are never explicitly deallocated. 67 | * Garbage collection is used to deallocate idle objects in the stack 68 | * Local variables are created in stacks (and also but rarely referred to as stack variables) 69 | * Local variables like primitives and object references are created on Stack memory. 70 | * Objects are created on Heap memory. 71 | * Instance variables are part of heap memory, because they are part of the object (inside a class but not inside a method) 72 | 73 | ### Modifiers 74 | 75 | * Marking a method as public and static makes it behave like a global variable. 76 | * Any code in any class of an application can access a public static method. 77 | * Any variable marked as public, static, and final = a globally-available constant. 78 | 79 | -------------------------------------------------------------------------------- /methods/shareLoop.java: -------------------------------------------------------------------------------- 1 | class shareLoop { 2 | 3 | //Instance variables 4 | private int sharey; 5 | //private = private to the class 6 | private static int sharez = 0; 7 | //private static = private to the class and all instances 8 | //static = initialized when the class is loaded, private to the class and all instances 9 | public static final String f = "Loop is Done"; 10 | //final = constant (will not change) 11 | 12 | //Getters and setters 13 | public int getSharey() { 14 | return sharey; 15 | } 16 | 17 | public void setSharey(int y) { 18 | sharey = y; 19 | } 20 | 21 | //Increments the private static int sharez 22 | //No getters and setters needed 23 | public int sharez() { 24 | sharez++; 25 | return sharez; 26 | } 27 | 28 | //The called method, void because we print values, none are needed 29 | void shareLoop(int x, int z) { 30 | System.out.println("Ex 3 Instance variables are now passed, not created before the Loop"); 31 | 32 | //This time we passed x instead of initializing it in the method. 33 | //int x = 1; 34 | 35 | System.out.println("Ex 3 Value of private int x is " + x); 36 | System.out.println("Ex 3 Value of private static int z is " + z); 37 | 38 | while (x < 4) { 39 | System.out.println("Ex 3 Running a loop"); 40 | System.out.println("Ex 3 Value of x is " + x); 41 | x = x + 1; 42 | } 43 | System.out.println("Ex 3 This is where values are returned, if any, after the loop"); 44 | System.out.println("Ex 3 Value of private int x is now " + x); 45 | 46 | } 47 | 48 | } 49 | 50 | -------------------------------------------------------------------------------- /stringformatting/stringformattingexample1.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Pattern; 2 | import java.util.StringTokenizer; 3 | import java.util.StringJoiner; 4 | import java.util.stream.*; 5 | import java.util.Arrays; 6 | import java.util.ArrayList; 7 | 8 | public class stringformattingexample1 { 9 | 10 | //char to String 11 | 12 | public static String charToString(char c) { 13 | return Character.toString(c); 14 | } 15 | 16 | //String to char 17 | 18 | public static char StringToChar(String str) { 19 | return str.charAt(0); 20 | } 21 | 22 | // String to char array 23 | 24 | public static char[] StringToCharUsingtoCharArray(String str) { 25 | //String str = "onetwothreefourfive"; 26 | char chararray[] = str.toCharArray(); 27 | for(char ch:chararray){ 28 | System.out.println(ch); 29 | } 30 | return chararray; 31 | 32 | } 33 | 34 | 35 | public static char[] StringToCharUsinggetChars(String str) { 36 | //String str = "onetwothreefourfive"; 37 | char[] chararr = new char[8]; 38 | str.getChars(8, 16, chararr, 0); 39 | for(char ch: chararr){ 40 | System.out.print(ch+" "); 41 | } 42 | return chararr; 43 | } 44 | 45 | public static Character[] StringToCharUsingChars(String str) { 46 | //String str = "onetwothreefourfive"; 47 | Character[] arraychars = str.chars() 48 | .mapToObj(c -> (char) c) 49 | .toArray(Character[]::new); 50 | for(Character ch: arraychars){ 51 | if(Character.isLowerCase(ch)) 52 | System.out.print(ch+" "); 53 | } 54 | return arraychars; 55 | } 56 | 57 | //String Array to String 58 | 59 | 60 | public String ArraytoStringusingtoString (String[] strarray) { 61 | //String[] strarray = {"One","Two", "Three", "Four","Five"}; 62 | String str = Arrays.toString(strarray); 63 | return str; 64 | } 65 | 66 | public String ArraytoStringusingStringBuilderandAppend (String[] strarray) { 67 | //String[] strarray = {"One","Two", "Three", "Four","Five"}; 68 | StringBuilder stringb = new StringBuilder(); 69 | for (int i = 0; i < strarray.length; i++) { 70 | stringb.append(strarray[i]+" "); 71 | } 72 | return stringb.toString(); 73 | 74 | } 75 | 76 | //must import java.util.StringJoiner; 77 | public String ArraytoStringusingStringJoiner (String[] strarray) { 78 | //String[] strarray = {"One","Two", "Three", "Four","Five"}; 79 | StringJoiner stringj = new StringJoiner(";;;", "[", "]"); 80 | for (int i = 0; i < strarray.length; i++) { 81 | stringj.add(strarray[i]+"/"); 82 | } 83 | return stringj.toString(); 84 | } 85 | 86 | //must import java.util.stream.* and java.util.Arrays; 87 | public String ArraytoStringusingStreamandcollector (String[] strarray) { 88 | //String[] strarray = {"One","Two", "Three", "Four","Five"}; 89 | return Stream.of(strarray).collect(Collectors.joining()); 90 | } 91 | 92 | 93 | //String to String Array 94 | public String[] StringToArrayusingSplit (String str) { 95 | //String[] strarray = {"One","Two", "Three", "Four","Five"}; 96 | String[] strarray = str.split(","); 97 | if(strarray.length > 0){ 98 | for(String elm: strarray){ 99 | System.out.print(elm+" "); 100 | } 101 | } 102 | return strarray; 103 | } 104 | 105 | // must import java.util.regex.Pattern; 106 | public String[] StringToArrayusingPattern (String str) { 107 | //String str = "one two three four five"; 108 | String splitpattern = "\\s\\s"; //2 spaces 109 | Pattern pattern = Pattern.compile(splitpattern); 110 | String[] strarray = pattern.split(str); 111 | for (int i = 0; i < strarray.length; i++) { 112 | System.out.println("strarray[" + i + "]=" + strarray[i]); 113 | } 114 | return strarray; 115 | } 116 | 117 | //must import java.util.StringTokenizer; 118 | public String[] StringToArrayusingTokenizer (String str) { 119 | 120 | //String str = "one, two, three, four, five"; 121 | StringTokenizer tokenizer = new StringTokenizer( str,","); 122 | String [] strarray = new String[tokenizer.countTokens()]; 123 | // Add tokens to our array 124 | int i = 0; 125 | while(tokenizer.hasMoreTokens()) { 126 | strarray[i] = tokenizer.nextToken(); 127 | i++; 128 | } 129 | for(String stritem : strarray){ 130 | System.out.println(stritem); 131 | } 132 | return strarray; 133 | } 134 | 135 | } -------------------------------------------------------------------------------- /stringformatting/stringformattingexampledescriptions.md: -------------------------------------------------------------------------------- 1 | # Formatting Strings 2 | 3 | ## Formatting and Conversion Notes 4 | 5 | * There are many, many, many ways to format strings in Java 6 | * You cannot pass values between the primitive data type char and String objects 7 | * They must be converted 8 | * There is no single best solution, it depends on your environment and needs 9 | * Here are several common scenarios and examples to help you compare and contrast options 10 | 11 | ## char to String 12 | 13 | ### String.valueOf(char) 14 | 15 | * To format char as a String, use the String.valueOf(char) method 16 | * returns char as a string object 17 | 18 | ```java 19 | public static String charToString(char c) { 20 | return Character.toString(c); 21 | } 22 | ``` 23 | 24 | ## String to char 25 | 26 | ### charAt(int) 27 | 28 | * To format a character in a String as a char, use the charAt(int) method 29 | * returns the character at position (int). 30 | 31 | ```java 32 | public static char StringToChar(String str) { 33 | return str.charAt(0); 34 | } 35 | ``` 36 | 37 | ## String to char array 38 | 39 | ### toCharArray() Method 40 | 41 | * creates an accessible char[] array 42 | * Java stores strings as primitive char[] arrays internallybut they are not accessible 43 | * Useful when working with non delimited string. Example: String str = "onetwothreefourfive"; 44 | 45 | ```java 46 | char chararray[] = str.toCharArray(); 47 | ``` 48 | 49 | ### getChars() 50 | 51 | * Copy characters from a string or a part of a string into a char[] array 52 | * Arguments are provided for string start, string end, array start, and Destination 53 | 54 | ```java 55 | mystr.getChars(0, 16, chararr, 0); 56 | 57 | ``` 58 | 59 | ### Streaming - chars() method 60 | 61 | * Creates a Stream from a String object 62 | * Use the mapToObj() and toArray() with chars() to convert a string to array of characters 63 | * helpful when selecting characters in a string based on conditions of each character 64 | 65 | ```java 66 | Character[] arraychars = str.chars() 67 | .mapToObj(c -> (char) c) 68 | .toArray(Character[]::new); 69 | ``` 70 | 71 | ## String Array to String 72 | 73 | ### Arrays.toString(); 74 | 75 | * Simple way to convert an array to a string 76 | 77 | ```java 78 | String str = Arrays.toString(strarray); 79 | ``` 80 | ### StringBuilder() and append() 81 | 82 | * Provides the option to conditionally add array elements to a string 83 | 84 | ```java 85 | StringBuilder stringb = new StringBuilder(); 86 | for (int i = 0; i < strarray.length; i++) { 87 | stringb.append(strarray[i]+" "); 88 | } 89 | ``` 90 | ### String Joiner 91 | 92 | Parameters: 93 | 94 | * Options for adding strings at the beginning and end of the constructed string 95 | * Also defines characters to be used between array elements 96 | * java.util.StringJoiner must be imported into your class 97 | 98 | ```java 99 | StringJoiner stringj = new StringJoiner(";;;", "[", "]"); 100 | ``` 101 | 102 | ### Stream and collector 103 | 104 | * Useful if you are provided with a string to consume 105 | * Also can be used to produce an ArrayList 106 | * java.util.stream.* and java.util.Arrays must be imported into your class 107 | 108 | ```java 109 | return Stream.of(strarray).collect(Collectors.joining()); 110 | ``` 111 | 112 | ## String to String Array 113 | 114 | ### split() Method 115 | 116 | * Splits a delimited string into string[] array using a specified character as a delimiter 117 | 118 | ```java 119 | String[] strarray = str.split(","); 120 | ``` 121 | 122 | ### pattern.split() 123 | 124 | * Splits a delimited string into string[] array using a specified pattern as a delimiter 125 | * java.util.regex.Pattern must be imported into your class 126 | 127 | ```java 128 | String splitpattern = "\\s\\s"; //2 spaces 129 | Pattern pattern = Pattern.compile(splitpattern); 130 | ``` 131 | 132 | ### StringTokenizer Class 133 | 134 | * Splits a string object into tokens 135 | * Used to split a non-delimited string into an array 136 | * Delimiters can be specified, default = space 137 | * java.util.StringTokenizer must be imported into your class 138 | 139 | ```java 140 | 141 | 142 | import java.util.StringTokenizer; 143 | .......... 144 | StringTokenizer tokenizer = new StringTokenizer(str); 145 | String [] strarray = new String[tokenizer.countTokens()]; 146 | // Add tokens to an array 147 | int i = 0; 148 | while(tokenizer.hasMoreTokens()) { 149 | strarray[i] = tokenizer.nextToken(); 150 | i++; 151 | } 152 | 153 | ``` 154 | -------------------------------------------------------------------------------- /strings/stringexampledescriptions.md: -------------------------------------------------------------------------------- 1 | # Java String Concepts 2 | 3 | ## char and String 4 | 5 | ### char 6 | 7 | * *char* is a Java primitive data type 8 | * Primitive means that the variable holds the actual value, not a reference 9 | * Others: boolean, byte, short, int, long. float and double 10 | * char not Char 11 | * The char data type can store: 12 | * Any letter 13 | * Numbers between 0 to 65,535 Inclusive 14 | * 16-bit Unicode characters including special characters 15 | * A value for char is enclosed in single quotes '' 16 | * There is also an object wrapper called *character* for a char data type 17 | 18 | Examples: 19 | 20 | ```java 21 | char ch = 'j'; 22 | char uniChar = '\0x004A'; // j in unicode 23 | char[] charArray ={ '1', '2', '3', '4', '@' }; 24 | ``` 25 | 26 | Methods: 27 | 28 | * isLetter() 29 | * isDigit() 30 | * isWhitespace() 31 | * isUpperCase() 32 | * isLowerCase() 33 | * toUpperCase() 34 | * toLowerCase() 35 | * toString() //Returns a String object 36 | 37 | ### String 38 | 39 | * *String* is a provided class in Java 40 | * String not string 41 | * String (and any other class) is a reference to an object 42 | * A value for String is enclosed in double quotes "" 43 | * String can also be stored in arrays, which are also objects 44 | * String is made up of an array of chars 45 | * Because strings are objects, they are immutable (cannot be changed once created) 46 | * String Buffer & String Builder Classes provide mutable string functionality 47 | 48 | Examples: 49 | 50 | ```java 51 | String s = "j"; 52 | String[] strarray = {"One","Two", "Three", "Four","Five"}; 53 | ``` 54 | 55 | ## Commonly used string methods 56 | 57 | ### Java 8+ methods 58 | 59 | * char charAt(int index) 60 | * int compareTo(String anotherString) 61 | * String concat(String str) 62 | * int hashCode() 63 | * int indexOf 64 | * int length() 65 | * String replace and String replaceAll 66 | * String[] split(String regex) 67 | * boolean startsWith(String prefix) 68 | * String substring(int beginIndex) 69 | * String toLowerCase() 70 | * String toUpperCase() 71 | * String trim() 72 | 73 | ### Java 11+ Methods 74 | 75 | * isBlank() 76 | * lines() returns a stream containing a collection of all * substrings split by lines (needs `java.util.stream.Collectors`) 77 | * strip() – Removes all white space from strings, unicode-aware 78 | * repeat(int) repeats a string (int) times 79 | 80 | ### Java 13+ Methods 81 | 82 | * Text Blocks improve the readability of string literals when representing a multi-line string. 83 | 84 | ```java 85 | // String literal formatting 86 | String block = "'String literals can be hard to parse,' said Brian,\n" + 87 | "'And read, --\n" + 88 | "especially if the text spans multiple lines\n" + 89 | "and needs embedded punctuation.'\n"; 90 | 91 | ``` 92 | 93 | 94 | ```java 95 | // Text Block formatting 96 | String block = """ 97 | Brian went on to say that 98 | 'Text blocks are much more readable 99 | And much easier to debug or follow' 100 | """; 101 | 102 | ``` 103 | 104 | ## String Arrays 105 | 106 | * Every main method in Java has a string array declaration as part of it's standard formatting: 107 | 108 | ```java 109 | public static void main(String[] args) { 110 | } 111 | ``` 112 | 113 | * String arrays can contain multiple string elements, also called tokens 114 | * elements and tokens are referred to via their corresponding index number (int) 115 | * Java array indexes start at 0 116 | 117 | ## ArrayLists 118 | 119 | * You need to know about java.util.ArrayList 120 | * The size of an array cannot be modified 121 | * If you want to add or remove elements to/from an array, you have to create a new one 122 | * Elements can be added and removed from an ArrayList at any time 123 | * To create an ArrayList object 124 | 125 | ```java 126 | ArrayList flexibleList = new ArrayList() 127 | ``` 128 | 129 | ## Naming Java variables 130 | 131 | * All variable names must start with a letter, underscore (_), or dollar sign ($) 132 | * The first character can not be a number 133 | * Numbers can be used after the first character 134 | * Java has reserved words which cannot be used 135 | 136 | --------------------------------------------------------------------------------