├── .gitignore ├── Collection ├── ArrayList.java ├── CollectionHierarchy.png ├── Map_Example.java └── test.txt ├── Groups.md ├── JVM └── test.txt ├── LICENSE ├── README.md ├── commandline ├── .vimrc ├── README.md └── git.md ├── enums ├── AdvancedColorEnum.java ├── ColorEnum.java └── README.md ├── functions ├── Overloading.java └── VarArgs.java ├── introduction ├── HelloWorld.bytecode ├── HelloWorld.hex ├── HelloWorld.java └── README.md ├── jdbc ├── LoginWindow.java ├── Validator.java ├── compile.sh ├── incorrect_pass.png ├── mysql-connector-java-5.0.8-bin.jar └── successful.png └── solutions ├── assignment1 ├── Dbl.java ├── Hello.java ├── IterativeSumFor.java ├── IterativeSumWhile.java └── Speak.java ├── assignment2 ├── Dbl.java ├── IterativeSumFor.java ├── IterativeSumWhile.java └── Speak.java ├── assignment3 ├── BinTree.java ├── BinTree2Tester.java ├── Q2.java ├── Q3.java └── Q4.java ├── assignment4 ├── Q2 │ ├── Circle.java │ └── Square.java ├── Q3 │ ├── Circle.java │ ├── Square.java │ ├── Tester.java │ ├── TesterCircle.java │ ├── TesterSquare.java │ └── classes │ │ ├── Tester.class │ │ └── shapes │ │ ├── circle │ │ ├── Circle.class │ │ └── TesterCircle.class │ │ └── square │ │ ├── Square.class │ │ └── TesterSquare.class └── README.md ├── assignment6 ├── Q2.java ├── Q3.java └── Q4.java └── assignment7 ├── Q2.java ├── Q3.java └── Q4.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | 24 | # Swap 25 | [._]*.s[a-v][a-z] 26 | [._]*.sw[a-p] 27 | [._]s[a-v][a-z] 28 | [._]sw[a-p] 29 | 30 | # Session 31 | Session.vim 32 | 33 | # Temporary 34 | .netrwhist 35 | *~ 36 | # Auto-generated tag files 37 | tags 38 | -------------------------------------------------------------------------------- /Collection/ArrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class TestCollection1 3 | { 4 | public static void main(String args[]) 5 | { 6 | ArrayList list=new ArrayList(); //Creating arraylist 7 | list.add("Rahul"); //Adding object in arraylist 8 | list.add("Atul"); 9 | list.add("Ashok"); 10 | list.add("Shubham"); 11 | 12 | //Traversing list through Iterator or we can traverse also using for-each loop 13 | Iterator itr=list.iterator(); 14 | 15 | while(itr.hasNext()) 16 | { 17 | System.out.println(itr.next()); 18 | } 19 | } 20 | } 21 | ******************************************************************************************************************** 22 | import java.util.*; 23 | class TestCollection2 24 | { 25 | public static void main(String args[]) 26 | { 27 | ArrayList al=new ArrayList(); 28 | al.add("Rahul"); 29 | al.add("Atul"); 30 | al.add("Shubham"); 31 | ArrayList al2=new ArrayList(); 32 | al2.add("Ashok"); 33 | al2.add("Ajay"); 34 | al.addAll(al2);//adding second list in first list 35 | Iterator itr=al.iterator(); 36 | while(itr.hasNext()) 37 | { 38 | System.out.println(itr.next()); 39 | } 40 | } 41 | } 42 | ************************************************************************************************************************ 43 | import java.util.*; 44 | class TestCollection3 45 | { 46 | public static void main(String args[]) 47 | { 48 | ArrayList al=new ArrayList(); 49 | al.add("Rahul"); 50 | al.add("Atul"); 51 | al.add("Ashok"); 52 | ArrayList al2=new ArrayList(); 53 | al2.add("Ashok"); 54 | al2.add("Shubham"); 55 | al.removeAll(al2); 56 | System.out.println("iterating the elements after removing the elements of al2..."); 57 | Iterator itr=al.iterator(); 58 | while(itr.hasNext()) 59 | { 60 | System.out.println(itr.next()); 61 | } 62 | 63 | } 64 | } 65 | **************************************************************************************************************************** 66 | import java.util.*; 67 | class TestCollection4 68 | { 69 | public static void main(String args[]) 70 | { 71 | ArrayList al=new ArrayList(); 72 | al.add("Atul"); 73 | al.add("Rahul"); 74 | al.add("Shubham"); 75 | ArrayList al2=new ArrayList(); 76 | al2.add("Rahul"); 77 | al2.add("Shubham"); 78 | al.retainAll(al2); // return common elements 79 | System.out.println("iterating the elements after retaining the elements of al2..."); 80 | Iterator itr=al.iterator(); 81 | while(itr.hasNext()) 82 | { 83 | System.out.println(itr.next()); 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /Collection/CollectionHierarchy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/Collection/CollectionHierarchy.png -------------------------------------------------------------------------------- /Collection/Map_Example.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class TestCollection 3 | { 4 | public static void main(String args[]) 5 | { 6 | HashMap hm=new HashMap(); 7 | hm.put(100,"Shubham"); 8 | hm.put(101,"Atul"); 9 | hm.put(102,"Rahul"); 10 | hm.remove(102); 11 | for(Map.Entry m:hm.entrySet()) 12 | { 13 | System.out.println(m.getKey()+" "+m.getValue()); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Collection/test.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Groups.md: -------------------------------------------------------------------------------- 1 | # GROUPS 2 | GROUP 1 3 | 4 | ['MT2017002', 'MT2017097', 'MT2017085', 'MT2017101', 'MT2017052', 'MT2017038', 'MT2017064'] 5 | 6 | GROUP 2 7 | 8 | ['MT2017124', 'MT2017016', 'MT2017127', 'MT2017026', 'MT2017017', 'MT2017128', 'MT2017131'] 9 | 10 | GROUP 3 11 | 12 | ['MT2017073', 'MT2017029', 'MT2017040', 'MT2017090', 'MT2017091', 'MT2017119', 'MT2017018'] 13 | 14 | GROUP 4 15 | 16 | ['MT2017129', 'MT2017105', 'MT2017096', 'MT2017053', 'MT2017021', 'MT2017006', 'MT2017078'] 17 | 18 | GROUP 5 19 | 20 | ['MT2017075', 'MT2017095', 'MT2017039', 'MT2017080', 'MT2017102', 'MT2017109', 'MT2017054'] 21 | 22 | GROUP 6 23 | 24 | ['MT2017077', 'MT2017041', 'MT2017009', 'MT2017063', 'MT2017120', 'MT2017104', 'MT2017094'] 25 | 26 | GROUP 7 27 | 28 | ['MT2017033', 'MT2017061', 'MT2017050', 'MT2017079', 'MT2017019', 'MT2017036', 'MT2017001'] 29 | 30 | GROUP 8 31 | 32 | ['MT2017121', 'MT2017013', 'MT2017011', 'MT2017042', 'MT2017048', 'MT2017113', 'MT2017071'] 33 | 34 | GROUP 9 35 | 36 | ['MT2017027', 'MT2017030', 'MT2017028', 'MT2017130', 'MT2017003', 'MT2017037', 'MT2017135'] 37 | 38 | GROUP 10 39 | 40 | ['MT2017100', 'MT2017045', 'MT2017081', 'MT2017110', 'MT2017034', 'MT2017020', 'MT2017144'] 41 | 42 | GROUP 11 43 | 44 | ['MT2017092', 'MT2017051', 'MT2017066', 'MT2017047', 'MT2017108', 'MT2017112', 'MT2017044'] 45 | 46 | GROUP 12 47 | 48 | ['MT2017106', 'MT2017057', 'MT2017015', 'MT2017099', 'MT2017060', 'MT2017014', 'MT2017132'] 49 | 50 | GROUP 13 51 | 52 | ['MT2017010', 'MT2017055', 'MT2017074', 'MT2017103', 'MT2017084', 'MT2017118', 53 | 'MT2017007', 'MT2017141'] 54 | 55 | GROUP 14 56 | 57 | ['MT2017023', 'MT2017115', 'MT2017069', 'MT2017089', 'MT2017004', 'MT2017145', 'MT2017139', 'MT2017142'] 58 | 59 | GROUP 15 60 | 61 | ['MT2017122', 'MT2017008', 'MT2017098', 'MT2017123', 'MT2017067', 'MT2017143', 'MT2017093', Tripti] 62 | 63 | GROUP 16 64 | 65 | ['MT2017025', 'MT2017070', 'MT2017043', 'MT2017116', 'MT2017083', Varchita, 66 | Mayank, 'MT2017138'] 67 | 68 | GROUP 17 69 | 70 | ['MT2017087', 'MT2017126', 'MT2017072', 'MT2017088', 'MT2017114', Srinivas, 'MT2017147', 'MT2017140'] 71 | 72 | GROUP 18 73 | 74 | ['MT2017012', 'MT2017068', 'MT2017031', 'MT2017076', 'MT2017117', 'MT2017146', 'MT2017024'] 75 | 76 | GROUP 19 77 | 78 | ['MT2017046', 'MT2017082', 'MT2017049', 'MT2017022', 'MT2017059', 'MT2017133', 'MT2017136', 'MT2017137'] 79 | 80 | GROUP 20 81 | 82 | ['MT2017107', 'MT2017056', 'MT2017032', 'MT2017065', 'MT2017111', 'MT2017058', 'MT2017134'] 83 | -------------------------------------------------------------------------------- /JVM/test.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2017, Athul Suresh 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Contents 2 | * [Introduction to Java](introduction) 3 | * [Introduction to commandline & Vim](commandline) 4 | * [Working with multiple files - simplified version](solutions/assignment4) 5 | * [Past assignment solutions](solutions) 6 | * [Get started with Git](commandline/git.md) 7 | * [Skeleton for JSONParser](https://github.com/crunchbang/JSONExample) 8 | 9 | ### Misc 10 | * [What every computer science major should know](http://matt.might.net/articles/what-cs-majors-should-know/) 11 | * [Awesome Java - A curated list of all things Java!](https://github.com/akullpp/awesome-java) 12 | * [Vim cheatsheet](https://imgur.com/YLInLlY) 13 | * [Terminals are sexy](https://github.com/k4m4/terminals-are-sexy) 14 | * [Defensive Bash programming](http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/) 15 | * [Bash strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) 16 | 17 | --- 18 | 19 | This repo is collectively maintained by 20 | * [Athul Suresh](https://github.com/crunchbang) 21 | * [Ashok Lathwal](https://github.com/ashoklathwal) 22 | * [Rahul Sharma](https://github.com/rahul10019) 23 | * [Shubham Singh](https://github.com/singhShubh) 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /commandline/.vimrc: -------------------------------------------------------------------------------- 1 | " Reference : https://learnxinyminutes.com/docs/vim/ 2 | " https://gist.github.com/simonista/8703722 3 | " Example ~/.vimrc 4 | " 2015.10 5 | 6 | " Required for vim to be iMproved 7 | set nocompatible 8 | 9 | " Determines filetype from name to allow intelligent auto-indenting, etc. 10 | filetype indent plugin on 11 | 12 | " Enable syntax highlighting 13 | syntax on 14 | 15 | " Better command-line completion 16 | set wildmenu 17 | 18 | " Use case insensitive search except when using capital letters 19 | set ignorecase 20 | set smartcase 21 | 22 | " When opening a new line and no file-specific indenting is enabled, 23 | " keep same indent as the line you're currently on 24 | set autoindent 25 | 26 | " Display line numbers on the left 27 | set number 28 | 29 | " Show file stats 30 | set ruler 31 | 32 | " Indentation options, change according to personal preference 33 | 34 | " Number of visual spaces per TAB 35 | set tabstop=4 36 | 37 | " Number of spaces in TAB when editing 38 | set softtabstop=4 39 | 40 | " Number of spaces indented when reindent operations (>> and <<) are used 41 | set shiftwidth=4 42 | 43 | " Convert TABs to spaces 44 | set expandtab 45 | 46 | " Enable intelligent tabbing and spacing for indentation and alignment 47 | set smarttab 48 | 49 | " Searching 50 | set hlsearch 51 | set incsearch 52 | set ignorecase 53 | set smartcase 54 | 55 | set autoindent 56 | -------------------------------------------------------------------------------- /commandline/README.md: -------------------------------------------------------------------------------- 1 | # Surviving on the commandline 2 | 3 | Paths on \*Nix systems : /home/username/movies/new_movie.mp4 4 | 5 | 6 | ### Some directory conventions 7 | * `.` - current directory 8 | * `..` - parent directory 9 | * `~` - home directory 10 | * `-` - last directory you were in 11 | 12 | ### Getting around 13 | 14 | * `pwd` - **p**rint **w**orking **d**irectory 15 | * `cd ` - **c**hange **d**irectory 16 | * `ls` - **l**i**s**t files in current directory 17 | * `ls -l` - long list 18 | * `ls -a` - list hidden files 19 | * `ls *.java` - list all files ending with .java 20 | * `mkdir ` - make a directory 21 | * `rm ` - remove file 22 | * `rm *.java` - remove all files with .java extension 23 | * `cat file.txt` - output the contents of `file.txt` 24 | 25 | ### I/O Redirection 26 | * `command > file.txt` - redirect output of `command` to `file.txt`. If `file.txt` does not already exist, it will be created automatically. If it exists, its contents will be overwritten. 27 | * `command >> file.txt` - append the output of `command` to `file.txt`. 28 | * `command < file.txt` - `command` takes contents of `file.txt` as input. 29 | 30 | ### Other essential stuff 31 | * `grep pattern file.txt` - outputs lines containing `pattern` in `files.txt` 32 | 33 | ### Java stuff 34 | * `javac Test.java` compiles the file and produces `Test.class` which contains the bytecode in binary format. 35 | * `java Test` takes the .class file and runs it to produce the output 36 | * `javap -c Test` disassembles the class file to produce the bytecode in human readable format 37 | > Side note : Check out the book `Head First Java`. 38 | 39 | ### Pipes 40 | `command1 | command2` - Output of command1 is used as input by command 2 41 | 42 | ### Vim 43 | Copy the `.vimrc` file into your home directory. Refer this [handy doc](https://learnxinyminutes.com/docs/vim/) for a cheatsheet of vim commands. Use `vimtutor` to get yourself started after the class. And finally **do not** use the mouse when you're inside vim.NEVER EVER\ 44 | My preferred plugin manager - [Vim-plug](https://github.com/junegunn/vim-plug) 45 | 46 | ### Other cool stuff on the commandline 47 | All the programs can be installed using `sudo apt-get install ` 48 | * `htop` and `glances` 49 | * `pandoc` - cheatsheet available [here](https://github.com/dsanson/Pandoc.tmbundle/blob/master/Support/doc/cheatsheet.markdown) 50 | * `cmatrix`\ 51 | Find a lot more [here](https://kkovacs.eu/~cure-unix-tools). 52 | 53 | ### Making life a little easier 54 | Bash/Dash is the default shell you get on most systems. Install the fish shell if you want to make your life on the shell a litter easier (and colorful). `sudo apt-get install fish` to install `fish`. Use ``chsh -s `which fish` `` to set fish as your default shell. Otherwise you'll have to keep typing fish each time to get the fish shell. It provides syntax highlighting (for wrong commands), command completion and a lot more. 55 | 56 | ### Check out [The Art of The Command Line](https://github.com/jlevy/the-art-of-command-line) if you're looking to level up your commandline game. 57 | 58 | 59 | References & Further reading: 60 | 61 | * [TLDP](http://www.tldp.org/LDP/abs/html/index.html) 62 | 63 | * [Unix Programming Tools](http://cslibrary.stanford.edu/107/UnixProgrammingTools.pdf) 64 | 65 | * [Vi commands](http://web.stanford.edu/~laha/docs/Vi-commands.pdf) 66 | -------------------------------------------------------------------------------- /commandline/git.md: -------------------------------------------------------------------------------- 1 | 2 | # Get started with [Git](https://git-scm.com/) 3 | 4 | 5 | 6 | ## Cheat Sheet 7 | 8 | ### Local Workflow: 9 | 10 | **git init**: put Git in this folder so that it keeps track of changes to files in this folder and subfolders 11 | 12 | *Working Directory*: the directory you’re writing code in 13 | 14 | *Staging Area*: files are in the staging area if the changes in them will be included in the next save point 15 | 16 | *Repository*: everything Git is keeping track of 17 | 18 | **git status**: show me which files have been changed and which ones are ready to be committed 19 | 20 | **git add filename.txt**: include the changes to this file in the next commit 21 | 22 | **git commit -m “commit message”**: wrap up all these changes and save them together with a short description of the changes 23 | 24 | **git log**: show a history of all commits 25 | 26 | **git diff**: show what is different from the last commit line by line 27 | 28 | **git diff 234nod**: show what is different between the commit 234nod and current state, line by line 29 | 30 | ### Remote Repository 31 | 32 | **git remote add origin address-of-remote**: make address-of-remote a new place to put my code and call it “origin” 33 | 34 | **git push -u origin master**: push my code to the location origin points to, on the master branch, and also in the future I will pull code from this same location 35 | 36 | *Upstream*: where I will pull code from in the future 37 | 38 | *Origin*: where I put backups or share my code 39 | 40 | **git pull**: grab code from another repository 41 | 42 | **git fetch**: grab code from another repository 43 | 44 | **git push**: save my history and changes in another location 45 | 46 | *Fork*: I want a GitHub repo that looks like someone else’s repo 47 | 48 | *Pull Request*: I made some changes that I would like you to include in your repository, please accept them 49 | 50 | **git clone**: give me the code at this location 51 | 52 | --- 53 | References:\ 54 | [How to teach Git](https://recompilermag.com/issues/issue-1/how-to-teach-git/) 55 | 56 | #### Extra Stuff: 57 | * [Peepcode - Git internals](https://github.com/pluralsight/git-internals-pdf/raw/master/drafts/peepcode-git.pdf) 58 | * [Introduction to Git with Scott Chacon of GitHub](https://www.youtube.com/watch?v=ZDR433b0HJY) 59 | * [Making a Pull Request](https://www.atlassian.com/git/tutorials/making-a-pull-request) 60 | 61 | -------------------------------------------------------------------------------- /enums/AdvancedColorEnum.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | class AdvancedColorEnum { 4 | public enum Color { 5 | RED(255,0,0), 6 | GREEN(0,255,0), 7 | BLUE(0,0,255); //semicolon if methods follow the definition 8 | 9 | private final int[] hexCode; 10 | private Color(int r, int g, int b) { 11 | hexCode = new int[3]; 12 | hexCode[0] = r; 13 | hexCode[1] = g; 14 | hexCode[2] = b; 15 | } 16 | 17 | public String toString() { 18 | String hexRep = "(" + Integer.toString(hexCode[0]) + ", " 19 | + Integer.toString(hexCode[1]) + ", " 20 | + Integer.toString(hexCode[2]) + " )"; 21 | return hexRep; 22 | } 23 | 24 | 25 | } 26 | public static void main(String[] args) { 27 | 28 | Color outputColor = findColorOfObject(); 29 | switch(outputColor) { 30 | case RED: 31 | System.out.println("It's RED!"); 32 | break; 33 | case BLUE: 34 | System.out.println("It's BLUE!"); 35 | break; 36 | case GREEN: 37 | System.out.println("It's GREEN!"); 38 | break; 39 | 40 | } 41 | System.out.println(outputColor); 42 | 43 | System.out.println("Possible Colors:"); 44 | for (Color c : Color.values()) { 45 | System.out.println(c); 46 | } 47 | } 48 | 49 | public static Color findColorOfObject() { 50 | /* 51 | * Randomly return an enum 52 | */ 53 | Random random = new Random(); 54 | int val = random.nextInt(3); 55 | Color c; 56 | switch(val) { 57 | case 0 : 58 | c = Color.RED; 59 | break; 60 | case 1: 61 | c = Color.BLUE; 62 | break; 63 | case 2: 64 | c = Color.GREEN; 65 | break; 66 | default: 67 | c = Color.RED; 68 | break; 69 | } 70 | return c; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /enums/ColorEnum.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | enum Color { 4 | RED, 5 | GREEN, 6 | BLUE, 7 | } 8 | 9 | class ColorEnum { 10 | public static void main(String[] args) { 11 | 12 | Color outputColor = findColorOfObject(); 13 | switch(outputColor) { 14 | case RED: 15 | System.out.println("It's RED!"); 16 | break; 17 | case BLUE: 18 | System.out.println("It's BLUE!"); 19 | break; 20 | case GREEN: 21 | System.out.println("It's GREEN!"); 22 | break; 23 | 24 | } 25 | 26 | doSomethingToColor(Color.RED); 27 | 28 | 29 | System.out.println(outputColor); 30 | 31 | System.out.println("Possible Colors:"); 32 | for (Color c : Color.values()) { 33 | System.out.println(c); 34 | } 35 | } 36 | 37 | public static Color findColorOfObject() { 38 | /* 39 | * Randomly return an enum 40 | */ 41 | Random random = new Random(); 42 | int val = random.nextInt(3); 43 | Color c; 44 | switch(val) { 45 | case 0 : 46 | c = Color.RED; 47 | break; 48 | case 1: 49 | c = Color.BLUE; 50 | break; 51 | case 2: 52 | c = Color.GREEN; 53 | break; 54 | default: 55 | c = Color.RED; 56 | break; 57 | } 58 | return c; 59 | } 60 | 61 | public static void doSomethingToColor(Color c) { 62 | switch(c) { 63 | case RED : 64 | System.out.println("Bloody Red"); 65 | break; 66 | case BLUE: 67 | System.out.println("Sky Blue"); 68 | break; 69 | case GREEN: 70 | System.out.println("Grass Green"); 71 | break; 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /enums/README.md: -------------------------------------------------------------------------------- 1 | # Enums 2 | 3 | * [Why use Enums at all?](https://stackoverflow.com/questions/4709175/what-are-enums-and-why-are-they-useful) 4 | * [What is the use of Enums in Java](https://stackoverflow.com/questions/9850525/whats-the-use-of-enum-in-java) 5 | * [How are Enums internally represented](https://stackoverflow.com/questions/32354107/how-are-enums-internally-represented-in-java) 6 | -------------------------------------------------------------------------------- /functions/Overloading.java: -------------------------------------------------------------------------------- 1 | public class Overloading { 2 | // Correct examples 3 | static int add(int a, int b){ 4 | return a+b; 5 | } 6 | 7 | static double add(double a, double b){ 8 | return a+b; 9 | } 10 | 11 | static double add(double a, double b, double c){ 12 | return a+b+c; 13 | } 14 | 15 | /* 16 | //Can you guess the error in this function? 17 | 18 | static byte add(byte a, byte b){ 19 | byte c = a+b; 20 | return c; 21 | } 22 | */ 23 | 24 | /* 25 | //Incorrect example 26 | static long add(int a, int b){ 27 | long res = a+b; 28 | return res; 29 | } 30 | //We can't have two methods with same parameters and only diffferent return types. 31 | */ 32 | 33 | public static void main(String ...s){ 34 | System.out.println(Overloading.add(2,5)); 35 | System.out.println(Overloading.add(2.5,4.5)); 36 | System.out.println(Overloading.add(2.4,0.5,1.2)); 37 | 38 | // Can you tell the reason why the code will work? 39 | // Hint: type promotion 40 | System.out.println(Overloading.add(1,2,3)); 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /functions/VarArgs.java: -------------------------------------------------------------------------------- 1 | public class VarArgs { 2 | static int add(int ...n){ 3 | int sum = 0; 4 | for(int i:n){ 5 | sum += i; 6 | } 7 | return sum; 8 | } 9 | static int add(String message, int ...n){ 10 | System.out.println(message); 11 | int sum = 0; 12 | for(int i:n){ 13 | sum += i; 14 | } 15 | return sum; 16 | } 17 | /* 18 | //Wrong way of using variable arguments. 19 | // If the function consists of several arguments , then var_args must be at the last. 20 | int add(int ...n, String message){ 21 | System.out.println(message); 22 | int sum = 0; 23 | for(int i:n){ 24 | sum += i; 25 | } 26 | return sum; 27 | } 28 | */ 29 | public static void main(String ...s){ 30 | System.out.println(VarArgs.add(1,2,3)); 31 | System.out.println(VarArgs.add(1,2,3,4,5)); 32 | System.out.println(VarArgs.add("Demo of how to use variable arguments in JAVA",1,2,3,4,5)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /introduction/HelloWorld.bytecode: -------------------------------------------------------------------------------- 1 | Compiled from "HelloWorld.java" 2 | class HelloWorld { 3 | HelloWorld(); 4 | Code: 5 | 0: aload_0 6 | 1: invokespecial #1 // Method java/lang/Object."":()V 7 | 4: return 8 | 9 | public static void main(java.lang.String[]); 10 | Code: 11 | 0: iconst_1 12 | 1: istore_1 13 | 2: iconst_1 14 | 3: istore_2 15 | 4: iload_1 16 | 5: iload_2 17 | 6: invokestatic #2 // Method add:(II)I 18 | 9: istore_3 19 | 10: return 20 | 21 | public static int add(int, int); 22 | Code: 23 | 0: iload_0 24 | 1: iload_1 25 | 2: iadd 26 | 3: ireturn 27 | } 28 | -------------------------------------------------------------------------------- /introduction/HelloWorld.hex: -------------------------------------------------------------------------------- 1 | 00000000: cafe babe 0000 0034 0013 0a00 0400 0f0a .......4........ 2 | 00000010: 0003 0010 0700 1107 0012 0100 063c 696e ................()V...Code 4 | 00000030: 0100 0f4c 696e 654e 756d 6265 7254 6162 ...LineNumberTab 5 | 00000040: 6c65 0100 046d 6169 6e01 0016 285b 4c6a le...main...([Lj 6 | 00000050: 6176 612f 6c61 6e67 2f53 7472 696e 673b ava/lang/String; 7 | 00000060: 2956 0100 0361 6464 0100 0528 4949 2949 )V...add...(II)I 8 | 00000070: 0100 0a53 6f75 7263 6546 696c 6501 000f ...SourceFile... 9 | 00000080: 4865 6c6c 6f57 6f72 6c64 2e6a 6176 610c HelloWorld.java. 10 | 00000090: 0005 0006 0c00 0b00 0c01 000a 4865 6c6c ............Hell 11 | 000000a0: 6f57 6f72 6c64 0100 106a 6176 612f 6c61 oWorld...java/la 12 | 000000b0: 6e67 2f4f 626a 6563 7400 2000 0300 0400 ng/Object. ..... 13 | 000000c0: 0000 0000 0300 0000 0500 0600 0100 0700 ................ 14 | 000000d0: 0000 1d00 0100 0100 0000 052a b700 01b1 ...........*.... 15 | 000000e0: 0000 0001 0008 0000 0006 0001 0000 0002 ................ 16 | 000000f0: 0009 0009 000a 0001 0007 0000 002f 0002 ............./.. 17 | 00000100: 0004 0000 000b 043c 043d 1b1c b800 023e .......<.=.....> 18 | 00000110: b100 0000 0100 0800 0000 1200 0400 0000 ................ 19 | 00000120: 0500 0200 0600 0400 0700 0a00 0800 0900 ................ 20 | 00000130: 0b00 0c00 0100 0700 0000 1c00 0200 0200 ................ 21 | 00000140: 0000 041a 1b60 ac00 0000 0100 0800 0000 .....`.......... 22 | 00000150: 0600 0100 0000 0b00 0100 0d00 0000 0200 ................ 23 | 00000160: 0e0a .. 24 | -------------------------------------------------------------------------------- /introduction/HelloWorld.java: -------------------------------------------------------------------------------- 1 | 2 | class HelloWorld { 3 | 4 | public static void main(String[] args) { 5 | int a = 1; 6 | int b = 1; 7 | int c = add(a, b); 8 | } 9 | 10 | public static int add(int a, int b) { 11 | return a+b; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /introduction/README.md: -------------------------------------------------------------------------------- 1 | # Introduction to Java 2 | 3 | This repo will contain all the code snippets and links that we use during the class. This README will be continually updated with new stuff. Be sure to watch the repo to get the updates. On to the good stuff. 4 | 5 | ### Installation 6 | * ```sudo apt-get install openjdk-8-jdk``` for people on \*nix systems. 7 | * [Java 8 on Mac](https://gist.github.com/JeOam/a926dbb5145c4d0789c1) 8 | * [Java 8 on Windows](https://www.tutorialspoint.com/java8/java8_environment.htm) 9 | 10 | Try ```java -version``` on the command-line. It should show something similar to this: 11 | ``` 12 | java version "1.8.0_102" 13 | Java(TM) SE Runtime Environment (build 1.8.0_102-b14) 14 | Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) 15 | ``` 16 | Make sure it says 1.8.x. and you're good to go. 17 | 18 | ### Getting started with Git & Github 19 | 20 | 21 | * [Setting up git for Github](https://help.github.com/articles/set-up-git/) 22 | * [Github hello-world](https://guides.github.com/activities/hello-world/) 23 | * [An interactive git tutorial](https://github.com/jlord/git-it) 24 | * [git - the simple guide](https://rogerdudler.github.io/git-guide/) 25 | 26 | Create a Github user account and commit all your code to Github. It will help you in the future. 27 | 28 | ### A bit of history 29 | 30 | * [A short history of Java](https://dzone.com/articles/a-short-history-of-java) 31 | * [Java & Cafe Babe](https://dzone.com/articles/the-magic-word-in-java-cafebabe) 32 | 33 | ### Places to get help 34 | 35 | * [Oracle Java Tutorial](https://docs.oracle.com/javase/tutorial/) - Go through the tutorial atelast once. They provide an overview of almost all the features of Java with appropirate examples and motivation behind the design decisions. 36 | * [Oracle Java Docs](https://docs.oracle.com/javase/8/docs/api/) - This is where you'll spend a large amount of your time. Get used to reading the Java Docs. 37 | 38 | ### If you want to get into the gory internals 39 | 40 | * [Java Language specification](https://docs.oracle.com/javase/specs/jls/se8/html/index.html) - Though a bit pedantic and boring at times, this is the place to start (or atleast skim through) if you want to get into the Java internals. 41 | * [JVM Specification](http://docs.oracle.com/javase/specs/jvms/se7/html/index.html) - The JVM specs give you an insight into the inner workings of the JVM. The guide lays down rules and behaviors that JVM implementations are supposed to conform to. Read the specs first before getting into the JVM code. 42 | 43 | ### Where to get the code 44 | 45 | Java is an exteremly verbose and readable langugage. If you ever feel like looking at the code that makes all the magic happen, head over to [GrepCode/JVM](http://grepcode.com/project/repository.grepcode.com/java/root/jdk/openjdk/) to read the code. 46 | 47 | 48 | ### Coding convention 49 | 50 | [Here](http://javaranch.com/style.jsp) are some accepted practices and conventions to follow when coding in Java. 51 | 52 | 53 | #### If you're already familiar with Java and want to brush up on its syntax --> 54 | [Learn X in Y minutes / Java](https://learnxinyminutes.com/docs/java/) 55 | --- 56 | -------------------------------------------------------------------------------- /jdbc/LoginWindow.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.awt.Color; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | 7 | import javax.swing.*; 8 | 9 | 10 | public class LoginWindow { 11 | 12 | JFrame f; 13 | JButton bt; 14 | JTextField id; 15 | JPasswordField pwd; 16 | JLabel idL, pwdL; 17 | 18 | // constructor 19 | public LoginWindow() { 20 | f = new JFrame(); 21 | f.setTitle("Login Window"); 22 | f.setSize(600, 400); 23 | f.setLayout(null); 24 | 25 | this.addTextFields(); 26 | this.addButton(); 27 | 28 | f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 29 | f.setVisible(true); 30 | } 31 | 32 | // helper methods 33 | private void addTextFields() { 34 | 35 | idL = new JLabel("User Id:"); 36 | idL.setSize(100,30); 37 | idL.setLocation(150,100); 38 | 39 | id = new JTextField(); 40 | id.setSize(200,30); 41 | id.setLocation(250,100); 42 | 43 | pwd = new JPasswordField(); 44 | pwd.setSize(200,30); 45 | pwd.setLocation(250,160); 46 | 47 | pwdL = new JLabel("Password:"); 48 | pwdL.setSize(100,30); 49 | pwdL.setLocation(150, 160); 50 | 51 | f.add(idL); 52 | f.add(pwdL); 53 | f.add(id); 54 | f.add(pwd); 55 | } 56 | void addButton() { 57 | bt = new JButton("Login"); 58 | bt.setSize(100,40); 59 | bt.setLocation(250, 250); 60 | bt.addActionListener(new ActionListener() { 61 | 62 | @Override 63 | public void actionPerformed(ActionEvent evt) { 64 | if(evt.getSource() == bt) { 65 | Validator obj = new Validator(); 66 | int result = obj.validate(id.getText(),pwd.getText()); 67 | JDialog d = new JDialog(f); 68 | d.setLayout(null); 69 | d.setSize(430, 100); 70 | if(result == Validator.INCOMPLETE) { 71 | d.setTitle("Alert"); 72 | JLabel msg = new JLabel("Please enter User Id and Password to continue."); 73 | msg.setForeground(Color.RED); 74 | msg.setSize(350,30); 75 | msg.setLocation(50,30); 76 | d.add(msg); 77 | } 78 | else if(result == Validator.USER_NOT_FOUND) { 79 | d.setTitle("Alert"); 80 | JLabel msg = new JLabel("Incorrect Login Id!!!"); 81 | msg.setForeground(Color.RED); 82 | msg.setSize(300,30); 83 | msg.setLocation(150,30); 84 | d.add(msg); 85 | } 86 | else if(result == Validator.VALIDATION_SUCCESSFUL) { 87 | d.setTitle("Welcome"); 88 | JLabel msg = new JLabel("Login Successful."); 89 | msg.setForeground(Color.MAGENTA); 90 | msg.setSize(200,30); 91 | msg.setLocation(150,30); 92 | d.add(msg); 93 | } 94 | else { 95 | JLabel msg = new JLabel("Wrong Password"); 96 | msg.setForeground(Color.RED); 97 | msg.setSize(200,30); 98 | msg.setLocation(150,30); 99 | d.add(msg); 100 | } 101 | d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 102 | d.setVisible(true); 103 | } 104 | } 105 | }); 106 | f.add(bt); 107 | } 108 | 109 | // main method 110 | public static void main(String ...s) { 111 | new LoginWindow(); 112 | } 113 | } 114 | 115 | -------------------------------------------------------------------------------- /jdbc/Validator.java: -------------------------------------------------------------------------------- 1 | 2 | import java.sql.*; 3 | 4 | class Validator{ 5 | Connection con; 6 | 7 | static int INCOMPLETE = 0; 8 | static int USER_NOT_FOUND = 1; 9 | static int PASSWORD_MISMATCH = 2; 10 | static int VALIDATION_SUCCESSFUL = 3; 11 | 12 | public Validator(){ 13 | try { 14 | Class.forName("com.mysql.jdbc.Driver"); 15 | con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","3745"); 16 | } 17 | catch (ClassNotFoundException | SQLException ex) { 18 | System.out.println(ex); 19 | } 20 | } 21 | 22 | public int validate(String user, String pwd){ 23 | if(user.equals("") || pwd.equals("")){ 24 | try{ 25 | con.close(); 26 | } 27 | catch(SQLException e){ 28 | System.out.println(e); 29 | } 30 | return Validator.INCOMPLETE; 31 | } 32 | 33 | int result = -1; 34 | try{ 35 | Statement st = con.createStatement(); 36 | ResultSet rst; 37 | rst = st.executeQuery("select COUNT(user) from users where user='"+user+"';"); 38 | rst.next(); 39 | if(rst.getInt(1)==0){ 40 | result = Validator.USER_NOT_FOUND; 41 | } 42 | else{ 43 | rst = st.executeQuery("select pwd from users where user='"+user+"';"); 44 | rst.next(); 45 | String corr_pwd = rst.getString(1); 46 | if(corr_pwd.equals(pwd)){ 47 | result = Validator.VALIDATION_SUCCESSFUL; 48 | } 49 | else{ 50 | result = Validator.PASSWORD_MISMATCH; 51 | } 52 | } 53 | con.close(); 54 | } 55 | catch(SQLException e){ 56 | System.out.println(e); 57 | } 58 | return result; 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /jdbc/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "javac -classpath .:mysql-connector-java-5.0.8-bin.jar Validator.java" 4 | javac -classpath .:mysql-connector-java-5.0.8-bin.jar Validator.java 5 | 6 | echo "javac -classpath .:mysql-connector-java-5.0.8-bin.jar LoginWindow.java" 7 | javac -classpath .:mysql-connector-java-5.0.8-bin.jar LoginWindow.java 8 | 9 | echo "java -classpath .:mysql-connector-java-5.0.8-bin.jar LoginWindow.java" 10 | java -classpath .:mysql-connector-java-5.0.8-bin.jar LoginWindow.java 11 | 12 | echo "Running" 13 | echo "java -classpath .:mysql-connector-java-5.0.8-bin.jar LoginWindow" 14 | java -classpath .:mysql-connector-java-5.0.8-bin.jar LoginWindow 15 | -------------------------------------------------------------------------------- /jdbc/incorrect_pass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/jdbc/incorrect_pass.png -------------------------------------------------------------------------------- /jdbc/mysql-connector-java-5.0.8-bin.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/jdbc/mysql-connector-java-5.0.8-bin.jar -------------------------------------------------------------------------------- /jdbc/successful.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/jdbc/successful.png -------------------------------------------------------------------------------- /solutions/assignment1/Dbl.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; //for taking input 2 | 3 | public class Dbl { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); //Scanner class is used to take input from the user 6 | // can be omitted if you're hardcoding the input 7 | System.out.print("Enter a number: "); 8 | int n = s.nextInt(); 9 | System.out.println("Doubled output: " + (2*n)); 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /solutions/assignment1/Hello.java: -------------------------------------------------------------------------------- 1 | 2 | public class Hello { 3 | public static void main(String[] args) { 4 | System.out.println("Hello, world!"); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /solutions/assignment1/IterativeSumFor.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class IterativeSumFor { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | System.out.print("Enter a number: "); 7 | int n = s.nextInt(); 8 | int sum = 0; 9 | for (int i = 1; i <= n; ++i) { 10 | sum += i; 11 | } 12 | System.out.println("Sum of the sequence: " + sum); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /solutions/assignment1/IterativeSumWhile.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class IterativeSumWhile { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | System.out.print("Enter a number: "); 7 | int n = s.nextInt(); 8 | int sum = 0; 9 | int i = 1; 10 | while (i <= n) { 11 | sum += i; 12 | i++; 13 | } 14 | System.out.println("Sum of the sequence: " + sum); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /solutions/assignment1/Speak.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Speak { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | String animal; 7 | System.out.print("Enter the name of the animal: "); 8 | animal = s.next(); //next reads input till the first space character 9 | //use nextLine() to read the whole line 10 | printSound(animal); 11 | } 12 | 13 | public static void printSound(String animal) { 14 | String sound; 15 | if (animal.equals("human")) { 16 | sound = "bla bla bla"; 17 | } else if (animal.equals("dog")) { 18 | sound = "bark"; 19 | } else if (animal.equals("cat")) { 20 | sound = "meow"; 21 | } else { 22 | sound = "wrong animal"; 23 | } 24 | 25 | System.out.println(sound); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /solutions/assignment2/Dbl.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; //for taking input 2 | 3 | public class Dbl { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); //Scanner class is used to take input from the user 6 | // can be omitted if you're hardcoding the input 7 | System.out.print("Enter a number: "); 8 | int n = s.nextInt(); 9 | System.out.println("Doubled output: " + dbl(n)); 10 | 11 | } 12 | 13 | public static int dbl(int n) { 14 | return 2*n; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /solutions/assignment2/IterativeSumFor.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class IterativeSumFor { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | System.out.print("Enter a number: "); 7 | int n = s.nextInt(); 8 | System.out.println("Sum of the sequence: " + iterativeSumFor(n)); 9 | 10 | } 11 | 12 | public static int iterativeSumFor(int n) { 13 | int sum = 0; 14 | for (int i = 1; i <= n; ++i) { 15 | sum += i; 16 | } 17 | return sum; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /solutions/assignment2/IterativeSumWhile.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class IterativeSumWhile { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | System.out.print("Enter a number: "); 7 | int n = s.nextInt(); 8 | System.out.println("Sum of the sequence: " + iterativeSumWhile(n)); 9 | 10 | } 11 | 12 | public static int iterativeSumWhile(int n) { 13 | int sum = 0; 14 | int i = 1; 15 | while (i <= n) { 16 | sum += i; 17 | i++; 18 | } 19 | return sum; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /solutions/assignment2/Speak.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Speak { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | String animal; 7 | System.out.print("Enter the name of the animal: "); 8 | animal = s.next(); //next reads input till the first space character 9 | //use nextLine() to read the whole line 10 | System.out.println(printSound(animal)); 11 | } 12 | 13 | public static String printSound(String animal) { 14 | String sound; 15 | if (animal.equals("human")) { 16 | sound = "bla bla bla"; 17 | } else if (animal.equals("dog")) { 18 | sound = "bark"; 19 | } else if (animal.equals("cat")) { 20 | sound = "meow"; 21 | } else { 22 | sound = "wrong animal"; 23 | } 24 | 25 | return sound; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /solutions/assignment3/BinTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author singhShubh 4 | */ 5 | 6 | public class BinTree { 7 | int value; 8 | BinTree left; 9 | BinTree right; 10 | 11 | public BinTree(int value){ 12 | this.value = value; 13 | left = null; 14 | right = null; 15 | } 16 | public void setLeftTree(BinTree left){ 17 | this.left = left; 18 | } 19 | public void setRightTree(BinTree right){ 20 | this.right = right; 21 | } 22 | public boolean search(int num){ 23 | if(value == num) 24 | return true; 25 | else{ 26 | boolean leftResult = false,rightResult = false; 27 | if(left!=null) 28 | leftResult = left.search(num); 29 | if(this.right!=null) 30 | rightResult = this.right.search(num); 31 | return leftResult | rightResult; 32 | } 33 | } 34 | // Driver function to check your code. 35 | public static void main(String ...s){ 36 | BinTree tree= new BinTree(5); 37 | tree.setLeftTree(new BinTree(10)); 38 | tree.setRightTree(new BinTree(12)); 39 | tree.left.setLeftTree(new BinTree(18)); 40 | tree.left.setRightTree(new BinTree(15)); 41 | tree.left.left.setLeftTree(new BinTree(16)); 42 | tree.left.right.setRightTree(new BinTree(22)); 43 | tree.right.setLeftTree(new BinTree(40)); 44 | 45 | System.out.println(tree.search(35)); 46 | System.out.println(tree.search(40)); 47 | System.out.println(tree.search(15)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /solutions/assignment3/BinTree2Tester.java: -------------------------------------------------------------------------------- 1 | 2 | class BinTree2 { 3 | int value; 4 | BinTree2 left, right; 5 | 6 | public BinTree2(int v, BinTree2 l, BinTree2 r) { 7 | value = v; 8 | left = l; 9 | right = r; 10 | } 11 | 12 | /* 13 | * check if key is present in the tree 14 | */ 15 | public boolean find(int key) { 16 | if (value == key) 17 | return true; 18 | else { 19 | boolean inLeft = false; 20 | boolean inRight = false; 21 | 22 | if (left != null) { 23 | inLeft = left.find(key); 24 | } 25 | 26 | if (!inLeft && right != null) { 27 | inRight = right.find(key); 28 | } 29 | 30 | return (inLeft | inRight); 31 | } 32 | } 33 | 34 | /* 35 | * find number of keys in tree 36 | */ 37 | public int numberOfNodes() { 38 | int numNodes = 0; 39 | if (left == null && right == null) { 40 | numNodes = 1; 41 | } else { 42 | int numNodesLeft = 0; 43 | if (left != null) { 44 | numNodesLeft = left.numberOfNodes(); 45 | } 46 | 47 | int numNodesRight = 0; 48 | if (right != null) { 49 | numNodesRight = right.numberOfNodes(); 50 | } 51 | 52 | numNodes = 1 + numNodesLeft + numNodesRight; 53 | } 54 | return numNodes; 55 | } 56 | 57 | /* 58 | * find total value of all keys in tree 59 | */ 60 | public int totalValue() { 61 | int totalVal = 0; 62 | if (left == null && right == null) { 63 | totalVal = value; 64 | } else { 65 | int totalValLeft = 0; 66 | if (left != null) { 67 | totalValLeft = left.totalValue(); 68 | } 69 | 70 | int totalValRight = 0; 71 | if (right != null) { 72 | totalValRight = right.totalValue(); 73 | } 74 | 75 | totalVal = value + totalValLeft + totalValRight; 76 | } 77 | return totalVal; 78 | } 79 | 80 | /* 81 | * check if key is a descendent of current node(calling object) 82 | */ 83 | public boolean isDescendent(int key) { 84 | boolean inLeftSubTree = false; 85 | if (left != null) { 86 | inLeftSubTree = left.find(key); 87 | } 88 | 89 | boolean inRightSubTree = false; 90 | if (!inLeftSubTree && right != null) { 91 | inRightSubTree = right.find(key); 92 | } 93 | 94 | return (inLeftSubTree | inRightSubTree); 95 | } 96 | 97 | /* 98 | * check of node1 & node2 are children of the same parent 99 | */ 100 | public boolean areSiblings(int node1, int node2) { 101 | boolean status = false; 102 | 103 | if (left != null && right != null) { 104 | if (left.value == node1 && right.value == node2) 105 | status = true; 106 | } 107 | 108 | if (!status && left != null) { 109 | status = left.areSiblings(node1, node2); 110 | } 111 | 112 | if (!status && right != null) { 113 | status = right.areSiblings(node1, node2); 114 | } 115 | 116 | return status; 117 | } 118 | 119 | /* 120 | * helper function for areCousins. 121 | * find the level number of node in tree 122 | */ 123 | public int findLevel(int node) { 124 | int level = -1; 125 | if (value == node) { 126 | level = 0; 127 | } else { 128 | int levelLeft = -1; 129 | int levelRight = -1; 130 | 131 | if (left != null) 132 | levelLeft = left.findLevel(node); 133 | if (levelLeft != -1 && right != null) 134 | levelRight = right.findLevel(node); 135 | 136 | level = 1 + Math.max(levelLeft, levelRight); 137 | } 138 | return level; 139 | } 140 | 141 | /* 142 | * check if node1 & node2 are cousins (nodes at the same level but 143 | * not siblings). 144 | */ 145 | public boolean areCousins(int node1, int node2) { 146 | int node1Level = findLevel(node1); 147 | int node2Level = findLevel(node2); 148 | boolean status = false; 149 | 150 | if (node1Level == node2Level) { 151 | if (!areSiblings(node1, node2)) 152 | status = true; 153 | else 154 | status = false; 155 | } 156 | return status; 157 | } 158 | 159 | 160 | /* 161 | * find lowest common ancestor of node1 & node2 162 | */ 163 | public int closestCommonAncestor(int node1, int node2) { 164 | if (value == node1 || value == node2) 165 | return value; 166 | 167 | int valLeft = -1, valRight = -1; 168 | if (left != null) { 169 | valLeft = left.closestCommonAncestor(node1, node2); 170 | } 171 | 172 | if (right != null) { 173 | valRight = right.closestCommonAncestor(node1, node2); 174 | } 175 | 176 | if (valLeft != -1 && valRight != -1) { 177 | return value; 178 | } else if (valLeft != -1) { 179 | return valLeft; 180 | } else { 181 | return valRight; 182 | } 183 | } 184 | } 185 | 186 | class BinTree2Tester { 187 | public static void main(String[] args) { 188 | BinTree2 node4 = new BinTree2(4, null, null); 189 | BinTree2 node6 = new BinTree2(6, null, null); 190 | BinTree2 node5 = new BinTree2(5, null, null); 191 | BinTree2 node7 = new BinTree2(7, null, null); 192 | BinTree2 node2 = new BinTree2(2, node4, node6); 193 | BinTree2 node3 = new BinTree2(3, node5, node7); 194 | BinTree2 node1 = new BinTree2(1, node2, node3); 195 | 196 | 197 | System.out.println("find(3) : " + node1.find(3)); 198 | System.out.println("numberOfNodes() : " + node1.numberOfNodes()); 199 | System.out.println("totalValue() : " + node1.totalValue()); 200 | System.out.println("node3.isDescendent(5) : " + node3.isDescendent(5)); 201 | System.out.println("node2.isDescendent(7) : " + node2.isDescendent(7)); 202 | System.out.println("areSiblings(2, 3) : " + node1.areSiblings(2, 3)); 203 | System.out.println("areSiblings(4, 3) : " + node1.areSiblings(4, 3)); 204 | System.out.println("areCousins(4, 5) : " + node1.areCousins(4, 5)); 205 | System.out.println("areCousins(4, 6) : " + node1.areCousins(4, 6)); 206 | System.out.println("closestCommonAncestor(4, 5) : " + node1.closestCommonAncestor(4, 5)); 207 | System.out.println("closestCommonAncestor(4, 2) : " + node1.closestCommonAncestor(4, 2)); 208 | System.out.println("closestCommonAncestor(3, 6) : " + node1.closestCommonAncestor(3, 6)); 209 | 210 | /* 211 | * OUTPUT 212 | * find(3) : true 213 | * numberOfNodes() : 7 214 | * totalValue() : 28 215 | * node3.isDescendent(5) : true 216 | * node2.isDescendent(7) : false 217 | * areSiblings(2, 3) : true 218 | * areSiblings(4, 3) : false 219 | * areCousins(4, 5) : true 220 | * areCousins(4, 6) : false 221 | * closestCommonAncestor(4, 5) : 1 222 | * closestCommonAncestor(4, 2) : 2 223 | * closestCommonAncestor(3, 6) : 1 224 | */ 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /solutions/assignment3/Q2.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class Q2 { 4 | public static void main(String[] args) { 5 | Circle c = new Circle(); 6 | Square s = new Square(); 7 | System.out.println("Area of circle with radius 5: " + c.area(5)); 8 | System.out.println("Area of square with side 5: " + s.area(5)); 9 | } 10 | 11 | } 12 | 13 | class Circle { 14 | public float area(float radius) { 15 | return 3.14F * radius * radius; 16 | } 17 | } 18 | 19 | class Square { 20 | public float area(float side) { 21 | return side * side; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/assignment3/Q3.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class Q3 { 4 | public static void main(String[] args) { 5 | Circle c = new Circle(); 6 | c.radius = 5; 7 | System.out.println("Area of circle with radius 5: " + c.area()); 8 | 9 | Square s = new Square(); 10 | s.side = 5; 11 | System.out.println("Area of square with side 5: " + s.area()); 12 | } 13 | 14 | } 15 | 16 | class Circle { 17 | public float radius; 18 | 19 | public float area() { 20 | return 3.14F * radius * radius; 21 | } 22 | } 23 | 24 | class Square { 25 | public float side; 26 | 27 | public float area() { 28 | return side * side; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /solutions/assignment3/Q4.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class Q4 { 4 | public static void main(String[] args) { 5 | Circle c = new Circle(5); 6 | System.out.println("Area of circle with radius 5: " + c.area()); 7 | 8 | Square s = new Square(5); 9 | System.out.println("Area of square with side 5: " + s.area()); 10 | } 11 | 12 | } 13 | 14 | class Circle { 15 | public float radius; 16 | 17 | public Circle(float r) { 18 | radius = r; 19 | } 20 | 21 | public float area() { 22 | return 3.14F * radius * radius; 23 | } 24 | } 25 | 26 | class Square { 27 | public float side; 28 | 29 | public Square(float s) { 30 | side = s; 31 | } 32 | 33 | public float area() { 34 | return side * side; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /solutions/assignment4/Q2/Circle.java: -------------------------------------------------------------------------------- 1 | 2 | public class Circle { 3 | /* 4 | * private : we do not want users to access the radius directly 5 | * final : once set, the radius is assumed to not change (you can omit this if your assumptions are different) 6 | * non-static : static fields are shared across instances. Here radius is unique to each instance and is non-static. 7 | */ 8 | private final float radius; 9 | 10 | public Circle(float r) { 11 | /* 12 | * a final variable can only be initialized once but it need not be initialized at the time of declaration. 13 | * This is called a blank final variable. A blank final instance variable of a class must definitely be initialized 14 | * by the end of every constructor of the class in which it is declared 15 | */ 16 | radius = r; 17 | } 18 | 19 | public float area() { 20 | return 3.14F * radius * radius; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/assignment4/Q2/Square.java: -------------------------------------------------------------------------------- 1 | 2 | public class Square { 3 | /* 4 | * private : we do not want users to access the side directly 5 | * final : once set, the side is assumed to not change (you can omit this if your assumptions are different) 6 | * non-static : static fields are shared across instances. Here side is unique to each instance and is non-static. 7 | */ 8 | private final float side; 9 | 10 | public Square(float s) { 11 | /* 12 | * a final variable can only be initialized once but it need not be initialized at the time of declaration. 13 | * This is called a blank final variable. A blank final instance variable of a class must definitely be initialized 14 | * by the end of every constructor of the class in which it is declared. 15 | */ 16 | side = s; 17 | } 18 | 19 | public float area() { 20 | return side * side; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /solutions/assignment4/Q3/Circle.java: -------------------------------------------------------------------------------- 1 | package shapes.circle; 2 | 3 | public class Circle { 4 | /* 5 | * private : we do not want users to access the radius directly 6 | * final : once set, the radius is assumed to not change (you can omit this if your assumptions are different) 7 | * non-static : static fields are shared across instances. Here radius is unique to each instance and is non-static. 8 | */ 9 | private final float radius; 10 | 11 | public Circle(float r) { 12 | /* 13 | * a final variable can only be initialized once but it need not be initialized at the time of declaration. 14 | * This is called a blank final variable. A blank final instance variable of a class must definitely be initialized 15 | * by the end of every constructor of the class in which it is declared 16 | */ 17 | radius = r; 18 | } 19 | 20 | public float area() { 21 | return 3.14F * radius * radius; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/assignment4/Q3/Square.java: -------------------------------------------------------------------------------- 1 | package shapes.square; 2 | 3 | public class Square { 4 | /* 5 | * private : we do not want users to access the side directly 6 | * final : once set, the side is assumed to not change (you can omit this if your assumptions are different) 7 | * non-static : static fields are shared across instances. Here side is unique to each instance and is non-static. 8 | */ 9 | private final float side; 10 | 11 | public Square(float s) { 12 | /* 13 | * a final variable can only be initialized once but it need not be initialized at the time of declaration. 14 | * This is called a blank final variable. A blank final instance variable of a class must definitely be initialized 15 | * by the end of every constructor of the class in which it is declared. 16 | */ 17 | side = s; 18 | } 19 | 20 | public float area() { 21 | return side * side; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /solutions/assignment4/Q3/Tester.java: -------------------------------------------------------------------------------- 1 | import shapes.circle.*; 2 | import shapes.square.*; 3 | 4 | public class Tester { 5 | public static void main(String[] args) { 6 | Circle c = new Circle(3); 7 | System.out.println(c.area()); 8 | 9 | Square s = new Square(5); 10 | System.out.println(s.area()); 11 | 12 | } 13 | } 14 | 15 | 16 | -------------------------------------------------------------------------------- /solutions/assignment4/Q3/TesterCircle.java: -------------------------------------------------------------------------------- 1 | package shapes.circle; 2 | 3 | public class TesterCircle { 4 | public static void main(String[] args) { 5 | Circle c = new Circle(3); 6 | System.out.println(c.area()); 7 | 8 | } 9 | } 10 | 11 | 12 | -------------------------------------------------------------------------------- /solutions/assignment4/Q3/TesterSquare.java: -------------------------------------------------------------------------------- 1 | package shapes.square; 2 | 3 | public class TesterSquare { 4 | public static void main(String[] args) { 5 | Square s = new Square(5); 6 | System.out.println(s.area()); 7 | 8 | } 9 | } 10 | 11 | 12 | -------------------------------------------------------------------------------- /solutions/assignment4/Q3/classes/Tester.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/solutions/assignment4/Q3/classes/Tester.class -------------------------------------------------------------------------------- /solutions/assignment4/Q3/classes/shapes/circle/Circle.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/solutions/assignment4/Q3/classes/shapes/circle/Circle.class -------------------------------------------------------------------------------- /solutions/assignment4/Q3/classes/shapes/circle/TesterCircle.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/solutions/assignment4/Q3/classes/shapes/circle/TesterCircle.class -------------------------------------------------------------------------------- /solutions/assignment4/Q3/classes/shapes/square/Square.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/solutions/assignment4/Q3/classes/shapes/square/Square.class -------------------------------------------------------------------------------- /solutions/assignment4/Q3/classes/shapes/square/TesterSquare.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crunchbang/Java_TA_Codes/73bce11e0fc489f522a642de46af60218dc43722/solutions/assignment4/Q3/classes/shapes/square/TesterSquare.class -------------------------------------------------------------------------------- /solutions/assignment4/README.md: -------------------------------------------------------------------------------- 1 | ### Working with multiple files 2 | 3 | ``` 4 | Q3 5 | ├── Circle.java 6 | ├── Square.java 7 | ├── Tester.java 8 | ├── TesterCircle.java 9 | ├── TesterSquare.java 10 | └── classes 11 | ├── Tester.class 12 | └── shapes 13 | ├── circle 14 | │   ├── Circle.class 15 | │   └── TesterCircle.class 16 | └── square 17 | ├── Square.class 18 | └── TesterSquare.class 19 | 20 | 4 directories, 10 files 21 | 22 | ``` 23 | 24 | ### Compilation 25 | We'll compile the java files and direct the compiler to put the compiled class files within the `classes` folder. 26 | 27 | Compile the files as follows: 28 | 29 | `javac -d classes Circle.java`\ 30 | `javac -d classes Square.java` 31 | 32 | The `-d` option tells the compiler to put the compiled class files within the `classes ` directory according to the package structure. The directory structure within `classes` folder is automatically created by the compiler based on the package declaration at the top of each file. A package declaraion of `shapes.circle` in `Circles.java` translates to a directory structure of `shapes/circle/Circle.class` after compilation. 33 | 34 | When creating a testing class, you can choose to include it in the same package or not. 35 | 36 | **Same Package** 37 | 38 | Here `TesterCircle.java` and `TesterSquare.java` are part of the respective packages. \ 39 | **NOTE**: Packages within the same class can see other and can refer to each without importing the package i.e `TesterCircle` can directly refer to `Circle` without any extra imports. Same goes for `Square` and `TesterSquare`. 40 | 41 | Compile the tester files as follows: 42 | 43 | `javac -d classes -cp classes TesterCircle.java`\ 44 | `javac -d classes -cp classes TesterSquare.java` 45 | 46 | The `-cp` option is used to tell the compiler where to find the class files for the user defined classes, `Circle` and `Square` in this case. When compiling a file that references user defined classes, the `-cp` option should be used to tell the compiler where to look for these classes (so that the compiler can resolve these references). Otherwise you'll get a compile time error message saying that the class you're refering to does not exist. 47 | If the `-cp` option is not specified, the compiler will search the current directory for the referenced classes.\ 48 | *Extra*: It is similar to search path in gcc where you use the `-I` flag to specify the search path. 49 | 50 | Go into the classes folder and run the tester files as follows:\ 51 | `cd classes` 52 | 53 | `java shapes.square.TesterSquare`\ 54 | `java shapes.circle.TesterCircle` 55 | 56 | Here we did not have to specify the classpath because the compiler searches the specified directory i.e `shapes/square/` to resolve the reference to `Square` class and it succeeds. 57 | 58 | **Different Package** 59 | `Tester` is another testing class which is not part of any of the above packages. In order to test the classes, it imports the appropriate classes and then uses them. Based on the discussion above, the class can be compiled as follows: 60 | 61 | `javac -d classes -cp classes Tester.java` 62 | 63 | And it can be run as follows:\ 64 | `cd classes`\ 65 | `java Tester` 66 | 67 | I hope you can understand why we did not have to specify the `-cp` option in the above command. 68 | 69 | **Aside**: If you had compiled the files as follows `javac -cp classes Tester.java`, i.e the class file will be in the same directory as the source file, then you would have had to use `java -cp classes Tester` to run the program. Take a moment. See if you understand why it is so. 70 | 71 | -------------------------------------------------------------------------------- /solutions/assignment6/Q2.java: -------------------------------------------------------------------------------- 1 | 2 | class Animal { 3 | public void walk() { 4 | System.out.println("I'm walking"); 5 | } 6 | } 7 | 8 | class Bird extends Animal { 9 | public void fly() { 10 | System.out.println("I'm flying"); 11 | } 12 | } 13 | 14 | class Q2 { 15 | public static void main(String[] args) { 16 | Bird b = new Bird(); 17 | 18 | b.walk(); 19 | b.fly(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /solutions/assignment6/Q3.java: -------------------------------------------------------------------------------- 1 | 2 | class Rectangle { 3 | public final float length, breadth; 4 | 5 | public Rectangle(float l, float b) { 6 | length = l; 7 | breadth = b; 8 | } 9 | 10 | } 11 | 12 | class Square extends Rectangle { 13 | 14 | public Square(float side) { 15 | super(side, side); 16 | } 17 | 18 | } 19 | 20 | class Point extends Rectangle { 21 | 22 | public Point() { 23 | super(0, 0); 24 | } 25 | } 26 | 27 | class Q3 { 28 | public static void main(String[] args) { 29 | Rectangle[] rectArray = new Rectangle[3]; 30 | 31 | rectArray[0] = new Rectangle(10, 20); 32 | rectArray[1] = new Square(10); 33 | rectArray[2] = new Point(); 34 | 35 | for(Rectangle r : rectArray) { 36 | System.out.println("Area : " + r.length * r.breadth); 37 | } 38 | 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /solutions/assignment6/Q4.java: -------------------------------------------------------------------------------- 1 | 2 | class Account { 3 | protected float balance; 4 | 5 | public Account(float initial) { 6 | balance = initial; 7 | } 8 | 9 | public float getBalance() { 10 | return balance; 11 | } 12 | 13 | public boolean withdraw(float amount) { 14 | boolean status; 15 | 16 | if (balance - amount < 0) { 17 | status = false; 18 | } else { 19 | balance -= amount; 20 | status = true; 21 | } 22 | return status; 23 | } 24 | 25 | public boolean deposit(float amount) { 26 | boolean status; 27 | 28 | if (amount < 0) { 29 | status = false; 30 | } else { 31 | balance += amount; 32 | status = true; 33 | } 34 | return status; 35 | } 36 | } 37 | 38 | class SavingsAccount extends Account { 39 | 40 | private float interest; 41 | 42 | public SavingsAccount(float initial, float interest) { 43 | super(initial); 44 | this.interest = interest; 45 | } 46 | 47 | public boolean addInterest() { 48 | float interestAmt = (getBalance() * interest) / 100; 49 | boolean status = super.deposit(interestAmt); 50 | return status; 51 | } 52 | } 53 | 54 | class CurrentAccount extends Account { 55 | private final float overdraftLimit; 56 | 57 | public CurrentAccount(float initial, float limit) { 58 | super(initial); 59 | overdraftLimit = limit; 60 | } 61 | 62 | /* 63 | * Check if the amount to be withdrawn is within 64 | * the overdraft limit. If yes, allow; Deny otherwise. 65 | */ 66 | @Override 67 | public boolean withdraw(float amount) { 68 | float excess = getBalance() - amount; 69 | boolean status; 70 | if (Math.abs(excess) < overdraftLimit) { 71 | balance -= amount; 72 | status = true; 73 | } else { 74 | status = false; 75 | } 76 | return status; 77 | 78 | } 79 | 80 | } 81 | 82 | class Q4 { 83 | public static void main(String[] args) { 84 | Account a1 = new Account(100); 85 | System.out.println("Account with balance 100"); 86 | System.out.println("Balance: " + a1.getBalance()); 87 | 88 | if (a1.deposit(20)) { 89 | System.out.println("Deposited 20.\nBalance: " + a1.getBalance()); 90 | } else { 91 | System.out.println("Deposit failed"); 92 | } 93 | 94 | if (a1.withdraw(20)) { 95 | System.out.println("Rs.20 withdrawn.\nBalance: " + a1.getBalance()); 96 | } else { 97 | System.out.println("Withdraw failed. Insufficient balance."); 98 | } 99 | 100 | if (a1.withdraw(1000)) { 101 | System.out.println("Rs.1000 withdrawn.\nBalance: " + a1.getBalance()); 102 | } else { 103 | System.out.println("Withdraw of Rs.1000 failed. Insufficient balance."); 104 | } 105 | 106 | System.out.println(); 107 | SavingsAccount a2 = new SavingsAccount(100, 10); 108 | System.out.println("Savings account with balance 100 & interest 10% created"); 109 | if (a2.addInterest()) { 110 | System.out.println("Interest added.\nBalance: " + a2.getBalance()); 111 | } else { 112 | System.out.println("Error adding interest."); 113 | } 114 | 115 | System.out.println(); 116 | CurrentAccount a3 = new CurrentAccount(100, 500); 117 | System.out.println("Current account with balance 100 & overdraft limit 500 created"); 118 | if (a3.withdraw(400)) { 119 | System.out.println("Rs.400 withdrawn.\nBalance: " + a3.getBalance()); 120 | } else { 121 | System.out.println("Withdraw failed. Exceeds overdraft limit."); 122 | } 123 | 124 | if (a3.withdraw(100)) { 125 | System.out.println("Rs.100 withdrawn.\nBalance: " + a3.getBalance()); 126 | } else { 127 | System.out.println("Withdraw failed. Exceeds overdraft limit."); 128 | } 129 | 130 | if (a3.withdraw(200)) { 131 | System.out.println("Rs.200 withdrawn.\nBalance: " + a3.getBalance()); 132 | } else { 133 | System.out.println("Withdraw failed. Exceeds overdraft limit."); 134 | } 135 | 136 | /* 137 | * OUTPUT 138 | * 139 | * Account with balance 100 140 | * Balance: 100.0 141 | * Deposited 20. 142 | * Balance: 120.0 143 | * Rs.20 withdrawn. 144 | * Balance: 100.0 145 | * Withdraw of Rs.1000 failed. Insufficient balance. 146 | 147 | * Savings account with balance 100 & interest 10% created 148 | * Interest added. 149 | * Balance: 110.0 150 | 151 | * Current account with balance 100 & overdraft limit 500 created 152 | * Rs.400 withdrawn. 153 | * Balance: -300.0 154 | * Rs.100 withdrawn. 155 | * Balance: -400.0 156 | * Withdraw failed. Exceeds overdraft limit. 157 | */ 158 | 159 | 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /solutions/assignment7/Q2.java: -------------------------------------------------------------------------------- 1 | 2 | abstract class Animal { 3 | protected final String species; 4 | 5 | public Animal(String species) { 6 | this.species = species; 7 | } 8 | 9 | public abstract void move(); 10 | } 11 | 12 | class Bird extends Animal { 13 | 14 | public Bird() { 15 | super("Bird"); 16 | } 17 | 18 | @Override 19 | public void move() { 20 | System.out.println("Bird flying"); 21 | } 22 | } 23 | 24 | class Fish extends Animal { 25 | 26 | public Fish() { 27 | super("Fish"); 28 | } 29 | 30 | @Override 31 | public void move() { 32 | System.out.println("Fish swimming"); 33 | } 34 | } 35 | 36 | class Q2 { 37 | public static void main(String[] args) { 38 | Animal b = new Bird(); 39 | b.move(); 40 | 41 | Animal f = new Fish(); 42 | f.move(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /solutions/assignment7/Q3.java: -------------------------------------------------------------------------------- 1 | 2 | interface Shape { 3 | 4 | float area(); 5 | } 6 | 7 | class Rectangle implements Shape { 8 | private final float length, breadth; 9 | 10 | public Rectangle(float l, float b) { 11 | length = l; 12 | breadth = b; 13 | } 14 | 15 | @Override 16 | public float area() { 17 | return length * breadth; 18 | } 19 | 20 | } 21 | 22 | class Circle implements Shape { 23 | private final float radius; 24 | 25 | public Circle(float radius) { 26 | this.radius = radius; 27 | } 28 | 29 | @Override 30 | public float area() { 31 | return 3.14F * radius * radius; 32 | } 33 | } 34 | 35 | class Q3 { 36 | public static void main(String[] args) { 37 | Shape[] shapeArray = new Shape[3]; 38 | 39 | shapeArray[0] = new Rectangle(10, 20); 40 | shapeArray[1] = new Rectangle(1, 200); 41 | shapeArray[2] = new Circle(10.3F); 42 | 43 | for(Shape s : shapeArray) { 44 | System.out.println("Area : " + s.area()); 45 | } 46 | 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /solutions/assignment7/Q4.java: -------------------------------------------------------------------------------- 1 | 2 | abstract class Account { 3 | protected float balance; 4 | 5 | public Account(float initial) { 6 | balance = initial; 7 | } 8 | 9 | public float getBalance() { 10 | return balance; 11 | } 12 | 13 | public abstract boolean withdraw(float amount); 14 | 15 | public abstract boolean deposit(float amount); 16 | } 17 | 18 | class SavingsAccount extends Account { 19 | 20 | private float interest; 21 | 22 | public SavingsAccount(float initial, float interest) { 23 | super(initial); 24 | this.interest = interest; 25 | } 26 | 27 | @Override 28 | public boolean withdraw(float amount) { 29 | boolean status; 30 | 31 | if (balance - amount < 0) { 32 | status = false; 33 | } else { 34 | balance -= amount; 35 | status = true; 36 | } 37 | return status; 38 | } 39 | 40 | @Override 41 | public boolean deposit(float amount) { 42 | boolean status; 43 | 44 | if (amount < 0) { 45 | status = false; 46 | } else { 47 | balance += amount; 48 | status = true; 49 | } 50 | return status; 51 | } 52 | 53 | public boolean addInterest() { 54 | float interestAmt = (balance * interest) / 100; 55 | boolean status = deposit(interestAmt); 56 | return status; 57 | } 58 | } 59 | 60 | class CurrentAccount extends Account { 61 | private final float overdraftLimit; 62 | 63 | public CurrentAccount(float initial, float limit) { 64 | super(initial); 65 | overdraftLimit = limit; 66 | } 67 | 68 | @Override 69 | public boolean deposit(float amount) { 70 | boolean status; 71 | 72 | if (amount < 0) { 73 | status = false; 74 | } else { 75 | balance += amount; 76 | status = true; 77 | } 78 | return status; 79 | } 80 | 81 | /* 82 | * Check if the amount to be withdrawn is within 83 | * the overdraft limit. If yes, allow; Deny otherwise. 84 | */ 85 | @Override 86 | public boolean withdraw(float amount) { 87 | float excess = getBalance() - amount; 88 | boolean status; 89 | if (Math.abs(excess) < overdraftLimit) { 90 | balance -= amount; 91 | status = true; 92 | } else { 93 | status = false; 94 | } 95 | return status; 96 | 97 | } 98 | 99 | } 100 | 101 | class Q4 { 102 | public static void main(String[] args) { 103 | SavingsAccount a2 = new SavingsAccount(100, 10); 104 | System.out.println("Savings account with balance 100 & interest 10% created"); 105 | if (a2.addInterest()) { 106 | System.out.println("Interest added.\nBalance: " + a2.getBalance()); 107 | } else { 108 | System.out.println("Error adding interest."); 109 | } 110 | 111 | System.out.println(); 112 | CurrentAccount a3 = new CurrentAccount(100, 500); 113 | System.out.println("Current account with balance 100 & overdraft limit 500 created"); 114 | if (a3.withdraw(400)) { 115 | System.out.println("Rs.400 withdrawn.\nBalance: " + a3.getBalance()); 116 | } else { 117 | System.out.println("Withdraw failed. Exceeds overdraft limit."); 118 | } 119 | 120 | if (a3.withdraw(100)) { 121 | System.out.println("Rs.100 withdrawn.\nBalance: " + a3.getBalance()); 122 | } else { 123 | System.out.println("Withdraw failed. Exceeds overdraft limit."); 124 | } 125 | 126 | if (a3.withdraw(200)) { 127 | System.out.println("Rs.200 withdrawn.\nBalance: " + a3.getBalance()); 128 | } else { 129 | System.out.println("Withdraw failed. Exceeds overdraft limit."); 130 | } 131 | 132 | /* 133 | * OUTPUT 134 | * 135 | * Savings account with balance 100 & interest 10% created 136 | * Interest added. 137 | * Balance: 110.0 138 | * 139 | * Current account with balance 100 & overdraft limit 500 created 140 | * Rs.400 withdrawn. 141 | * Balance: -300.0 142 | * Rs.100 withdrawn. 143 | * Balance: -400.0 144 | * Withdraw failed. Exceeds overdraft limit. 145 | */ 146 | 147 | 148 | } 149 | } 150 | --------------------------------------------------------------------------------