Przejdź do głównej zawartości

Posty

Wyświetlanie postów z styczeń, 2019

Method Overloading - Java baisics

Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists. The same method name but different number of parameters. public class Main { public static void main ( String [] args ) { // no return value calculateScore ( "Pawel" , 100 ); //we use returned variable score and put to the new variable int newScore = calculateScore ( "John" , 100 ); System . out . println ( "New score is " + newScore ); //results of method overloading calculateScore ( 100 ); // result of method overloading calculateScore (); // data type of return variable does not overload method } public static int calculateScore ( String playerName

DO WHILE and WHILE loops - differences

Co to są pętle? Pętla – jedna z trzech podstawowych konstrukcji programowania strukturalnego (obok instrukcji warunkowej i instrukcji wyboru). Umożliwia cykliczne wykonywanie ciągu instrukcji określoną liczbę razy, do momentu zajścia pewnych warunków, dla każdego elementu kolekcji lub w nieskończoność. do while - najpierw robi do potem sprawdza warunek  while - od poczatku sprawdza warunek   musimy zainicjować wartosć zmiennej  ryzyko nie wykonania // Przykład nie wykonanie się pętli int mySecondNumber = 10 ; while ( mySecondNumber != 10 ){ System . out . println ( "While zostało wykonane" ); }

Learning by doing - Java - 50+ Interview Questions for Programmers

Learning by doing - Java - 50+ Interview Questions for Programmers 50+ Interview questions for 50+ days ? We will see ;) Risky resolution but method "learning by doing" is great!! First are coming questions regarding Arrays: How do you find the missing number in a given integer array of 1 to 100? ( solution ) How do you find the duplicate number on a given integer array? ( solution ) How do you find the largest and smallest number in an unsorted integer array? ( solution ) How do you find all pairs of an integer array whose sum is equal to a given number? ( solution ) How do you find duplicate numbers in an array if it contains multiple duplicates? ( solution ) How are duplicates removed from a given array in Java? ( solution ) How is an integer array sorted in place using the quicksort algorithm? ( solution ) How do you remove duplicates from an array in place? ( solution ) How do you reverse an array in place in Java? ( solution ) How are duplicates remov

Java Naming Convention

Java Naming Convention Naming Convention Oracle documentation: Thinks to name in Java are: Classes CamelCase Class names should be nouns - they represent things  Start with capital letter e.g. MyNewClass ArrayList LinkedList String TopSong Main Variables mixedCase start with lower case Meaningful and indicative  Packages low case unique internet domain name - reversed as a prefix Examples: Invalid Switch.supplier.com  Valid com.supplier._switch Methods mixedCase Often verbs Reflect the function size() getName() addPlayer() Constants represent constants values ALL_UPPER_CASE MAX_INT SEVERITY_ERROR P1 = = 3,141592653 Type Parameters single character, capital letters E-Element T-Type V-Value Interfaces

Generic Types in Java

Generic Types in Java - Definition of Generic Class public class CookieCutter < T > { private T glaze ; } Def: class Name < T1 , T2 , ..., Tn > { /* body */ } Klasy generyczne pozwalają wykluczyć błędy wywołane użyciem nie poprawnego typu danych. Rozwiązanie jest aby sprecyzować konkretny typ naszego pola, w momencie zastosowania w kodzie Przed: public class Walizka { private Object przedmiot ; public void set (Object przedmiot) { this . przedmiot = przedmiot ; } public Object get () { return przedmiot ; } } Po: public class GenerycznaWalizka< T > { private T przedmiot ; public void set ( T przedmiot) { this . przedmiot = przedmiot ; } public T get () { return przedmiot ; } } Różnica - nawiasy trójkątne tzw diamenty <> W powyższym przypadku < T > - może reprezentować wszystko co nie jest prymitywem Klasa może przyjmować wiele parametrów public class Mapa <K, V> {

Java - variables , data types

Data Types Data types in Java are classified in to types: Primitive - which include Integer, Character, Boolean and Floating Point Non-primitive - which includes Classes, Interfaces and Arrays Integer : byte 1 byte short 2 bytes int 4 bytes long 8 bytes Floating Point : number + fractional parts  float double Character : stores character Boolean : hold true false value Variables  Instance Variables (non-Static Fields) -  Objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Class Variables - Static Fields - any field with static modifier says that there is only one copy of this variable in existence static int myClassVariable = 6;  Local Variables - a method stores it's temporary state of local variables int count=0; Parameters - variables which will be passed to the methods of a class

Stored Procedures - JDBC Java SQL

Stored Procedures: group of SQL statements that perform a particular task  Normally created by DBA Can have any combination of input, output, and input/output parameters Benefits: Performance  - compiled once but executable more times Productivity and Ease of Use  - avoid redundant code, extend SQL Database functionality  Scalability   Maintainability Interoperability Replication Security To call stored procedure from Java The JDBC API provides the CallableStatement CallableStatement myCall = myConn.prepareCall("{ call some_stored_procedure() }"); ... myCall.execute(); JDBC API parameter types IN default INOUT OUT Stored Procedure can return result sets EXAMPLE: Created stored procedure on MySQL side - NAME:  increase_salaries_for_department DELIMITER $$ DROP PROCEDURE IF EXISTS ` increase_salaries_for_department `$$ CREATE DEFINER=`student`@`localhost` PROCEDURE `increase_salaries_for_department` ( IN the_depa

Inserting Data into SQL Database with Java

Inserting Data into SQL Database with Java Java Documentation - Processing SQL statements with JDBC  Process: Get connection to database Create a statement Execute SQL query import java.sql.*; /**  *  * @author www.luv2code.com  *  */ public class JdbcTest { public static void main(String[] args) throws SQLException { Connection myConn = null; Statement myStmt = null; ResultSet myRs = null; String dbUrl = "jdbc:mysql://localhost:3306/demo ?autoReconnect=true&useSSL=false "; String user = "root"; String pass = "Sasanka01"; try { // 1. Get a connection to database myConn = DriverManager.getConnection(dbUrl, user, pass); System.out.println("Database connection successfully created"); // 2. Create a statement myStmt = myConn.createStatement(); int rowsAffected = myStmt.executeUpdate(                          "insert into employees " +            

Java Database Connection: JDBC and MySQL

Java Database Connection: JDBC and MySQL JDBC - standard API allow to connect with MySQL Java Application <--------- >JDBC <---------> Database JDBC Architecture JDBC Driver  JDBC Driver Implementation JDBC Driver Manager JDBC API is definded in following packages: java.sql and javax.sql ------------------------ Submitting SQL Queries  - JAVA Get a connection to database Create Statement object Execute SQL query Process Result Set Get a connection to database                    import java.sql.*;                     ....                    String dbUrl = "jdbc:mysql://localhost:3306/demo ?                                                                                  autoReconnect=true&useSSL=false ";                     String user = "root";                     String pass = "Sasanka01";                      ....                      Connection myConn = DriverManager.getConnection(dbUr

References types vs Value Types

References types vs Value Types import java.util.Arrays ; public class Main { public static void main (String[] args) { // write your code here int myIntValue = 10 ; int anotherIntValue = myIntValue ; System. out .println( "myIntValue= " +myIntValue) ; System. out .println( "anotherIntValue= " + anotherIntValue) ; anotherIntValue++ ; System. out .println( "myIntValue= " +myIntValue) ; System. out .println( "anotherIntValue= " + anotherIntValue) ; int [] myIntArray = new int [ 5 ] ; int [] anotherIntArray = myIntArray ; System. out .println( "myIntArray= " + Arrays. toString (myIntArray)) ; System. out .println( "anotherIntArray= " + Arrays. toString (anotherIntArray)) ; anotherIntArray[ 0 ] = 1 ; System. out .println( "after change myIntArray= " + Arrays. toString (myIntArray)) ; Syste

Java -Arrays

Array - data structure that allows us to store multiple values of the same type into a single variable Default value - zero Arrays are zero indexed - Array with ten elements will be indexed from 0 to 9 Array[] How to create array: int[] array = new int[5]; (boxes have value zero - secured slot in memory to hold values) int[] myArray = {1,2,3,4,5}; this type of initializing an array is also known as an anonymous array boolean type arrays - default value is false Errors while working with arrays ArrayIndexOutOfBoundsExeption int[] my Array = {10,35,45,78,55} myArray[5] = 55; out of bound index 5 does not exist int[] myArray = {10,15,20,17,18}; for (int i=1 ; i < myArray.lenght; i++)  System.out.println("value= " + myArray[i] it will return values from index 1 How to print out simple int array? example: int [] myArray = new int [ 2 ] ; myArray[ 0 ]= 0 ; myArray[ 1 ]= 1 ; System. out .println( "My array: " +